World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#2705] feat(core): Add the relational backend for User Entity (#2850)
lwyang008adb4b7710
diff --git a/core/src/main/java/com/datastrato/gravitino/authorization/AuthorizationUtils.java b/core/src/main/java/com/datastrato/gravitino/authorization/AuthorizationUtils.javaindex d6ded111e3..05475abc9f 100644--- a/core/src/main/java/com/datastrato/gravitino/authorization/AuthorizationUtils.java+++ b/core/src/main/java/com/datastrato/gravitino/authorization/AuthorizationUtils.java@@ -17,7 +17,7 @@ import org.slf4j.Logger;import org.slf4j.LoggerFactory;/* The utilization class of authorization module*/-class AuthorizationUtils {+public class AuthorizationUtils {static final String USER_DOES_NOT_EXIST_MSG = "User %s does not exist in th metalake %s";static final String GROUP_DOES_NOT_EXIST_MSG = "Group %s does not exist in th metalake %s";diff --git a/core/src/main/java/com/datastrato/gravitino/storage/relational/JDBCBackend.java b/core/src/main/java/com/datastrato/gravitino/storage/relational/JDBCBackend.javaindex 14a0df4fca..9d884fa808 100644--- a/core/src/main/java/com/datastrato/gravitino/storage/relational/JDBCBackend.java+++ b/core/src/main/java/com/datastrato/gravitino/storage/relational/JDBCBackend.java@@ -18,16 +18,20 @@ import com.datastrato.gravitino.exceptions.NoSuchEntityException;import com.datastrato.gravitino.meta.BaseMetalake;import com.datastrato.gravitino.meta.CatalogEntity;import com.datastrato.gravitino.meta.FilesetEntity;+import com.datastrato.gravitino.meta.RoleEntity;import com.datastrato.gravitino.meta.SchemaEntity;import com.datastrato.gravitino.meta.TableEntity;import com.datastrato.gravitino.meta.TopicEntity;+import com.datastrato.gravitino.meta.UserEntity;import com.datastrato.gravitino.storage.relational.converters.SQLExceptionConverterFactory;import com.datastrato.gravitino.storage.relational.service.CatalogMetaService;import com.datastrato.gravitino.storage.relational.service.FilesetMetaService;import com.datastrato.gravitino.storage.relational.service.MetalakeMetaService;+import com.datastrato.gravitino.storage.relational.service.RoleMetaService;import com.datastrato.gravitino.storage.relational.service.SchemaMetaService;import com.datastrato.gravitino.storage.relational.service.TableMetaService;import com.datastrato.gravitino.storage.relational.service.TopicMetaService;+import com.datastrato.gravitino.storage.relational.service.UserMetaService;import com.datastrato.gravitino.storage.relational.session.SqlSessionFactoryHelper;import java.io.IOException;import java.util.List;@@ -95,6 +99,10 @@ public class JDBCBackend implements RelationalBackend {FilesetMetaService.getInstance().insertFileset((FilesetEntity) e, overwritten);} else if (e instanceof TopicEntity) {TopicMetaService.getInstance().insertTopic((TopicEntity) e, overwritten);+ } else if (e instanceof UserEntity) {+ UserMetaService.getInstance().insertUser((UserEntity) e, overwritten);+ } else if (e instanceof RoleEntity) {+ RoleMetaService.getInstance().insertRole((RoleEntity) e, overwritten);} else {throw new UnsupportedEntityTypeException("Unsupported entity type: %s for insert operation", e.getClass());@@ -118,6 +126,8 @@ public class JDBCBackend implements RelationalBackend {return (E) FilesetMetaService.getInstance().updateFileset(ident, updater);case TOPIC:return (E) TopicMetaService.getInstance().updateTopic(ident, updater);+ case USER:+ return (E) UserMetaService.getInstance().updateUser(ident, updater);default:throw new UnsupportedEntityTypeException("Unsupported entity type: %s for update operation", entityType);@@ -140,6 +150,8 @@ public class JDBCBackend implements RelationalBackend {return (E) FilesetMetaService.getInstance().getFilesetByIdentifier(ident);case TOPIC:return (E) TopicMetaService.getInstance().getTopicByIdentifier(ident);+ case USER:+ return (E) UserMetaService.getInstance().getUserByIdentifier(ident);default:throw new UnsupportedEntityTypeException("Unsupported entity type: %s for get operation", entityType);@@ -161,6 +173,8 @@ public class JDBCBackend implements RelationalBackend {return FilesetMetaService.getInstance().deleteFileset(ident);case TOPIC:return TopicMetaService.getInstance().deleteTopic(ident);+ case USER:+ return UserMetaService.getInstance().deleteUser(ident);default:throw new UnsupportedEntityTypeException("Unsupported entity type: %s for delete operation", entityType);diff --git a/core/src/main/java/com/datastrato/gravitino/storage/relational/mapper/RoleMetaMapper.java b/core/src/main/java/com/datastrato/gravitino/storage/relational/mapper/RoleMetaMapper.javanew file mode 100644index 0000000000..f9732d040e--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/storage/relational/mapper/RoleMetaMapper.java@@ -0,0 +1,99 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.storage.relational.mapper;++import com.datastrato.gravitino.storage.relational.po.RolePO;+import java.util.List;+import org.apache.ibatis.annotations.Insert;+import org.apache.ibatis.annotations.Param;+import org.apache.ibatis.annotations.Select;++/**+ * A MyBatis Mapper for table meta operation SQLs.+ *+ * <p>This interface class is a specification defined by MyBatis. It requires this interface class+ * to identify the corresponding SQLs for execution. We can write SQLs in an additional XML file, or+ * write SQLs with annotations in this interface Mapper. See: <a+ * href="https://mybatis.org/mybatis-3/getting-started.html"></a>+ */+public interface RoleMetaMapper {+ String ROLE_TABLE_NAME = "role_meta";+ String RELATION_TABLE_NAME = "user_role_rel";++ @Select(+ "SELECT role_id as roleId FROM "+ + ROLE_TABLE_NAME+ + " WHERE metalake_id = #{metalakeId} AND role_name = #{roleName}"+ + " AND deleted_at = 0")+ Long selectRoleIdByMetalakeIdAndName(+ @Param("metalakeId") Long metalakeId, @Param("roleName") String name);++ @Select(+ "SELECT ro.role_id as roleId, ro.role_name as roleName,"+ + " ro.metalake_id as metalakeId, ro.properties as properties,"+ + " ro.securable_object as securableObject, ro.privileges as privileges,"+ + " ro.audit_info as auditInfo, ro.current_version as currentVersion,"+ + " ro.last_version as lastVersion, ro.deleted_at as deletedAt"+ + " FROM "+ + ROLE_TABLE_NAME+ + " ro JOIN "+ + RELATION_TABLE_NAME+ + " re ON ro.role_id = re.role_id"+ + " WHERE re.user_id = #{userId}"+ + " AND ro.deleted_at = 0 AND re.deleted_at = 0")+ List<RolePO> listRolesByUserId(@Param("userId") Long userId);++ @Insert(+ "INSERT INTO "+ + ROLE_TABLE_NAME+ + "(role_id, role_name,"+ + " metalake_id, properties,"+ + " securable_object, privileges,"+ + " audit_info, current_version, last_version, deleted_at)"+ + " VALUES("+ + " #{roleMeta.roleId},"+ + " #{roleMeta.roleName},"+ + " #{roleMeta.metalakeId},"+ + " #{roleMeta.properties},"+ + " #{roleMeta.securableObject},"+ + " #{roleMeta.privileges},"+ + " #{roleMeta.auditInfo},"+ + " #{roleMeta.currentVersion},"+ + " #{roleMeta.lastVersion},"+ + " #{roleMeta.deletedAt}"+ + " )")+ void insertRoleMeta(@Param("roleMeta") RolePO rolePO);++ @Insert(+ "INSERT INTO "+ + ROLE_TABLE_NAME+ + "(role_id, role_name,"+ + " metalake_id, properties,"+ + " securable_object, privileges,"+ + " audit_info, current_version, last_version, deleted_at)"+ + " VALUES("+ + " #{roleMeta.roleId},"+ + " #{roleMeta.roleName},"+ + " #{roleMeta.metalakeId},"+ + " #{roleMeta.properties},"+ + " #{roleMeta.securableObject},"+ + " #{roleMeta.privileges},"+ + " #{roleMeta.auditInfo},"+ + " #{roleMeta.currentVersion},"+ + " #{roleMeta.lastVersion},"+ + " #{roleMeta.deletedAt}"+ + " ) ON DUPLICATE KEY UPDATE"+ + " role_name = #{roleMeta.roleName},"+ + " metalake_id = #{roleMeta.metalakeId},"+ + " properties = #{roleMeta.properties},"+ + " securable_object = #{roleMeta.securableObject},"+ + " privileges = #{roleMeta.privileges},"+ + " audit_info = #{roleMeta.auditInfo},"+ + " current_version = #{roleMeta.currentVersion},"+ + " last_version = #{roleMeta.lastVersion},"+ + " deleted_at = #{roleMeta.deletedAt}")+ void insertRoleMetaOnDuplicateKeyUpdate(@Param("roleMeta") RolePO rolePO);+}diff --git a/core/src/main/java/com/datastrato/gravitino/storage/relational/mapper/UserMetaMapper.java b/core/src/main/java/com/datastrato/gravitino/storage/relational/mapper/UserMetaMapper.javanew file mode 100644index 0000000000..83b94fa24c--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/storage/relational/mapper/UserMetaMapper.java@@ -0,0 +1,119 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.storage.relational.mapper;++import com.datastrato.gravitino.storage.relational.po.UserPO;+import org.apache.ibatis.annotations.Insert;+import org.apache.ibatis.annotations.Param;+import org.apache.ibatis.annotations.Select;+import org.apache.ibatis.annotations.Update;++/**+ * A MyBatis Mapper for table meta operation SQLs.+ *+ * <p>This interface class is a specification defined by MyBatis. It requires this interface class+ * to identify the corresponding SQLs for execution. We can write SQLs in an additional XML file, or+ * write SQLs with annotations in this interface Mapper. See: <a+ * href="https://mybatis.org/mybatis-3/getting-started.html"></a>+ */+public interface UserMetaMapper {+ String TABLE_NAME = "user_meta";++ @Select(+ "SELECT user_id as userId FROM "+ + TABLE_NAME+ + " WHERE metalake_id = #{metalakeId} AND user_name = #{userName}"+ + " AND deleted_at = 0")+ Long selectUserIdByMetalakeIdAndName(+ @Param("metalakeId") Long metalakeId, @Param("userName") String name);++ @Select(+ "SELECT user_id as userId, user_name as userName,"+ + " metalake_id as metalakeId,"+ + " audit_info as auditInfo,"+ + " current_version as currentVersion, last_version as lastVersion,"+ + " deleted_at as deletedAt"+ + " FROM "+ + TABLE_NAME+ + " WHERE metalake_id = #{metalakeId} AND user_name = #{userName}"+ + " AND deleted_at = 0")+ UserPO selectUserMetaByMetalakeIdAndName(+ @Param("metalakeId") Long metalakeId, @Param("userName") String name);++ @Insert(+ "INSERT INTO "+ + TABLE_NAME+ + "(user_id, user_name,"+ + " metalake_id, audit_info,"+ + " current_version, last_version, deleted_at)"+ + " VALUES("+ + " #{userMeta.userId},"+ + " #{userMeta.userName},"+ + " #{userMeta.metalakeId},"+ + " #{userMeta.auditInfo},"+ + " #{userMeta.currentVersion},"+ + " #{userMeta.lastVersion},"+ + " #{userMeta.deletedAt}"+ + " )")+ void insertUserMeta(@Param("userMeta") UserPO userPO);++ @Insert(+ "INSERT INTO "+ + TABLE_NAME+ + "(user_id, user_name,"+ + "metalake_id, audit_info,"+ + " current_version, last_version, deleted_at)"+ + " VALUES("+ + " #{userMeta.userId},"+ + " #{userMeta.userName},"+ + " #{userMeta.metalakeId},"+ + " #{userMeta.auditInfo},"+ + " #{userMeta.currentVersion},"+ + " #{userMeta.lastVersion},"+ + " #{userMeta.deletedAt}"+ + " )"+ + " ON DUPLICATE KEY UPDATE"+ + " user_name = #{userMeta.userName},"+ + " metalake_id = #{userMeta.metalakeId},"+ + " audit_info = #{userMeta.auditInfo},"+ + " current_version = #{userMeta.currentVersion},"+ + " last_version = #{userMeta.lastVersion},"+ + " deleted_at = #{userMeta.deletedAt}")+ void insertUserMetaOnDuplicateKeyUpdate(@Param("userMeta") UserPO userPO);++ @Update(+ "UPDATE "+ + TABLE_NAME+ + " SET deleted_at = UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000.0"+ + " WHERE user_id = #{userId} AND deleted_at = 0")+ void softDeleteUserMetaByUserId(@Param("userId") Long userId);++ @Update(+ "UPDATE "+ + TABLE_NAME+ + " SET deleted_at = UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000.0"+ + " WHERE metalake_id = #{metalakeId} AND deleted_at = 0")+ void softDeleteUserMetasByMetalakeId(@Param("metalakeId") Long metalakeId);++ @Update(+ "UPDATE "+ + TABLE_NAME+ + " SET user_name = #{newUserMeta.userName},"+ + " metalake_id = #{newUserMeta.metalakeId},"+ + " audit_info = #{newUserMeta.auditInfo},"+ + " current_version = #{newUserMeta.currentVersion},"+ + " last_version = #{newUserMeta.lastVersion},"+ + " deleted_at = #{newUserMeta.deletedAt}"+ + " WHERE user_id = #{oldUserMeta.userId}"+ + " AND user_name = #{oldUserMeta.userName}"+ + " AND metalake_id = #{oldUserMeta.metalakeId}"+ + " AND audit_info = #{oldUserMeta.auditInfo}"+ + " AND current_version = #{oldUserMeta.currentVersion}"+ + " AND last_version = #{oldUserMeta.lastVersion}"+ + " AND deleted_at = 0")+ Integer updateUserMeta(+ @Param("newUserMeta") UserPO newUserPO, @Param("oldUserMeta") UserPO oldUserPO);+}diff --git a/core/src/main/java/com/datastrato/gravitino/storage/relational/mapper/UserRoleRelMapper.java b/core/src/main/java/com/datastrato/gravitino/storage/relational/mapper/UserRoleRelMapper.javanew file mode 100644index 0000000000..637a34753f--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/storage/relational/mapper/UserRoleRelMapper.java@@ -0,0 +1,105 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.storage.relational.mapper;++import com.datastrato.gravitino.storage.relational.po.UserRoleRelPO;+import java.util.List;+import org.apache.ibatis.annotations.Insert;+import org.apache.ibatis.annotations.Param;+import org.apache.ibatis.annotations.Update;++/**+ * A MyBatis Mapper for table meta operation SQLs.+ *+ * <p>This interface class is a specification defined by MyBatis. It requires this interface class+ * to identify the corresponding SQLs for execution. We can write SQLs in an additional XML file, or+ * write SQLs with annotations in this interface Mapper. See: <a+ * href="https://mybatis.org/mybatis-3/getting-started.html"></a>+ */+public interface UserRoleRelMapper {+ String RELATION_TABLE_NAME = "user_role_rel";+ String USER_TABLE_NAME = "user_meta";++ @Insert({+ "<script>",+ "INSERT INTO "+ + RELATION_TABLE_NAME+ + "(user_id, role_id,"+ + " audit_info,"+ + " current_version, last_version, deleted_at)"+ + " VALUES ",+ "<foreach collection='userRoleRels' item='item' separator=','>",+ "(#{item.userId},"+ + " #{item.roleId},"+ + " #{item.auditInfo},"+ + " #{item.currentVersion},"+ + " #{item.lastVersion},"+ + " #{item.deletedAt})",+ "</foreach>",+ "</script>"+ })+ void batchInsertUserRoleRel(@Param("userRoleRels") List<UserRoleRelPO> userRoleRelPOs);++ @Insert({+ "<script>",+ "INSERT INTO "+ + RELATION_TABLE_NAME+ + "(user_id, role_id,"+ + " audit_info,"+ + " current_version, last_version, deleted_at)"+ + " VALUES ",+ "<foreach collection='userRoleRels' item='item' separator=','>",+ "(#{item.userId},"+ + " #{item.roleId},"+ + " #{item.auditInfo},"+ + " #{item.currentVersion},"+ + " #{item.lastVersion},"+ + " #{item.deletedAt})",+ "</foreach>",+ " ON DUPLICATE KEY UPDATE"+ + " user_id = VALUES(user_id),"+ + " role_id = VALUES(role_id),"+ + " audit_info = VALUES(audit_info),"+ + " current_version = VALUES(current_version),"+ + " last_version = VALUES(last_version),"+ + " deleted_at = VALUES(deleted_at)",+ "</script>"+ })+ void batchInsertUserRoleRelOnDuplicateKeyUpdate(+ @Param("userRoleRels") List<UserRoleRelPO> userRoleRelPOs);++ @Update(+ "UPDATE "+ + RELATION_TABLE_NAME+ + " SET deleted_at = UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000.0"+ + " WHERE user_id = #{userId} AND deleted_at = 0")+ void softDeleteUserRoleRelByUserId(@Param("userId") Long userId);++ @Update({+ "<script>",+ "UPDATE "+ + RELATION_TABLE_NAME+ + " SET deleted_at = UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000.0"+ + " WHERE user_id = #{userId} AND role_id in (",+ "<foreach collection='roleIds' item='roleId' separator=','>",+ "#{roleId}",+ "</foreach>",+ ") " + "AND deleted_at = 0",+ "</script>"+ })+ void softDeleteUserRoleRelByUserAndRoles(+ @Param("userId") Long userId, @Param("roleIds") List<Long> roleIds);++ @Update(+ "UPDATE "+ + RELATION_TABLE_NAME+ + " SET deleted_at = UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000.0"+ + " WHERE user_id IN (SELECT user_id FROM "+ + USER_TABLE_NAME+ + " WHERE metalake_id = #{metalakeId} AND deleted_at = 0)"+ + " AND deleted_at = 0")+ void softDeleteUserRoleRelByMetalakeId(Long metalakeId);+}diff --git a/core/src/main/java/com/datastrato/gravitino/storage/relational/po/RolePO.java b/core/src/main/java/com/datastrato/gravitino/storage/relational/po/RolePO.javanew file mode 100644index 0000000000..721e30a561--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/storage/relational/po/RolePO.java@@ -0,0 +1,182 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.gravitino.storage.relational.po;++import com.google.common.base.Objects;+import com.google.common.base.Preconditions;++public class RolePO {+ private Long roleId;+ private String roleName;+ private Long metalakeId;+ private String properties;+ private String securableObject;+ private String privileges;+ private String auditInfo;+ private Long currentVersion;+ private Long lastVersion;+ private Long deletedAt;++ public Long getRoleId() {+ return roleId;+ }++ public String getRoleName() {+ return roleName;+ }++ public Long getMetalakeId() {+ return metalakeId;+ }++ public String getProperties() {+ return properties;+ }++ public String getSecurableObject() {+ return securableObject;+ }++ public String getPrivileges() {+ return privileges;+ }++ public String getAuditInfo() {+ return auditInfo;+ }++ public Long getCurrentVersion() {+ return currentVersion;+ }++ public Long getLastVersion() {+ return lastVersion;+ }++ public Long getDeletedAt() {+ return deletedAt;+ }++ @Override+ public boolean equals(Object o) {+ if (this == o) {+ return true;+ }+ if (!(o instanceof RolePO)) {+ return false;+ }+ RolePO tablePO = (RolePO) o;+ return Objects.equal(getRoleId(), tablePO.getRoleId())+ && Objects.equal(getRoleName(), tablePO.getRoleName())+ && Objects.equal(getMetalakeId(), tablePO.getMetalakeId())+ && Objects.equal(getProperties(), tablePO.getProperties())+ && Objects.equal(getSecurableObject(), tablePO.getSecurableObject())+ && Objects.equal(getPrivileges(), tablePO.getPrivileges())+ && Objects.equal(getAuditInfo(), tablePO.getAuditInfo())+ && Objects.equal(getCurrentVersion(), tablePO.getCurrentVersion())+ && Objects.equal(getLastVersion(), tablePO.getLastVersion())+ && Objects.equal(getDeletedAt(), tablePO.getDeletedAt());+ }++ @Override+ public int hashCode() {+ return Objects.hashCode(+ getRoleId(),+ getRoleName(),+ getMetalakeId(),+ getProperties(),+ getSecurableObject(),+ getPrivileges(),+ getAuditInfo(),+ getCurrentVersion(),+ getLastVersion(),+ getDeletedAt());+ }++ public static class Builder {+ private final RolePO rolePO;++ private Builder() {+ rolePO = new RolePO();+ }++ public Builder withRoleId(Long roleId) {+ rolePO.roleId = roleId;+ return this;+ }++ public Builder withRoleName(String roleName) {+ rolePO.roleName = roleName;+ return this;+ }++ public Builder withMetalakeId(Long metalakeId) {+ rolePO.metalakeId = metalakeId;+ return this;+ }++ public Builder withProperties(String properties) {+ rolePO.properties = properties;+ return this;+ }++ public Builder withSecurableObject(String securableObject) {+ rolePO.securableObject = securableObject;+ return this;+ }++ public Builder withPrivileges(String privileges) {+ rolePO.privileges = privileges;+ return this;+ }++ public Builder withAuditInfo(String auditInfo) {+ rolePO.auditInfo = auditInfo;+ return this;+ }++ public Builder withCurrentVersion(Long currentVersion) {+ rolePO.currentVersion = currentVersion;+ return this;+ }++ public Builder withLastVersion(Long lastVersion) {+ rolePO.lastVersion = lastVersion;+ return this;+ }++ public Builder withDeletedAt(Long deletedAt) {+ rolePO.deletedAt = deletedAt;+ return this;+ }++ private void validate() {+ Preconditions.checkArgument(rolePO.roleId != null, "Role id is required");+ Preconditions.checkArgument(rolePO.roleName != null, "Role name is required");+ Preconditions.checkArgument(rolePO.metalakeId != null, "Metalake id is required");+ Preconditions.checkArgument(rolePO.properties != null, "Properties is required");+ Preconditions.checkArgument(rolePO.securableObject != null, "Securable object is required");+ Preconditions.checkArgument(rolePO.privileges != null, "Privileges is required");+ Preconditions.checkArgument(rolePO.auditInfo != null, "Audit info is required");+ Preconditions.checkArgument(rolePO.currentVersion != null, "Current version is required");+ Preconditions.checkArgument(rolePO.lastVersion != null, "Last version is required");+ Preconditions.checkArgument(rolePO.deletedAt != null, "Deleted at is required");+ }++ public RolePO build() {+ validate();+ return rolePO;+ }+ }++ /**+ * Creates a new instance of {@link Builder}.+ *+ * @return The new instance.+ */+ public static Builder builder() {+ return new Builder();+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/storage/relational/po/UserPO.java b/core/src/main/java/com/datastrato/gravitino/storage/relational/po/UserPO.javanew file mode 100644index 0000000000..cf22bf3432--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/storage/relational/po/UserPO.java@@ -0,0 +1,143 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.gravitino.storage.relational.po;++import com.google.common.base.Objects;+import com.google.common.base.Preconditions;++public class UserPO {+ private Long userId;+ private String userName;+ private Long metalakeId;+ private String auditInfo;+ private Long currentVersion;+ private Long lastVersion;+ private Long deletedAt;++ public Long getUserId() {+ return userId;+ }++ public String getUserName() {+ return userName;+ }++ public Long getMetalakeId() {+ return metalakeId;+ }++ public String getAuditInfo() {+ return auditInfo;+ }++ public Long getCurrentVersion() {+ return currentVersion;+ }++ public Long getLastVersion() {+ return lastVersion;+ }++ public Long getDeletedAt() {+ return deletedAt;+ }++ @Override+ public boolean equals(Object o) {+ if (this == o) {+ return true;+ }+ if (!(o instanceof UserPO)) {+ return false;+ }+ UserPO tablePO = (UserPO) o;+ return Objects.equal(getUserId(), tablePO.getUserId())+ && Objects.equal(getUserName(), tablePO.getUserName())+ && Objects.equal(getMetalakeId(), tablePO.getMetalakeId())+ && Objects.equal(getAuditInfo(), tablePO.getAuditInfo())+ && Objects.equal(getCurrentVersion(), tablePO.getCurrentVersion())+ && Objects.equal(getLastVersion(), tablePO.getLastVersion())+ && Objects.equal(getDeletedAt(), tablePO.getDeletedAt());+ }++ @Override+ public int hashCode() {+ return Objects.hashCode(+ getUserId(),+ getUserName(),+ getMetalakeId(),+ getAuditInfo(),+ getCurrentVersion(),+ getLastVersion(),+ getDeletedAt());+ }++ public static class Builder {+ private final UserPO userPO;++ private Builder() {+ userPO = new UserPO();+ }++ public Builder withUserId(Long userId) {+ userPO.userId = userId;+ return this;+ }++ public Builder withUserName(String userName) {+ userPO.userName = userName;+ return this;+ }++ public Builder withMetalakeId(Long metalakeId) {+ userPO.metalakeId = metalakeId;+ return this;+ }++ public Builder withAuditInfo(String auditInfo) {+ userPO.auditInfo = auditInfo;+ return this;+ }++ public Builder withCurrentVersion(Long currentVersion) {+ userPO.currentVersion = currentVersion;+ return this;+ }++ public Builder withLastVersion(Long lastVersion) {+ userPO.lastVersion = lastVersion;+ return this;+ }++ public Builder withDeletedAt(Long deletedAt) {+ userPO.deletedAt = deletedAt;+ return this;+ }++ private void validate() {+ Preconditions.checkArgument(userPO.userId != null, "User id is required");+ Preconditions.checkArgument(userPO.userName != null, "User name is required");+ Preconditions.checkArgument(userPO.metalakeId != null, "Metalake id is required");+ Preconditions.checkArgument(userPO.auditInfo != null, "Audit info is required");+ Preconditions.checkArgument(userPO.currentVersion != null, "Current version is required");+ Preconditions.checkArgument(userPO.lastVersion != null, "Last version is required");+ Preconditions.checkArgument(userPO.deletedAt != null, "Deleted at is required");+ }++ public UserPO build() {+ validate();+ return userPO;+ }+ }++ /**+ * Creates a new instance of {@link Builder}.+ *+ * @return The new instance.+ */+ public static Builder builder() {+ return new Builder();+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/storage/relational/po/UserRoleRelPO.java b/core/src/main/java/com/datastrato/gravitino/storage/relational/po/UserRoleRelPO.javanew file mode 100644index 0000000000..48e225a7ac--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/storage/relational/po/UserRoleRelPO.java@@ -0,0 +1,131 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.gravitino.storage.relational.po;++import com.google.common.base.Objects;+import com.google.common.base.Preconditions;++public class UserRoleRelPO {+ private Long userId;+ private Long roleId;+ private String auditInfo;+ private Long currentVersion;+ private Long lastVersion;+ private Long deletedAt;++ public Long getUserId() {+ return userId;+ }++ public Long getRoleId() {+ return roleId;+ }++ public String getAuditInfo() {+ return auditInfo;+ }++ public Long getCurrentVersion() {+ return currentVersion;+ }++ public Long getLastVersion() {+ return lastVersion;+ }++ public Long getDeletedAt() {+ return deletedAt;+ }++ @Override+ public boolean equals(Object o) {+ if (this == o) {+ return true;+ }+ if (!(o instanceof UserRoleRelPO)) {+ return false;+ }+ UserRoleRelPO userRoleRelPO = (UserRoleRelPO) o;+ return Objects.equal(getUserId(), userRoleRelPO.getUserId())+ && Objects.equal(getRoleId(), userRoleRelPO.getRoleId())+ && Objects.equal(getAuditInfo(), userRoleRelPO.getAuditInfo())+ && Objects.equal(getCurrentVersion(), userRoleRelPO.getCurrentVersion())+ && Objects.equal(getLastVersion(), userRoleRelPO.getLastVersion())+ && Objects.equal(getDeletedAt(), userRoleRelPO.getDeletedAt());+ }++ @Override+ public int hashCode() {+ return Objects.hashCode(+ getUserId(),+ getRoleId(),+ getAuditInfo(),+ getCurrentVersion(),+ getLastVersion(),+ getDeletedAt());+ }++ public static class Builder {+ private final UserRoleRelPO userRoleRelPO;++ private Builder() {+ userRoleRelPO = new UserRoleRelPO();+ }++ public Builder withUserId(Long userId) {+ userRoleRelPO.userId = userId;+ return this;+ }++ public Builder withRoleId(Long roleId) {+ userRoleRelPO.roleId = roleId;+ return this;+ }++ public Builder withAuditInfo(String auditInfo) {+ userRoleRelPO.auditInfo = auditInfo;+ return this;+ }++ public Builder withCurrentVersion(Long currentVersion) {+ userRoleRelPO.currentVersion = currentVersion;+ return this;+ }++ public Builder withLastVersion(Long lastVersion) {+ userRoleRelPO.lastVersion = lastVersion;+ return this;+ }++ public Builder withDeletedAt(Long deletedAt) {+ userRoleRelPO.deletedAt = deletedAt;+ return this;+ }++ private void validate() {+ Preconditions.checkArgument(userRoleRelPO.userId != null, "User id is required");+ Preconditions.checkArgument(userRoleRelPO.roleId != null, "Role id is required");+ Preconditions.checkArgument(userRoleRelPO.auditInfo != null, "Audit info is required");+ Preconditions.checkArgument(+ userRoleRelPO.currentVersion != null, "Current version is required");+ Preconditions.checkArgument(userRoleRelPO.lastVersion != null, "Last version is required");+ Preconditions.checkArgument(userRoleRelPO.deletedAt != null, "Deleted at is required");+ }++ public UserRoleRelPO build() {+ validate();+ return userRoleRelPO;+ }+ }++ /**+ * Creates a new instance of {@link Builder}.+ *+ * @return The new instance.+ */+ public static Builder builder() {+ return new Builder();+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/storage/relational/service/MetalakeMetaService.java b/core/src/main/java/com/datastrato/gravitino/storage/relational/service/MetalakeMetaService.javaindex 7c76ab4ebb..c35dd23c50 100644--- a/core/src/main/java/com/datastrato/gravitino/storage/relational/service/MetalakeMetaService.java+++ b/core/src/main/java/com/datastrato/gravitino/storage/relational/service/MetalakeMetaService.java@@ -20,6 +20,8 @@ import com.datastrato.gravitino.storage.relational.mapper.MetalakeMetaMapper;import com.datastrato.gravitino.storage.relational.mapper.SchemaMetaMapper;import com.datastrato.gravitino.storage.relational.mapper.TableMetaMapper;import com.datastrato.gravitino.storage.relational.mapper.TopicMetaMapper;+import com.datastrato.gravitino.storage.relational.mapper.UserMetaMapper;+import com.datastrato.gravitino.storage.relational.mapper.UserRoleRelMapper;import com.datastrato.gravitino.storage.relational.po.MetalakePO;import com.datastrato.gravitino.storage.relational.utils.ExceptionUtils;import com.datastrato.gravitino.storage.relational.utils.POConverters;@@ -170,7 +172,15 @@ public class MetalakeMetaService {() ->SessionUtils.doWithoutCommit(TopicMetaMapper.class,- mapper -> mapper.softDeleteTopicMetasByMetalakeId(metalakeId)));+ mapper -> mapper.softDeleteTopicMetasByMetalakeId(metalakeId)),+ () ->+ SessionUtils.doWithoutCommit(+ UserRoleRelMapper.class,+ mapper -> mapper.softDeleteUserRoleRelByMetalakeId(metalakeId)),+ () ->+ SessionUtils.doWithoutCommit(+ UserMetaMapper.class,+ mapper -> mapper.softDeleteUserMetasByMetalakeId(metalakeId)));} else {List<CatalogEntity> catalogEntities =CatalogMetaService.getInstance()@@ -179,9 +189,19 @@ public class MetalakeMetaService {throw new NonEmptyEntityException("Entity %s has sub-entities, you should remove sub-entities first", ident);}- SessionUtils.doWithCommit(- MetalakeMetaMapper.class,- mapper -> mapper.softDeleteMetalakeMetaByMetalakeId(metalakeId));+ SessionUtils.doMultipleWithCommit(+ () ->+ SessionUtils.doWithoutCommit(+ MetalakeMetaMapper.class,+ mapper -> mapper.softDeleteMetalakeMetaByMetalakeId(metalakeId)),+ () ->+ SessionUtils.doWithoutCommit(+ UserRoleRelMapper.class,+ mapper -> mapper.softDeleteUserRoleRelByMetalakeId(metalakeId)),+ () ->+ SessionUtils.doWithoutCommit(+ UserMetaMapper.class,+ mapper -> mapper.softDeleteUserMetasByMetalakeId(metalakeId)));}}return true;diff --git a/core/src/main/java/com/datastrato/gravitino/storage/relational/service/RoleMetaService.java b/core/src/main/java/com/datastrato/gravitino/storage/relational/service/RoleMetaService.javanew file mode 100644index 0000000000..c0656628c9--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/storage/relational/service/RoleMetaService.java@@ -0,0 +1,77 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.gravitino.storage.relational.service;++import com.datastrato.gravitino.Entity;+import com.datastrato.gravitino.exceptions.NoSuchEntityException;+import com.datastrato.gravitino.meta.RoleEntity;+import com.datastrato.gravitino.storage.relational.mapper.RoleMetaMapper;+import com.datastrato.gravitino.storage.relational.po.RolePO;+import com.datastrato.gravitino.storage.relational.utils.ExceptionUtils;+import com.datastrato.gravitino.storage.relational.utils.POConverters;+import com.datastrato.gravitino.storage.relational.utils.SessionUtils;+import com.google.common.base.Preconditions;+import java.util.List;++/** The service class for role metadata. It provides the basic database operations for role. */+public class RoleMetaService {+ private static final RoleMetaService INSTANCE = new RoleMetaService();++ public static RoleMetaService getInstance() {+ return INSTANCE;+ }++ private RoleMetaService() {}++ public Long getRoleIdByMetalakeIdAndName(Long metalakeId, String roleName) {+ Long roleId =+ SessionUtils.getWithoutCommit(+ RoleMetaMapper.class,+ mapper -> mapper.selectRoleIdByMetalakeIdAndName(metalakeId, roleName));++ if (roleId == null) {+ throw new NoSuchEntityException(+ NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,+ Entity.EntityType.ROLE.name().toLowerCase(),+ roleName);+ }+ return roleId;+ }++ public List<RolePO> listRolesByUserId(Long userId) {+ return SessionUtils.getWithoutCommit(+ RoleMetaMapper.class, mapper -> mapper.listRolesByUserId(userId));+ }++ public void insertRole(RoleEntity roleEntity, boolean overwritten) {+ try {+ Preconditions.checkArgument(+ roleEntity.namespace() != null+ && !roleEntity.namespace().isEmpty()+ && roleEntity.namespace().levels().length == 3,+ "The identifier should not be null and should have three level.");++ Long metalakeId =+ MetalakeMetaService.getInstance().getMetalakeIdByName(roleEntity.namespace().level(0));+ RolePO.Builder builder = RolePO.builder().withMetalakeId(metalakeId);+ RolePO rolePO = POConverters.initializeRolePOWithVersion(roleEntity, builder);++ SessionUtils.doWithCommit(+ RoleMetaMapper.class,+ mapper -> {+ if (overwritten) {+ mapper.insertRoleMetaOnDuplicateKeyUpdate(rolePO);+ } else {+ mapper.insertRoleMeta(rolePO);+ }+ });++ } catch (RuntimeException re) {+ ExceptionUtils.checkSQLException(+ re, Entity.EntityType.ROLE, roleEntity.nameIdentifier().toString());+ throw re;+ }+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/storage/relational/service/UserMetaService.java b/core/src/main/java/com/datastrato/gravitino/storage/relational/service/UserMetaService.javanew file mode 100644index 0000000000..cc1de84a19--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/storage/relational/service/UserMetaService.java@@ -0,0 +1,226 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.gravitino.storage.relational.service;++import com.datastrato.gravitino.Entity;+import com.datastrato.gravitino.HasIdentifier;+import com.datastrato.gravitino.NameIdentifier;+import com.datastrato.gravitino.exceptions.NoSuchEntityException;+import com.datastrato.gravitino.meta.UserEntity;+import com.datastrato.gravitino.storage.relational.mapper.UserMetaMapper;+import com.datastrato.gravitino.storage.relational.mapper.UserRoleRelMapper;+import com.datastrato.gravitino.storage.relational.po.RolePO;+import com.datastrato.gravitino.storage.relational.po.UserPO;+import com.datastrato.gravitino.storage.relational.po.UserRoleRelPO;+import com.datastrato.gravitino.storage.relational.utils.ExceptionUtils;+import com.datastrato.gravitino.storage.relational.utils.POConverters;+import com.datastrato.gravitino.storage.relational.utils.SessionUtils;+import com.google.common.base.Preconditions;+import com.google.common.collect.Lists;+import com.google.common.collect.Sets;+import java.util.List;+import java.util.Objects;+import java.util.Optional;+import java.util.Set;+import java.util.function.Function;+import java.util.stream.Collectors;++/** The service class for user metadata. It provides the basic database operations for user. */+public class UserMetaService {+ private static final UserMetaService INSTANCE = new UserMetaService();++ public static UserMetaService getInstance() {+ return INSTANCE;+ }++ private UserMetaService() {}++ private UserPO getUserPOByMetalakeIdAndName(Long metalakeId, String userName) {+ UserPO userPO =+ SessionUtils.getWithoutCommit(+ UserMetaMapper.class,+ mapper -> mapper.selectUserMetaByMetalakeIdAndName(metalakeId, userName));++ if (userPO == null) {+ throw new NoSuchEntityException(+ NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,+ Entity.EntityType.USER.name().toLowerCase(),+ userName);+ }+ return userPO;+ }++ private Long getUserIdByMetalakeIdAndName(Long metalakeId, String userName) {+ Long userId =+ SessionUtils.getWithoutCommit(+ UserMetaMapper.class,+ mapper -> mapper.selectUserIdByMetalakeIdAndName(metalakeId, userName));++ if (userId == null) {+ throw new NoSuchEntityException(+ NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,+ Entity.EntityType.USER.name().toLowerCase(),+ userName);+ }+ return userId;+ }++ public UserEntity getUserByIdentifier(NameIdentifier identifier) {+ Preconditions.checkArgument(+ identifier != null+ && !identifier.namespace().isEmpty()+ && identifier.namespace().levels().length == 3,+ "The identifier should not be null and should have three level.");+ Long metalakeId =+ MetalakeMetaService.getInstance().getMetalakeIdByName(identifier.namespace().level(0));+ UserPO userPO = getUserPOByMetalakeIdAndName(metalakeId, identifier.name());+ List<RolePO> rolePOs = RoleMetaService.getInstance().listRolesByUserId(userPO.getUserId());++ return POConverters.fromUserPO(userPO, rolePOs, identifier.namespace());+ }++ public void insertUser(UserEntity userEntity, boolean overwritten) {+ try {+ Preconditions.checkArgument(+ userEntity.namespace() != null+ && !userEntity.namespace().isEmpty()+ && userEntity.namespace().levels().length == 3,+ "The identifier should not be null and should have three level.");++ Long metalakeId =+ MetalakeMetaService.getInstance().getMetalakeIdByName(userEntity.namespace().level(0));+ UserPO.Builder builder = UserPO.builder().withMetalakeId(metalakeId);+ UserPO userPO = POConverters.initializeUserPOWithVersion(userEntity, builder);++ List<Long> roleIds = userEntity.roleIds();+ if (roleIds == null) {+ roleIds =+ Optional.ofNullable(userEntity.roleNames()).orElse(Lists.newArrayList()).stream()+ .map(+ roleName ->+ RoleMetaService.getInstance()+ .getRoleIdByMetalakeIdAndName(metalakeId, roleName))+ .collect(Collectors.toList());+ }+ List<UserRoleRelPO> userRoleRelPOs =+ POConverters.initializeUserRoleRelsPOWithVersion(userEntity, roleIds);++ SessionUtils.doMultipleWithCommit(+ () ->+ SessionUtils.doWithoutCommit(+ UserMetaMapper.class,+ mapper -> {+ if (overwritten) {+ mapper.insertUserMetaOnDuplicateKeyUpdate(userPO);+ } else {+ mapper.insertUserMeta(userPO);+ }+ }),+ () -> {+ if (userRoleRelPOs.isEmpty()) {+ return;+ }+ SessionUtils.doWithoutCommit(+ UserRoleRelMapper.class,+ mapper -> {+ if (overwritten) {+ mapper.batchInsertUserRoleRelOnDuplicateKeyUpdate(userRoleRelPOs);+ } else {+ mapper.batchInsertUserRoleRel(userRoleRelPOs);+ }+ });+ });+ } catch (RuntimeException re) {+ ExceptionUtils.checkSQLException(+ re, Entity.EntityType.USER, userEntity.nameIdentifier().toString());+ throw re;+ }+ }++ public boolean deleteUser(NameIdentifier identifier) {+ Preconditions.checkArgument(+ identifier != null+ && !identifier.namespace().isEmpty()+ && identifier.namespace().levels().length == 3,+ "The identifier should not be null and should have three level.");+ Long metalakeId =+ MetalakeMetaService.getInstance().getMetalakeIdByName(identifier.namespace().level(0));+ Long userId = getUserIdByMetalakeIdAndName(metalakeId, identifier.name());++ SessionUtils.doMultipleWithCommit(+ () ->+ SessionUtils.doWithoutCommit(+ UserMetaMapper.class, mapper -> mapper.softDeleteUserMetaByUserId(userId)),+ () ->+ SessionUtils.doWithoutCommit(+ UserRoleRelMapper.class, mapper -> mapper.softDeleteUserRoleRelByUserId(userId)));+ return true;+ }++ public <E extends Entity & HasIdentifier> UserEntity updateUser(+ NameIdentifier identifier, Function<E, E> updater) {+ Preconditions.checkArgument(+ identifier != null+ && !identifier.namespace().isEmpty()+ && identifier.namespace().levels().length == 3,+ "The identifier should not be null and should have three level.");++ Long metalakeId =+ MetalakeMetaService.getInstance().getMetalakeIdByName(identifier.namespace().level(0));+ UserPO oldUserPO = getUserPOByMetalakeIdAndName(metalakeId, identifier.name());+ List<RolePO> rolePOs = RoleMetaService.getInstance().listRolesByUserId(oldUserPO.getUserId());+ UserEntity oldUserEntity = POConverters.fromUserPO(oldUserPO, rolePOs, identifier.namespace());++ UserEntity newEntity = (UserEntity) updater.apply((E) oldUserEntity);+ Preconditions.checkArgument(+ Objects.equals(oldUserEntity.id(), newEntity.id()),+ "The updated user entity id: %s should be same with the user entity id before: %s",+ newEntity.id(),+ oldUserEntity.id());++ Set<Long> oldRoleIds =+ oldUserEntity.roleIds() == null+ ? Sets.newHashSet()+ : Sets.newHashSet(oldUserEntity.roleIds());+ Set<Long> newRoleIds =+ newEntity.roleIds() == null ? Sets.newHashSet() : Sets.newHashSet(newEntity.roleIds());++ Set<Long> insertRoleIds = Sets.difference(newRoleIds, oldRoleIds);+ Set<Long> deleteRoleIds = Sets.difference(oldRoleIds, newRoleIds);++ if (insertRoleIds.isEmpty() && deleteRoleIds.isEmpty()) {+ return newEntity;+ }+ SessionUtils.doMultipleWithCommit(+ () ->+ SessionUtils.doWithoutCommit(+ UserMetaMapper.class,+ mapper ->+ mapper.updateUserMeta(+ POConverters.updateUserPOWithVersion(oldUserPO, newEntity), oldUserPO)),+ () -> {+ if (insertRoleIds.isEmpty()) {+ return;+ }+ SessionUtils.doWithoutCommit(+ UserRoleRelMapper.class,+ mapper ->+ mapper.batchInsertUserRoleRel(+ POConverters.initializeUserRoleRelsPOWithVersion(+ newEntity, Lists.newArrayList(insertRoleIds))));+ },+ () -> {+ if (deleteRoleIds.isEmpty()) {+ return;+ }+ SessionUtils.doWithoutCommit(+ UserRoleRelMapper.class,+ mapper ->+ mapper.softDeleteUserRoleRelByUserAndRoles(+ newEntity.id(), Lists.newArrayList(deleteRoleIds)));+ });+ return newEntity;+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/storage/relational/session/SqlSessionFactoryHelper.java b/core/src/main/java/com/datastrato/gravitino/storage/relational/session/SqlSessionFactoryHelper.javaindex aa9b6f0f1f..485435e1e8 100644--- a/core/src/main/java/com/datastrato/gravitino/storage/relational/session/SqlSessionFactoryHelper.java+++ b/core/src/main/java/com/datastrato/gravitino/storage/relational/session/SqlSessionFactoryHelper.java@@ -11,9 +11,12 @@ import com.datastrato.gravitino.storage.relational.mapper.CatalogMetaMapper;import com.datastrato.gravitino.storage.relational.mapper.FilesetMetaMapper;import com.datastrato.gravitino.storage.relational.mapper.FilesetVersionMapper;import com.datastrato.gravitino.storage.relational.mapper.MetalakeMetaMapper;+import com.datastrato.gravitino.storage.relational.mapper.RoleMetaMapper;import com.datastrato.gravitino.storage.relational.mapper.SchemaMetaMapper;import com.datastrato.gravitino.storage.relational.mapper.TableMetaMapper;import com.datastrato.gravitino.storage.relational.mapper.TopicMetaMapper;+import com.datastrato.gravitino.storage.relational.mapper.UserMetaMapper;+import com.datastrato.gravitino.storage.relational.mapper.UserRoleRelMapper;import com.google.common.base.Preconditions;import java.sql.SQLException;import java.time.Duration;@@ -86,6 +89,9 @@ public class SqlSessionFactoryHelper {configuration.addMapper(FilesetMetaMapper.class);configuration.addMapper(FilesetVersionMapper.class);configuration.addMapper(TopicMetaMapper.class);+ configuration.addMapper(UserMetaMapper.class);+ configuration.addMapper(RoleMetaMapper.class);+ configuration.addMapper(UserRoleRelMapper.class);// Create the SqlSessionFactory object, it is a singleton objectif (sqlSessionFactory == null) {diff --git a/core/src/main/java/com/datastrato/gravitino/storage/relational/utils/POConverters.java b/core/src/main/java/com/datastrato/gravitino/storage/relational/utils/POConverters.javaindex 2d3a327585..591131071b 100644--- a/core/src/main/java/com/datastrato/gravitino/storage/relational/utils/POConverters.java+++ b/core/src/main/java/com/datastrato/gravitino/storage/relational/utils/POConverters.java@@ -13,18 +13,24 @@ import com.datastrato.gravitino.meta.AuditInfo;import com.datastrato.gravitino.meta.BaseMetalake;import com.datastrato.gravitino.meta.CatalogEntity;import com.datastrato.gravitino.meta.FilesetEntity;+import com.datastrato.gravitino.meta.RoleEntity;import com.datastrato.gravitino.meta.SchemaEntity;import com.datastrato.gravitino.meta.SchemaVersion;import com.datastrato.gravitino.meta.TableEntity;import com.datastrato.gravitino.meta.TopicEntity;+import com.datastrato.gravitino.meta.UserEntity;import com.datastrato.gravitino.storage.relational.po.CatalogPO;import com.datastrato.gravitino.storage.relational.po.FilesetPO;import com.datastrato.gravitino.storage.relational.po.FilesetVersionPO;import com.datastrato.gravitino.storage.relational.po.MetalakePO;+import com.datastrato.gravitino.storage.relational.po.RolePO;import com.datastrato.gravitino.storage.relational.po.SchemaPO;import com.datastrato.gravitino.storage.relational.po.TablePO;import com.datastrato.gravitino.storage.relational.po.TopicPO;+import com.datastrato.gravitino.storage.relational.po.UserPO;+import com.datastrato.gravitino.storage.relational.po.UserRoleRelPO;import com.fasterxml.jackson.core.JsonProcessingException;+import com.google.common.collect.Lists;import java.util.List;import java.util.Map;import java.util.stream.Collectors;@@ -611,4 +617,135 @@ public class POConverters {throw new RuntimeException("Failed to serialize json object:", e);}}++ /**+ * Initialize UserPO+ *+ * @param userEntity UserEntity object+ * @return UserPO object with version initialized+ */+ public static UserPO initializeUserPOWithVersion(UserEntity userEntity, UserPO.Builder builder) {+ try {+ return builder+ .withUserId(userEntity.id())+ .withUserName(userEntity.name())+ .withAuditInfo(JsonUtils.anyFieldMapper().writeValueAsString(userEntity.auditInfo()))+ .withCurrentVersion(INIT_VERSION)+ .withLastVersion(INIT_VERSION)+ .withDeletedAt(DEFAULT_DELETED_AT)+ .build();+ } catch (JsonProcessingException e) {+ throw new RuntimeException("Failed to serialize json object:", e);+ }+ }++ /**+ * Update UserPO version+ *+ * @param oldUserPO the old UserEntity object+ * @param newUser the new TableEntity object+ * @return UserPO object with updated version+ */+ public static UserPO updateUserPOWithVersion(UserPO oldUserPO, UserEntity newUser) {+ Long lastVersion = oldUserPO.getLastVersion();+ // Will set the version to the last version + 1 when having some fields need be multiple version+ Long nextVersion = lastVersion;+ try {+ return UserPO.builder()+ .withUserId(oldUserPO.getUserId())+ .withUserName(newUser.name())+ .withMetalakeId(oldUserPO.getMetalakeId())+ .withAuditInfo(JsonUtils.anyFieldMapper().writeValueAsString(newUser.auditInfo()))+ .withCurrentVersion(nextVersion)+ .withLastVersion(nextVersion)+ .withDeletedAt(DEFAULT_DELETED_AT)+ .build();+ } catch (JsonProcessingException e) {+ throw new RuntimeException("Failed to serialize json object:", e);+ }+ }++ /**+ * Convert {@link UserPO} to {@link UserEntity}+ *+ * @param userPO UserPo object to be converted+ * @param rolePOs list of rolePO+ * @param namespace Namespace object to be associated with the user+ * @return UserEntity object from UserPO object+ */+ public static UserEntity fromUserPO(UserPO userPO, List<RolePO> rolePOs, Namespace namespace) {+ try {+ List<String> roleNames =+ rolePOs.stream().map(RolePO::getRoleName).collect(Collectors.toList());+ List<Long> roleIds = rolePOs.stream().map(RolePO::getRoleId).collect(Collectors.toList());+ return UserEntity.builder()+ .withId(userPO.getUserId())+ .withName(userPO.getUserName())+ .withRoleNames(roleNames.isEmpty() ? null : roleNames)+ .withRoleIds(roleIds.isEmpty() ? null : roleIds)+ .withNamespace(namespace)+ .withAuditInfo(+ JsonUtils.anyFieldMapper().readValue(userPO.getAuditInfo(), AuditInfo.class))+ .build();+ } catch (JsonProcessingException e) {+ throw new RuntimeException("Failed to deserialize json object:", e);+ }+ }++ /**+ * Initialize UserRoleRelPO+ *+ * @param userEntity UserEntity object+ * @param roleIds list of role ids+ * @return UserRoleRelPO object with version initialized+ */+ public static List<UserRoleRelPO> initializeUserRoleRelsPOWithVersion(+ UserEntity userEntity, List<Long> roleIds) {+ try {+ List<UserRoleRelPO> userRoleRelPOs = Lists.newArrayList();+ for (Long roleId : roleIds) {+ UserRoleRelPO roleRelPO =+ UserRoleRelPO.builder()+ .withUserId(userEntity.id())+ .withRoleId(roleId)+ .withAuditInfo(+ JsonUtils.anyFieldMapper().writeValueAsString(userEntity.auditInfo()))+ .withCurrentVersion(INIT_VERSION)+ .withLastVersion(INIT_VERSION)+ .withDeletedAt(DEFAULT_DELETED_AT)+ .build();+ userRoleRelPOs.add(roleRelPO);+ }+ return userRoleRelPOs;+ } catch (JsonProcessingException e) {+ throw new RuntimeException("Failed to serialize json object:", e);+ }+ }++ /**+ * Initialize RolePO+ *+ * @param roleEntity RoleEntity object+ * @return RolePO object with version initialized+ */+ public static RolePO initializeRolePOWithVersion(RoleEntity roleEntity, RolePO.Builder builder) {+ try {+ return builder+ .withRoleId(roleEntity.id())+ .withRoleName(roleEntity.name())+ .withProperties(JsonUtils.anyFieldMapper().writeValueAsString(roleEntity.properties()))+ .withSecurableObject(roleEntity.securableObject().toString())+ .withPrivileges(+ roleEntity.privileges().stream()+ .map(privilege -> privilege.name().toString())+ .collect(Collectors.joining(",")))+ .withAuditInfo(JsonUtils.anyFieldMapper().writeValueAsString(roleEntity.auditInfo()))+ .withCurrentVersion(INIT_VERSION)+ .withLastVersion(INIT_VERSION)+ .withDeletedAt(DEFAULT_DELETED_AT)+ .build();+ } catch (JsonProcessingException e) {+ throw new RuntimeException("Failed to serialize json object:", e);+ }+ }}diff --git a/core/src/test/java/com/datastrato/gravitino/storage/TestEntityStorage.java b/core/src/test/java/com/datastrato/gravitino/storage/TestEntityStorage.javaindex 3bd7cf8a70..c5dcae5e85 100644--- a/core/src/test/java/com/datastrato/gravitino/storage/TestEntityStorage.java+++ b/core/src/test/java/com/datastrato/gravitino/storage/TestEntityStorage.java@@ -28,6 +28,7 @@ import com.datastrato.gravitino.EntityStore;import com.datastrato.gravitino.EntityStoreFactory;import com.datastrato.gravitino.NameIdentifier;import com.datastrato.gravitino.Namespace;+import com.datastrato.gravitino.authorization.AuthorizationUtils;import com.datastrato.gravitino.authorization.Privileges;import com.datastrato.gravitino.authorization.SecurableObjects;import com.datastrato.gravitino.exceptions.AlreadyExistsException;@@ -229,6 +230,8 @@ public class TestEntityStorage {Namespace.of("metalake", "catalog", "schema1"),"topic1",auditInfo);+ UserEntity user1 =+ createUser(RandomIdGenerator.INSTANCE.nextId(), "metalake", "user1", auditInfo);// Store all entitiesstore.put(metalake);@@ -238,6 +241,7 @@ public class TestEntityStorage {store.put(table1);store.put(fileset1);store.put(topic1);+ store.put(user1);Assertions.assertDoesNotThrow(() ->@@ -273,6 +277,13 @@ public class TestEntityStorage {NameIdentifier.of("metalake", "catalog", "schema1", "topic1"),Entity.EntityType.TOPIC,TopicEntity.class));++ Assertions.assertDoesNotThrow(+ () ->+ store.get(+ AuthorizationUtils.ofUser("metalake", "user1"),+ Entity.EntityType.USER,+ UserEntity.class));}// It will automatically close the store we create before, then we reopen the entity store@@ -313,6 +324,12 @@ public class TestEntityStorage {NameIdentifier.of("metalake", "catalog", "schema1", "topic1"),Entity.EntityType.TOPIC,TopicEntity.class));+ Assertions.assertDoesNotThrow(+ () ->+ store.get(+ AuthorizationUtils.ofUser("metalake", "user1"),+ Entity.EntityType.USER,+ UserEntity.class));destroy(type);}}@@ -439,9 +456,9 @@ public class TestEntityStorage {BaseMetalake metalake = createBaseMakeLake(1L, "metalake", auditInfo);store.put(metalake);- UserEntity oneUser = createUser("metalake", "oneUser", auditInfo);+ UserEntity oneUser = createUser(1L, "metalake", "oneUser", auditInfo);store.put(oneUser);- UserEntity anotherUser = createUser("metalake", "anotherUser", auditInfo);+ UserEntity anotherUser = createUser(2L, "metalake", "anotherUser", auditInfo);store.put(anotherUser);GroupEntity oneGroup = createGroup("metalake", "oneGroup", auditInfo);store.put(oneGroup);@@ -510,6 +527,8 @@ public class TestEntityStorage {TopicEntity topic1InSchema2 =createTopicEntity(2L, Namespace.of("metalake", "catalog", "schema2"), "topic1", auditInfo);+ UserEntity user1 = createUser(1L, "metalake", "user1", auditInfo);+ UserEntity user2 = createUser(2L, "metalake", "user2", auditInfo);// Store all entitiesstore.put(metalake);@@ -523,6 +542,8 @@ public class TestEntityStorage {store.put(fileset1InSchema2);store.put(topic1);store.put(topic1InSchema2);+ store.put(user1);+ store.put(user2);validateAllEntityExist(metalake,@@ -536,7 +557,11 @@ public class TestEntityStorage {fileset1,fileset1InSchema2,topic1,- topic1InSchema2);+ topic1InSchema2,+ user1,+ user2);++ validateDeleteUser(store, user1);validateDeleteTable(store, schema2, table1, table1InSchema2);@@ -558,7 +583,7 @@ public class TestEntityStorage {topic1,topic1InSchema2);- validateDeleteMetalake(store, metalake, catalogCopy);+ validateDeleteMetalake(store, metalake, catalogCopy, user2);// Store all entities again// metalake@@ -643,6 +668,9 @@ public class TestEntityStorage {topic1InSchema2.name(),topic1InSchema2.auditInfo());store.put(topic1InSchema2New);+ UserEntity userNew =+ createUser(RandomIdGenerator.INSTANCE.nextId(), "metalake", "userNew", auditInfo);+ store.put(userNew);validateDeleteTableCascade(store, table1New);@@ -654,7 +682,7 @@ public class TestEntityStorage {validateDeleteCatalogCascade(store, catalogNew, schema2New);- validateDeleteMetalakeCascade(store, metalakeNew, catalogNew, schema2New);+ validateDeleteMetalakeCascade(store, metalakeNew, catalogNew, schema2New, userNew);destroy(type);}@@ -1153,14 +1181,14 @@ public class TestEntityStorage {.build();}- private static UserEntity createUser(String metalake, String name, AuditInfo auditInfo) {+ private static UserEntity createUser(Long id, String metalake, String name, AuditInfo auditInfo) {return UserEntity.builder()- .withId(1L)+ .withId(id).withNamespace(Namespace.of(metalake, Entity.SYSTEM_CATALOG_RESERVED_NAME, Entity.USER_SCHEMA_NAME)).withName(name).withAuditInfo(auditInfo)- .withRoleNames(Lists.newArrayList())+ .withRoleNames(null).build();}@@ -1247,8 +1275,14 @@ public class TestEntityStorage {}private void validateDeleteMetalakeCascade(- EntityStore store, BaseMetalake metalake, CatalogEntity catalog, SchemaEntity schema2)+ EntityStore store,+ BaseMetalake metalake,+ CatalogEntity catalog,+ SchemaEntity schema2,+ UserEntity userNew)throws IOException {+ Assertions.assertTrue(store.exists(userNew.nameIdentifier(), Entity.EntityType.USER));+Assertions.assertTrue(store.delete(metalake.nameIdentifier(), Entity.EntityType.METALAKE, true));@@ -1256,6 +1290,7 @@ public class TestEntityStorage {Assertions.assertFalse(store.exists(catalog.nameIdentifier(), Entity.EntityType.CATALOG));Assertions.assertFalse(store.exists(schema2.nameIdentifier(), Entity.EntityType.SCHEMA));Assertions.assertFalse(store.exists(metalake.nameIdentifier(), Entity.EntityType.METALAKE));+ Assertions.assertFalse(store.exists(userNew.nameIdentifier(), Entity.EntityType.USER));}private void validateDeleteCatalogCascade(@@ -1334,8 +1369,11 @@ public class TestEntityStorage {}private static void validateDeleteMetalake(- EntityStore store, BaseMetalake metalake, CatalogEntity catalogCopy) throws IOException {+ EntityStore store, BaseMetalake metalake, CatalogEntity catalogCopy, UserEntity user2)+ throws IOException {// Now delete catalog 'catalogCopy' and metalake+ Assertions.assertTrue(store.exists(user2.nameIdentifier(), Entity.EntityType.USER));+Assertions.assertThrowsExactly(NonEmptyEntityException.class,() -> store.delete(metalake.nameIdentifier(), Entity.EntityType.METALAKE));@@ -1344,6 +1382,7 @@ public class TestEntityStorage {store.delete(metalake.nameIdentifier(), Entity.EntityType.METALAKE);Assertions.assertFalse(store.exists(metalake.nameIdentifier(), Entity.EntityType.METALAKE));+ Assertions.assertFalse(store.exists(user2.nameIdentifier(), Entity.EntityType.USER));}private static void validateDeleteCatalog(@@ -1454,6 +1493,17 @@ public class TestEntityStorage {topic1New, store.get(topic1.nameIdentifier(), Entity.EntityType.TOPIC, TopicEntity.class));}+ private void validateDeleteUser(EntityStore store, UserEntity user1) throws IOException {+ Assertions.assertTrue(store.exists(user1.nameIdentifier(), Entity.EntityType.USER));+ Assertions.assertTrue(store.delete(user1.nameIdentifier(), Entity.EntityType.USER));+ Assertions.assertFalse(store.exists(user1.nameIdentifier(), Entity.EntityType.USER));++ UserEntity user =+ createUser(RandomIdGenerator.INSTANCE.nextId(), "metalake", "user1", user1.auditInfo());+ store.put(user);+ Assertions.assertTrue(store.exists(user.nameIdentifier(), Entity.EntityType.USER));+ }+private void validateDeleteTable(EntityStore store, SchemaEntity schema2, TableEntity table1, TableEntity table1InSchema2)throws IOException {@@ -1490,7 +1540,9 @@ public class TestEntityStorage {FilesetEntity fileset1,FilesetEntity fileset1InSchema2,TopicEntity topic1,- TopicEntity topic1InSchema2)+ TopicEntity topic1InSchema2,+ UserEntity user1,+ UserEntity user2)throws IOException {// Now try to getAssertions.assertEquals(@@ -1523,6 +1575,10 @@ public class TestEntityStorage {Assertions.assertEquals(topic1InSchema2,store.get(topic1InSchema2.nameIdentifier(), Entity.EntityType.TOPIC, TopicEntity.class));+ Assertions.assertEquals(+ user1, store.get(user1.nameIdentifier(), Entity.EntityType.USER, UserEntity.class));+ Assertions.assertEquals(+ user2, store.get(user2.nameIdentifier(), Entity.EntityType.USER, UserEntity.class));}private void validateDeletedFileset(EntityStore store) throws IOException {diff --git a/core/src/test/java/com/datastrato/gravitino/storage/memory/TestMemoryEntityStore.java b/core/src/test/java/com/datastrato/gravitino/storage/memory/TestMemoryEntityStore.javaindex 7f6d6c5172..9ec63ed5c0 100644--- a/core/src/test/java/com/datastrato/gravitino/storage/memory/TestMemoryEntityStore.java+++ b/core/src/test/java/com/datastrato/gravitino/storage/memory/TestMemoryEntityStore.java@@ -24,6 +24,7 @@ import com.datastrato.gravitino.meta.FilesetEntity;import com.datastrato.gravitino.meta.SchemaEntity;import com.datastrato.gravitino.meta.SchemaVersion;import com.datastrato.gravitino.meta.TableEntity;+import com.datastrato.gravitino.meta.UserEntity;import com.datastrato.gravitino.utils.Executable;import com.google.common.collect.Maps;import java.io.IOException;@@ -197,6 +198,15 @@ public class TestMemoryEntityStore {.withAuditInfo(auditInfo).build();+ UserEntity userEntity =+ UserEntity.builder()+ .withId(1L)+ .withName("user")+ .withNamespace(Namespace.of("metalake", "catalog", "db"))+ .withAuditInfo(auditInfo)+ .withRoleNames(null)+ .build();+InMemoryEntityStore store = new InMemoryEntityStore();store.initialize(Mockito.mock(Config.class));store.setSerDe(Mockito.mock(EntitySerDe.class));@@ -206,6 +216,7 @@ public class TestMemoryEntityStore {store.put(schemaEntity);store.put(tableEntity);store.put(filesetEntity);+ store.put(userEntity);Metalake retrievedMetalake =store.get(metalake.nameIdentifier(), EntityType.METALAKE, BaseMetalake.class);@@ -227,6 +238,10 @@ public class TestMemoryEntityStore {store.get(filesetEntity.nameIdentifier(), EntityType.FILESET, FilesetEntity.class);Assertions.assertEquals(filesetEntity, retrievedFileset);+ UserEntity retrievedUser =+ store.get(userEntity.nameIdentifier(), EntityType.USER, UserEntity.class);+ Assertions.assertEquals(userEntity, retrievedUser);+store.delete(metalake.nameIdentifier(), EntityType.METALAKE);NameIdentifier id = metalake.nameIdentifier();Assertions.assertThrows(diff --git a/core/src/test/java/com/datastrato/gravitino/storage/relational/TestJDBCBackend.java b/core/src/test/java/com/datastrato/gravitino/storage/relational/TestJDBCBackend.javaindex 965e604367..4b4a4f31d1 100644--- a/core/src/test/java/com/datastrato/gravitino/storage/relational/TestJDBCBackend.java+++ b/core/src/test/java/com/datastrato/gravitino/storage/relational/TestJDBCBackend.java@@ -19,19 +19,25 @@ import com.datastrato.gravitino.Config;import com.datastrato.gravitino.Configs;import com.datastrato.gravitino.Entity;import com.datastrato.gravitino.Namespace;+import com.datastrato.gravitino.authorization.Privilege;+import com.datastrato.gravitino.authorization.Privileges;+import com.datastrato.gravitino.authorization.SecurableObjects;import com.datastrato.gravitino.exceptions.AlreadyExistsException;import com.datastrato.gravitino.file.Fileset;import com.datastrato.gravitino.meta.AuditInfo;import com.datastrato.gravitino.meta.BaseMetalake;import com.datastrato.gravitino.meta.CatalogEntity;import com.datastrato.gravitino.meta.FilesetEntity;+import com.datastrato.gravitino.meta.RoleEntity;import com.datastrato.gravitino.meta.SchemaEntity;import com.datastrato.gravitino.meta.SchemaVersion;import com.datastrato.gravitino.meta.TableEntity;import com.datastrato.gravitino.meta.TopicEntity;+import com.datastrato.gravitino.meta.UserEntity;import com.datastrato.gravitino.storage.RandomIdGenerator;import com.datastrato.gravitino.storage.relational.session.SqlSessionFactoryHelper;import com.google.common.collect.ImmutableMap;+import com.google.common.collect.Lists;import java.io.File;import java.io.IOException;import java.nio.charset.StandardCharsets;@@ -466,4 +472,41 @@ public class TestJDBCBackend {.withAuditInfo(auditInfo).build();}++ public static UserEntity createUserEntity(+ Long id, Namespace namespace, String name, AuditInfo auditInfo) {+ return UserEntity.builder()+ .withId(id)+ .withName(name)+ .withNamespace(namespace)+ .withRoleNames(null)+ .withRoleIds(null)+ .withAuditInfo(auditInfo)+ .build();+ }++ public static UserEntity createUserEntity(+ Long id, Namespace namespace, String name, AuditInfo auditInfo, List<String> roleNames) {+ return UserEntity.builder()+ .withId(id)+ .withName(name)+ .withNamespace(namespace)+ .withRoleNames(roleNames)+ .withRoleIds(null)+ .withAuditInfo(auditInfo)+ .build();+ }++ public static RoleEntity createRoleEntity(+ Long id, Namespace namespace, String name, AuditInfo auditInfo) {+ return RoleEntity.builder()+ .withId(id)+ .withName(name)+ .withNamespace(namespace)+ .withProperties(null)+ .withAuditInfo(auditInfo)+ .withSecurableObject(SecurableObjects.ofAllCatalogs())+ .withPrivileges(Lists.newArrayList(Privileges.fromName(Privilege.Name.LOAD_CATALOG)))+ .build();+ }}diff --git a/core/src/test/java/com/datastrato/gravitino/storage/relational/service/TestUserMetaService.java b/core/src/test/java/com/datastrato/gravitino/storage/relational/service/TestUserMetaService.javanew file mode 100644index 0000000000..9a509e0dcc--- /dev/null+++ b/core/src/test/java/com/datastrato/gravitino/storage/relational/service/TestUserMetaService.java@@ -0,0 +1,604 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.storage.relational.service;++import com.datastrato.gravitino.authorization.AuthorizationUtils;+import com.datastrato.gravitino.exceptions.AlreadyExistsException;+import com.datastrato.gravitino.exceptions.NoSuchEntityException;+import com.datastrato.gravitino.meta.AuditInfo;+import com.datastrato.gravitino.meta.BaseMetalake;+import com.datastrato.gravitino.meta.RoleEntity;+import com.datastrato.gravitino.meta.UserEntity;+import com.datastrato.gravitino.storage.RandomIdGenerator;+import com.datastrato.gravitino.storage.relational.TestJDBCBackend;+import com.datastrato.gravitino.storage.relational.mapper.RoleMetaMapper;+import com.datastrato.gravitino.storage.relational.po.RolePO;+import com.datastrato.gravitino.storage.relational.utils.SessionUtils;+import com.google.common.collect.Lists;+import com.google.common.collect.Sets;+import java.time.Instant;+import java.util.List;+import java.util.function.Function;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++class TestUserMetaService extends TestJDBCBackend {++ String metalakeName = "metalake";++ @Test+ void getUserByIdentifier() {+ AuditInfo auditInfo =+ AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();++ BaseMetalake metalake =+ createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);+ backend.insert(metalake, false);++ UserMetaService userMetaService = UserMetaService.getInstance();+ RoleMetaService roleMetaService = RoleMetaService.getInstance();++ // get not exist user+ Assertions.assertThrows(+ NoSuchEntityException.class,+ () ->+ userMetaService.getUserByIdentifier(AuthorizationUtils.ofUser(metalakeName, "user1")));++ // get user+ UserEntity user1 =+ createUserEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofUserNamespace(metalakeName),+ "user1",+ auditInfo);+ userMetaService.insertUser(user1, false);+ Assertions.assertEquals(user1, userMetaService.getUserByIdentifier(user1.nameIdentifier()));++ // get user with roles+ RoleEntity role1 =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(metalakeName),+ "role1",+ auditInfo);+ RoleEntity role2 =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(metalakeName),+ "role2",+ auditInfo);+ roleMetaService.insertRole(role1, false);+ roleMetaService.insertRole(role2, false);+ UserEntity user2 =+ createUserEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofUserNamespace(metalakeName),+ "user2",+ auditInfo,+ Lists.newArrayList("role1", "role2"));+ userMetaService.insertUser(user2, false);+ UserEntity actualUser = userMetaService.getUserByIdentifier(user2.nameIdentifier());+ Assertions.assertEquals(user2.name(), actualUser.name());+ Assertions.assertEquals(+ Sets.newHashSet(user2.roleNames()), Sets.newHashSet(actualUser.roleNames()));+ }++ @Test+ void insertUser() {+ AuditInfo auditInfo =+ AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();+ BaseMetalake metalake =+ createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);+ backend.insert(metalake, false);++ UserMetaService userMetaService = UserMetaService.getInstance();+ RoleMetaService roleMetaService = RoleMetaService.getInstance();++ // insert user+ UserEntity user1 =+ createUserEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofUserNamespace(metalakeName),+ "user1",+ auditInfo);+ Assertions.assertThrows(+ NoSuchEntityException.class,+ () -> userMetaService.getUserByIdentifier(user1.nameIdentifier()));+ Assertions.assertDoesNotThrow(() -> userMetaService.insertUser(user1, false));+ Assertions.assertEquals(user1, userMetaService.getUserByIdentifier(user1.nameIdentifier()));++ // insert duplicate user+ UserEntity user1Exist =+ createUserEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofUserNamespace(metalakeName),+ "user1",+ auditInfo);+ Assertions.assertThrows(+ AlreadyExistsException.class, () -> userMetaService.insertUser(user1Exist, false));++ // insert overwrite+ UserEntity user1Overwrite =+ createUserEntity(+ user1.id(),+ AuthorizationUtils.ofUserNamespace(metalakeName),+ "user1Overwrite",+ auditInfo);+ Assertions.assertDoesNotThrow(() -> userMetaService.insertUser(user1Overwrite, true));+ Assertions.assertEquals(+ "user1Overwrite",+ userMetaService.getUserByIdentifier(user1Overwrite.nameIdentifier()).name());+ Assertions.assertEquals(+ user1Overwrite, userMetaService.getUserByIdentifier(user1Overwrite.nameIdentifier()));++ // insert user with roles+ RoleEntity role1 =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(metalakeName),+ "role1",+ auditInfo);+ RoleEntity role2 =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(metalakeName),+ "role2",+ auditInfo);+ roleMetaService.insertRole(role1, false);+ roleMetaService.insertRole(role2, false);+ UserEntity user2 =+ createUserEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofUserNamespace(metalakeName),+ "user2",+ auditInfo,+ Lists.newArrayList("role1", "role2"));+ Assertions.assertDoesNotThrow(() -> userMetaService.insertUser(user2, false));+ UserEntity actualUser = userMetaService.getUserByIdentifier(user2.nameIdentifier());+ Assertions.assertEquals(user2.name(), actualUser.name());+ Assertions.assertEquals(+ Sets.newHashSet(user2.roleNames()), Sets.newHashSet(actualUser.roleNames()));++ // insert duplicate user with roles+ UserEntity user2Exist =+ createUserEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofUserNamespace(metalakeName),+ "user2",+ auditInfo);+ Assertions.assertThrows(+ AlreadyExistsException.class, () -> userMetaService.insertUser(user2Exist, false));++ // insert overwrite user with roles+ UserEntity user2Overwrite =+ createUserEntity(+ user1.id(),+ AuthorizationUtils.ofUserNamespace(metalakeName),+ "user2Overwrite",+ auditInfo);+ Assertions.assertDoesNotThrow(() -> userMetaService.insertUser(user2Overwrite, true));+ Assertions.assertEquals(+ "user2Overwrite",+ userMetaService.getUserByIdentifier(user2Overwrite.nameIdentifier()).name());+ Assertions.assertEquals(+ user2Overwrite, userMetaService.getUserByIdentifier(user2Overwrite.nameIdentifier()));+ }++ @Test+ void deleteUser() {+ AuditInfo auditInfo =+ AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();+ BaseMetalake metalake =+ createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);+ backend.insert(metalake, false);++ UserMetaService userMetaService = UserMetaService.getInstance();+ RoleMetaService roleMetaService = RoleMetaService.getInstance();++ // delete user+ UserEntity user1 =+ createUserEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofUserNamespace(metalakeName),+ "user1",+ auditInfo);+ Assertions.assertThrows(+ NoSuchEntityException.class,+ () -> userMetaService.getUserByIdentifier(user1.nameIdentifier()));+ Assertions.assertDoesNotThrow(() -> userMetaService.insertUser(user1, false));+ Assertions.assertEquals(user1, userMetaService.getUserByIdentifier(user1.nameIdentifier()));+ Assertions.assertTrue(userMetaService.deleteUser(user1.nameIdentifier()));+ Assertions.assertThrows(+ NoSuchEntityException.class,+ () -> userMetaService.getUserByIdentifier(user1.nameIdentifier()));++ // delete user with roles+ RoleEntity role1 =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(metalakeName),+ "role1",+ auditInfo);+ RoleEntity role2 =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(metalakeName),+ "role2",+ auditInfo);+ roleMetaService.insertRole(role1, false);+ roleMetaService.insertRole(role2, false);+ UserEntity user2 =+ createUserEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofUserNamespace(metalakeName),+ "user2",+ auditInfo,+ Lists.newArrayList("role1", "role2"));+ userMetaService.insertUser(user2, false);+ List<RolePO> rolePOs =+ SessionUtils.doWithCommitAndFetchResult(+ RoleMetaMapper.class, mapper -> mapper.listRolesByUserId(user2.id()));+ Assertions.assertEquals(2, rolePOs.size());+ UserEntity actualUser = userMetaService.getUserByIdentifier(user2.nameIdentifier());+ Assertions.assertEquals(user2.name(), actualUser.name());+ Assertions.assertEquals(+ Sets.newHashSet(user2.roleNames()), Sets.newHashSet(actualUser.roleNames()));++ Assertions.assertTrue(userMetaService.deleteUser(user2.nameIdentifier()));+ Assertions.assertThrows(+ NoSuchEntityException.class,+ () -> userMetaService.getUserByIdentifier(user2.nameIdentifier()));+ rolePOs =+ SessionUtils.doWithCommitAndFetchResult(+ RoleMetaMapper.class, mapper -> mapper.listRolesByUserId(user2.id()));+ Assertions.assertEquals(0, rolePOs.size());+ }++ @Test+ void updateUser() {+ AuditInfo auditInfo =+ AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();+ BaseMetalake metalake =+ createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);+ backend.insert(metalake, false);++ UserMetaService userMetaService = UserMetaService.getInstance();+ RoleMetaService roleMetaService = RoleMetaService.getInstance();++ RoleEntity role1 =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(metalakeName),+ "role1",+ auditInfo);+ RoleEntity role2 =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(metalakeName),+ "role2",+ auditInfo);+ roleMetaService.insertRole(role1, false);+ roleMetaService.insertRole(role2, false);+ UserEntity user1 =+ createUserEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofUserNamespace(metalakeName),+ "user1",+ auditInfo,+ Lists.newArrayList("role1", "role2"));+ userMetaService.insertUser(user1, false);+ UserEntity actualUser = userMetaService.getUserByIdentifier(user1.nameIdentifier());+ Assertions.assertEquals(user1.name(), actualUser.name());+ Assertions.assertEquals(+ Sets.newHashSet(user1.roleNames()), Sets.newHashSet(actualUser.roleNames()));++ RoleEntity role3 =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(metalakeName),+ "role3",+ auditInfo);+ roleMetaService.insertRole(role3, false);++ // update user (grant)+ Function<UserEntity, UserEntity> grantUpdater =+ user -> {+ AuditInfo updateAuditInfo =+ AuditInfo.builder()+ .withCreator(user.auditInfo().creator())+ .withCreateTime(user.auditInfo().createTime())+ .withLastModifier("grantUser")+ .withLastModifiedTime(Instant.now())+ .build();++ List<String> roleNames = Lists.newArrayList(user.roleNames());+ List<Long> roleIds = Lists.newArrayList(user.roleIds());+ roleNames.add(role3.name());+ roleIds.add(role3.id());++ return UserEntity.builder()+ .withNamespace(user.namespace())+ .withId(user.id())+ .withName(user.name())+ .withRoleNames(roleNames)+ .withRoleIds(roleIds)+ .withAuditInfo(updateAuditInfo)+ .build();+ };++ Assertions.assertNotNull(userMetaService.updateUser(user1.nameIdentifier(), grantUpdater));+ UserEntity grantUser =+ UserMetaService.getInstance().getUserByIdentifier(user1.nameIdentifier());+ Assertions.assertEquals(user1.id(), grantUser.id());+ Assertions.assertEquals(user1.name(), grantUser.name());+ Assertions.assertEquals(+ Sets.newHashSet("role1", "role2", "role3"), Sets.newHashSet(grantUser.roleNames()));+ Assertions.assertEquals(+ Sets.newHashSet(role1.id(), role2.id(), role3.id()), Sets.newHashSet(grantUser.roleIds()));+ Assertions.assertEquals("creator", grantUser.auditInfo().creator());+ Assertions.assertEquals("grantUser", grantUser.auditInfo().lastModifier());++ // update user (revoke)+ Function<UserEntity, UserEntity> revokeUpdater =+ user -> {+ AuditInfo updateAuditInfo =+ AuditInfo.builder()+ .withCreator(user.auditInfo().creator())+ .withCreateTime(user.auditInfo().createTime())+ .withLastModifier("revokeUser")+ .withLastModifiedTime(Instant.now())+ .build();++ List<String> roleNames = Lists.newArrayList(user.roleNames());+ List<Long> roleIds = Lists.newArrayList(user.roleIds());+ roleIds.remove(roleNames.indexOf("role2"));+ roleNames.remove("role2");++ return UserEntity.builder()+ .withNamespace(user.namespace())+ .withId(user.id())+ .withName(user.name())+ .withRoleNames(roleNames)+ .withRoleIds(roleIds)+ .withAuditInfo(updateAuditInfo)+ .build();+ };++ Assertions.assertNotNull(userMetaService.updateUser(user1.nameIdentifier(), revokeUpdater));+ UserEntity revokeUser =+ UserMetaService.getInstance().getUserByIdentifier(user1.nameIdentifier());+ Assertions.assertEquals(user1.id(), revokeUser.id());+ Assertions.assertEquals(user1.name(), revokeUser.name());+ Assertions.assertEquals(+ Sets.newHashSet("role1", "role3"), Sets.newHashSet(revokeUser.roleNames()));+ Assertions.assertEquals(+ Sets.newHashSet(role1.id(), role3.id()), Sets.newHashSet(revokeUser.roleIds()));+ Assertions.assertEquals("creator", revokeUser.auditInfo().creator());+ Assertions.assertEquals("revokeUser", revokeUser.auditInfo().lastModifier());++ RoleEntity role4 =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(metalakeName),+ "role4",+ auditInfo);+ roleMetaService.insertRole(role4, false);++ // update user (grant & revoke)+ Function<UserEntity, UserEntity> grantRevokeUpdater =+ user -> {+ AuditInfo updateAuditInfo =+ AuditInfo.builder()+ .withCreator(user.auditInfo().creator())+ .withCreateTime(user.auditInfo().createTime())+ .withLastModifier("grantRevokeUser")+ .withLastModifiedTime(Instant.now())+ .build();++ List<String> roleNames = Lists.newArrayList(user.roleNames());+ List<Long> roleIds = Lists.newArrayList(user.roleIds());+ roleIds.remove(roleNames.indexOf("role3"));+ roleNames.remove("role3");+ roleIds.add(role4.id());+ roleNames.add(role4.name());++ return UserEntity.builder()+ .withNamespace(user.namespace())+ .withId(user.id())+ .withName(user.name())+ .withRoleNames(roleNames)+ .withRoleIds(roleIds)+ .withAuditInfo(updateAuditInfo)+ .build();+ };+ Assertions.assertNotNull(+ userMetaService.updateUser(user1.nameIdentifier(), grantRevokeUpdater));+ UserEntity grantRevokeUser =+ UserMetaService.getInstance().getUserByIdentifier(user1.nameIdentifier());+ Assertions.assertEquals(user1.id(), grantRevokeUser.id());+ Assertions.assertEquals(user1.name(), grantRevokeUser.name());+ Assertions.assertEquals(+ Sets.newHashSet("role1", "role4"), Sets.newHashSet(grantRevokeUser.roleNames()));+ Assertions.assertEquals(+ Sets.newHashSet(role1.id(), role4.id()), Sets.newHashSet(grantRevokeUser.roleIds()));+ Assertions.assertEquals("creator", grantRevokeUser.auditInfo().creator());+ Assertions.assertEquals("grantRevokeUser", grantRevokeUser.auditInfo().lastModifier());++ Function<UserEntity, UserEntity> noUpdater =+ user -> {+ AuditInfo updateAuditInfo =+ AuditInfo.builder()+ .withCreator(user.auditInfo().creator())+ .withCreateTime(user.auditInfo().createTime())+ .withLastModifier("noUpdateUser")+ .withLastModifiedTime(Instant.now())+ .build();++ List<String> roleNames = Lists.newArrayList(user.roleNames());+ List<Long> roleIds = Lists.newArrayList(user.roleIds());++ return UserEntity.builder()+ .withNamespace(user.namespace())+ .withId(user.id())+ .withName(user.name())+ .withRoleNames(roleNames)+ .withRoleIds(roleIds)+ .withAuditInfo(updateAuditInfo)+ .build();+ };+ Assertions.assertNotNull(userMetaService.updateUser(user1.nameIdentifier(), noUpdater));+ UserEntity noUpdaterUser =+ UserMetaService.getInstance().getUserByIdentifier(user1.nameIdentifier());+ Assertions.assertEquals(user1.id(), noUpdaterUser.id());+ Assertions.assertEquals(user1.name(), noUpdaterUser.name());+ Assertions.assertEquals(+ Sets.newHashSet("role1", "role4"), Sets.newHashSet(noUpdaterUser.roleNames()));+ Assertions.assertEquals(+ Sets.newHashSet(role1.id(), role4.id()), Sets.newHashSet(noUpdaterUser.roleIds()));+ Assertions.assertEquals("creator", noUpdaterUser.auditInfo().creator());+ Assertions.assertEquals("grantRevokeUser", noUpdaterUser.auditInfo().lastModifier());+ }++ @Test+ void deleteMetalake() {+ AuditInfo auditInfo =+ AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();+ BaseMetalake metalake =+ createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);+ backend.insert(metalake, false);++ UserMetaService userMetaService = UserMetaService.getInstance();+ RoleMetaService roleMetaService = RoleMetaService.getInstance();++ RoleEntity role1 =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(metalakeName),+ "role1",+ auditInfo);+ RoleEntity role2 =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(metalakeName),+ "role2",+ auditInfo);+ RoleEntity role3 =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(metalakeName),+ "role3",+ auditInfo);+ roleMetaService.insertRole(role1, false);+ roleMetaService.insertRole(role2, false);+ roleMetaService.insertRole(role3, false);+ UserEntity user1 =+ createUserEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofUserNamespace(metalakeName),+ "user1",+ auditInfo,+ Lists.newArrayList("role1", "role2"));+ UserEntity user2 =+ createUserEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofUserNamespace(metalakeName),+ "user2",+ auditInfo,+ Lists.newArrayList("role3"));+ userMetaService.insertUser(user1, false);+ userMetaService.insertUser(user2, false);++ Assertions.assertEquals(+ user1.name(), userMetaService.getUserByIdentifier(user1.nameIdentifier()).name());+ Assertions.assertEquals(2, roleMetaService.listRolesByUserId(user1.id()).size());+ Assertions.assertEquals(+ user2.name(), userMetaService.getUserByIdentifier(user2.nameIdentifier()).name());+ Assertions.assertEquals(1, roleMetaService.listRolesByUserId(user2.id()).size());++ // delete metalake without cascade+ Assertions.assertTrue(+ MetalakeMetaService.getInstance().deleteMetalake(metalake.nameIdentifier(), false));++ Assertions.assertThrows(+ NoSuchEntityException.class,+ () -> userMetaService.getUserByIdentifier(user1.nameIdentifier()));+ Assertions.assertThrows(+ NoSuchEntityException.class,+ () -> userMetaService.getUserByIdentifier(user2.nameIdentifier()));+ Assertions.assertEquals(0, roleMetaService.listRolesByUserId(user1.id()).size());+ Assertions.assertEquals(0, roleMetaService.listRolesByUserId(user2.id()).size());+ }++ @Test+ void deleteMetalakeCascade() {+ AuditInfo auditInfo =+ AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();+ BaseMetalake metalake =+ createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);+ backend.insert(metalake, false);++ UserMetaService userMetaService = UserMetaService.getInstance();+ RoleMetaService roleMetaService = RoleMetaService.getInstance();++ RoleEntity role1 =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(metalakeName),+ "role1",+ auditInfo);+ RoleEntity role2 =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(metalakeName),+ "role2",+ auditInfo);+ RoleEntity role3 =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(metalakeName),+ "role3",+ auditInfo);+ roleMetaService.insertRole(role1, false);+ roleMetaService.insertRole(role2, false);+ roleMetaService.insertRole(role3, false);+ UserEntity user1 =+ createUserEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofUserNamespace(metalakeName),+ "user1",+ auditInfo,+ Lists.newArrayList("role1", "role2"));+ UserEntity user2 =+ createUserEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofUserNamespace(metalakeName),+ "user2",+ auditInfo,+ Lists.newArrayList("role3"));+ userMetaService.insertUser(user1, false);+ userMetaService.insertUser(user2, false);++ Assertions.assertEquals(+ user1.name(), userMetaService.getUserByIdentifier(user1.nameIdentifier()).name());+ Assertions.assertEquals(2, roleMetaService.listRolesByUserId(user1.id()).size());+ Assertions.assertEquals(+ user2.name(), userMetaService.getUserByIdentifier(user2.nameIdentifier()).name());+ Assertions.assertEquals(1, roleMetaService.listRolesByUserId(user2.id()).size());++ // delete metalake with cascade+ Assertions.assertTrue(+ MetalakeMetaService.getInstance().deleteMetalake(metalake.nameIdentifier(), true));++ Assertions.assertThrows(+ NoSuchEntityException.class,+ () -> userMetaService.getUserByIdentifier(user1.nameIdentifier()));+ Assertions.assertThrows(+ NoSuchEntityException.class,+ () -> userMetaService.getUserByIdentifier(user2.nameIdentifier()));+ Assertions.assertEquals(0, roleMetaService.listRolesByUserId(user1.id()).size());+ Assertions.assertEquals(0, roleMetaService.listRolesByUserId(user2.id()).size());+ }+}diff --git a/core/src/test/resources/h2/schema-h2.sql b/core/src/test/resources/h2/schema-h2.sqlindex 6e2796c316..0b2c269b9b 100644--- a/core/src/test/resources/h2/schema-h2.sql+++ b/core/src/test/resources/h2/schema-h2.sql@@ -124,4 +124,44 @@ CREATE TABLE IF NOT EXISTS `topic_meta` (-- Aliases are used here, and indexes with the same name in H2 can only be created once.KEY idx_tvmid (metalake_id),KEY idx_tvcid (catalog_id)+) ENGINE=InnoDB;++CREATE TABLE IF NOT EXISTS `user_meta` (+ `user_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'user id',+ `user_name` VARCHAR(128) NOT NULL COMMENT 'username',+ `metalake_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'metalake id',+ `audit_info` MEDIUMTEXT NOT NULL COMMENT 'user audit info',+ `current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'user current version',+ `last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'user last version',+ `deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'user deleted at',+ PRIMARY KEY (`user_id`),+ CONSTRAINT `uk_mid_us_del` UNIQUE (`metalake_id`, `user_name`, `deleted_at`)+) ENGINE=InnoDB;++CREATE TABLE IF NOT EXISTS `role_meta` (+ `role_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'role id',+ `role_name` VARCHAR(128) NOT NULL COMMENT 'role name',+ `metalake_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'metalake id',+ `properties` MEDIUMTEXT DEFAULT NULL COMMENT 'schema properties',+ `securable_object` VARCHAR(256) NOT NULL COMMENT 'securable object',+ `privileges` VARCHAR(64) NOT NULL COMMENT 'securable privileges',+ `audit_info` MEDIUMTEXT NOT NULL COMMENT 'role audit info',+ `current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'role current version',+ `last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'role last version',+ `deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'role deleted at',+ PRIMARY KEY (`role_id`),+ CONSTRAINT `uk_mid_rn_del` UNIQUE (`metalake_id`, `role_name`, `deleted_at`)+) ENGINE=InnoDB;++CREATE TABLE IF NOT EXISTS `user_role_rel` (+ `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',+ `user_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'user id',+ `role_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'role id',+ `audit_info` MEDIUMTEXT NOT NULL COMMENT 'relation audit info',+ `current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'relation current version',+ `last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'relation last version',+ `deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'relation deleted at',+ PRIMARY KEY (`id`),+ CONSTRAINT `uk_ui_ri_del` UNIQUE (`user_id`, `role_id`, `deleted_at`),+ KEY `idx_rid` (`role_id`)) ENGINE=InnoDB;\ No newline at end of filediff --git a/scripts/mysql/schema-0.5.0-mysql.sql b/scripts/mysql/schema-0.5.0-mysql.sqlindex f3a1e323d1..f78942a65c 100644--- a/scripts/mysql/schema-0.5.0-mysql.sql+++ b/scripts/mysql/schema-0.5.0-mysql.sql@@ -116,4 +116,44 @@ CREATE TABLE IF NOT EXISTS `topic_meta` (UNIQUE KEY `uk_sid_tn_del` (`schema_id`, `topic_name`, `deleted_at`),KEY `idx_mid` (`metalake_id`),KEY `idx_cid` (`catalog_id`)- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'topic metadata';\ No newline at end of file+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'topic metadata';++CREATE TABLE IF NOT EXISTS `user_meta` (+ `user_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'user id',+ `user_name` VARCHAR(128) NOT NULL COMMENT 'username',+ `metalake_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'metalake id',+ `audit_info` MEDIUMTEXT NOT NULL COMMENT 'user audit info',+ `current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'user current version',+ `last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'user last version',+ `deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'user deleted at',+ PRIMARY KEY (`user_id`),+ UNIQUE KEY `uk_mid_us_del` (`metalake_id`, `user_name`, `deleted_at`)+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'user metadata';++CREATE TABLE IF NOT EXISTS `role_meta` (+ `role_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'role id',+ `role_name` VARCHAR(128) NOT NULL COMMENT 'role name',+ `metalake_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'metalake id',+ `properties` MEDIUMTEXT DEFAULT NULL COMMENT 'schema properties',+ `securable_object` VARCHAR(256) NOT NULL COMMENT 'securable object',+ `privileges` VARCHAR(64) NOT NULL COMMENT 'securable privileges',+ `audit_info` MEDIUMTEXT NOT NULL COMMENT 'role audit info',+ `current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'role current version',+ `last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'role last version',+ `deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'role deleted at',+ PRIMARY KEY (`role_id`),+ UNIQUE KEY `uk_mid_rn_del` (`metalake_id`, `role_name`, `deleted_at`)+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'role metadata';++CREATE TABLE IF NOT EXISTS `user_role_rel` (+ `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',+ `user_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'user id',+ `role_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'role id',+ `audit_info` MEDIUMTEXT NOT NULL COMMENT 'relation audit info',+ `current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'relation current version',+ `last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'relation last version',+ `deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'relation deleted at',+ PRIMARY KEY (`id`),+ UNIQUE KEY `uk_ui_ri_del` (`user_id`, `role_id`, `deleted_at`),+ KEY `idx_rid` (`role_id`)+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'user role relation';\ No newline at end of file