Unverified Commit e5bdefe6 authored by aiwenmo's avatar aiwenmo Committed by GitHub

[Feature-1641][admin,client] Add Flink row level permissions (#1831)

parent a45fb097
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.controller;
import org.dinky.common.result.ProTableResult;
import org.dinky.common.result.Result;
import org.dinky.model.RoleSelectPermissions;
import org.dinky.service.RoleSelectPermissionsService;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
@RequestMapping("/api/roleSelectPermissions")
public class RoleSelectPermissionsController {
@Autowired private RoleSelectPermissionsService roleSelectPermissionsService;
/** create or update roleSelectPermissions */
@PutMapping
public Result saveOrUpdateRole(@RequestBody RoleSelectPermissions roleSelectPermissions) {
if (roleSelectPermissionsService.saveOrUpdate(roleSelectPermissions)) {
return Result.succeed("新增成功");
} else {
return Result.failed("新增失败");
}
}
/** delete roleSelectPermissions by id */
@DeleteMapping
public Result deleteMul(@RequestBody JsonNode para) {
if (para.size() > 0) {
List<Integer> error = new ArrayList<>();
for (final JsonNode item : para) {
Integer id = item.asInt();
if (!roleSelectPermissionsService.removeById(id)) {
error.add(id);
}
}
if (error.size() == 0) {
return Result.succeed("删除成功");
} else {
return Result.succeed(
"删除部分成功,但" + error.toString() + "删除失败,共" + error.size() + "次失败。");
}
} else {
return Result.failed("请选择要删除的记录");
}
}
/** query roleSelectPermissions list */
@PostMapping
public ProTableResult<RoleSelectPermissions> listRoles(@RequestBody JsonNode para) {
return roleSelectPermissionsService.selectForProTable(para);
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.mapper;
import org.dinky.db.mapper.SuperMapper;
import org.dinky.model.RoleSelectPermissions;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/** role select permissions mapper interface */
@Mapper
public interface RoleSelectPermissionsMapper extends SuperMapper<RoleSelectPermissions> {
/**
* delete user role select permissions by role id
*
* @param roleIds role id
* @return delete status
*/
int deleteByRoleIds(@Param("roleIds") List<Integer> roleIds);
/**
* select user role data permissions by role ids
*
* @param roleIds role ids
* @return List<RoleSelectPermissions>
*/
List<RoleSelectPermissions> listRoleSelectPermissionsByRoleIds(
@Param("roleIds") List<Integer> roleIds);
}
......@@ -20,6 +20,7 @@
package org.dinky.mapper;
import org.dinky.db.mapper.SuperMapper;
import org.dinky.model.Role;
import org.dinky.model.UserRole;
import org.apache.ibatis.annotations.Mapper;
......@@ -52,4 +53,12 @@ public interface UserRoleMapper extends SuperMapper<UserRole> {
* @return delete status
*/
int deleteByRoleIds(@Param("roleIds") List<Integer> roleIds);
/**
* get role list by user id
*
* @param userId userId
* @return role list
*/
List<Role> getRoleByUserId(Integer userId);
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.model;
import java.io.Serializable;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("dinky_role_select_permissions")
public class RoleSelectPermissions implements Serializable {
private static final long serialVersionUID = 8676666963206334660L;
/** id */
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/** role id */
private Integer roleId;
/** table_name */
private String tableName;
/** expression */
private String expression;
/** create time */
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/** update time */
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/** role code */
@TableField(exist = false)
private String roleCode;
/** role name */
@TableField(exist = false)
private String roleName;
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.service;
import org.dinky.db.service.ISuperService;
import org.dinky.model.RoleSelectPermissions;
import java.util.List;
public interface RoleSelectPermissionsService extends ISuperService<RoleSelectPermissions> {
/**
* delete user role select permissions by role id
*
* @param roleIds role id
* @return delete status
*/
boolean deleteByRoleIds(List<Integer> roleIds);
/**
* select user role data permissions by role id
*
* @param roleId role id
* @return List<RoleSelectPermissions>
*/
List<RoleSelectPermissions> listAllByRoleId(Integer roleId);
/**
* select user role data permissions by role ids
*
* @param roleIds role ids
* @return List<RoleSelectPermissions>
*/
List<RoleSelectPermissions> listRoleSelectPermissionsByRoleIds(List<Integer> roleIds);
}
......@@ -24,6 +24,8 @@ import org.dinky.common.result.Result;
import org.dinky.db.service.ISuperService;
import org.dinky.model.Role;
import java.util.List;
import com.fasterxml.jackson.databind.JsonNode;
public interface RoleService extends ISuperService<Role> {
......@@ -66,4 +68,12 @@ public interface RoleService extends ISuperService<Role> {
* @return {@link Result} of {@link Void}
*/
Result<Void> deleteRoleById(Integer id);
/**
* get role list by user id
*
* @param userId user id
* @return role list
*/
List<Role> getRoleByUserId(Integer userId);
}
......@@ -20,6 +20,7 @@
package org.dinky.service;
import org.dinky.db.service.ISuperService;
import org.dinky.model.Role;
import org.dinky.model.UserRole;
import java.util.List;
......@@ -57,4 +58,12 @@ public interface UserRoleService extends ISuperService<UserRole> {
* @return
*/
boolean deleteByRoleIds(List<Integer> roleIds);
/**
* query roles by user id
*
* @param userId user id
* @return role list
*/
List<Role> getRoleByUserId(Integer userId);
}
......@@ -24,10 +24,14 @@ import org.dinky.db.service.ISuperService;
import org.dinky.dto.LoginDTO;
import org.dinky.dto.ModifyPasswordDTO;
import org.dinky.dto.UserDTO;
import org.dinky.model.Role;
import org.dinky.model.RoleSelectPermissions;
import org.dinky.model.Tenant;
import org.dinky.model.User;
import org.dinky.params.AssignRoleParams;
import java.util.List;
import com.fasterxml.jackson.databind.JsonNode;
/**
......@@ -134,4 +138,18 @@ public interface UserService extends ISuperService<User> {
* @return {@link Boolean}
*/
Boolean checkAdmin(Integer id);
/**
* get role by current user
*
* @return role list
*/
List<Role> getCurrentRole();
/**
* get role select permissions by current user
*
* @return role select permissions list
*/
List<RoleSelectPermissions> getCurrentRoleSelectPermissions();
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.service.impl;
import org.dinky.db.service.impl.SuperServiceImpl;
import org.dinky.mapper.RoleSelectPermissionsMapper;
import org.dinky.model.RoleSelectPermissions;
import org.dinky.service.RoleSelectPermissionsService;
import java.util.List;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
@Service
public class RoleSelectPermissionsServiceImpl
extends SuperServiceImpl<RoleSelectPermissionsMapper, RoleSelectPermissions>
implements RoleSelectPermissionsService {
@Override
public boolean deleteByRoleIds(List<Integer> roleIds) {
return baseMapper.deleteByRoleIds(roleIds) > 0;
}
@Override
public List<RoleSelectPermissions> listAllByRoleId(Integer roleId) {
return baseMapper.selectList(
new QueryWrapper<RoleSelectPermissions>().eq("role_id", roleId));
}
@Override
public List<RoleSelectPermissions> listRoleSelectPermissionsByRoleIds(List<Integer> roleIds) {
return baseMapper.listRoleSelectPermissionsByRoleIds(roleIds);
}
}
......@@ -220,4 +220,9 @@ public class RoleServiceImpl extends SuperServiceImpl<RoleMapper, Role> implemen
return roleProTableResult;
}
@Override
public List<Role> getRoleByUserId(Integer userId) {
return userRoleService.getRoleByUserId(userId);
}
}
......@@ -22,6 +22,7 @@ package org.dinky.service.impl;
import org.dinky.api.FlinkAPI;
import org.dinky.assertion.Asserts;
import org.dinky.config.Dialect;
import org.dinky.context.RowLevelPermissionsContext;
import org.dinky.dto.AbstractStatementDTO;
import org.dinky.dto.SqlDTO;
import org.dinky.dto.StudioCADTO;
......@@ -41,6 +42,7 @@ import org.dinky.model.Catalog;
import org.dinky.model.Cluster;
import org.dinky.model.DataBase;
import org.dinky.model.FlinkColumn;
import org.dinky.model.RoleSelectPermissions;
import org.dinky.model.Savepoints;
import org.dinky.model.Schema;
import org.dinky.model.Table;
......@@ -59,6 +61,7 @@ import org.dinky.service.FragmentVariableService;
import org.dinky.service.SavepointsService;
import org.dinky.service.StudioService;
import org.dinky.service.TaskService;
import org.dinky.service.UserService;
import org.dinky.sql.FlinkQuery;
import org.dinky.utils.RunTimeUtil;
......@@ -66,6 +69,7 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -79,12 +83,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.dev33.satoken.stp.StpUtil;
import lombok.RequiredArgsConstructor;
/**
* StudioServiceImpl
*
* @author wenmo
* @since 2021/5/30 11:08
*/
/** StudioServiceImpl */
@Service
@RequiredArgsConstructor
public class StudioServiceImpl implements StudioService {
......@@ -97,6 +96,7 @@ public class StudioServiceImpl implements StudioService {
private final DataBaseService dataBaseService;
private final TaskService taskService;
private final FragmentVariableService fragmentVariableService;
private final UserService userService;
private void addFlinkSQLEnv(AbstractStatementDTO statementDTO) {
ProcessEntity process = ProcessContextHolder.getProcess();
......@@ -132,6 +132,23 @@ public class StudioServiceImpl implements StudioService {
process.info("No FlinkSQLEnv are loaded.");
}
}
process.info("Initializing data permissions...");
List<RoleSelectPermissions> currentRoleSelectPermissions =
userService.getCurrentRoleSelectPermissions();
if (Asserts.isNotNullCollection(currentRoleSelectPermissions)) {
ConcurrentHashMap<String, String> permission = new ConcurrentHashMap<>();
for (RoleSelectPermissions roleSelectPermissions : currentRoleSelectPermissions) {
if (Asserts.isAllNotNullString(
roleSelectPermissions.getTableName(),
roleSelectPermissions.getExpression())) {
permission.put(
roleSelectPermissions.getTableName(),
roleSelectPermissions.getExpression());
}
}
RowLevelPermissionsContext.set(permission);
}
process.info("Finish initialize FlinkSQLEnv.");
}
......
......@@ -32,6 +32,7 @@ import org.dinky.config.Dialect;
import org.dinky.config.Docker;
import org.dinky.constant.FlinkRestResultConstant;
import org.dinky.constant.NetConstant;
import org.dinky.context.RowLevelPermissionsContext;
import org.dinky.context.TenantContextHolder;
import org.dinky.daemon.task.DaemonFactory;
import org.dinky.daemon.task.DaemonTaskConfig;
......@@ -73,6 +74,7 @@ import org.dinky.model.JobInfoDetail;
import org.dinky.model.JobInstance;
import org.dinky.model.JobLifeCycle;
import org.dinky.model.JobStatus;
import org.dinky.model.RoleSelectPermissions;
import org.dinky.model.Savepoints;
import org.dinky.model.Statement;
import org.dinky.model.SystemConfiguration;
......@@ -103,6 +105,7 @@ import org.dinky.service.StatementService;
import org.dinky.service.TaskService;
import org.dinky.service.TaskVersionService;
import org.dinky.service.UDFTemplateService;
import org.dinky.service.UserService;
import org.dinky.utils.DockerClientUtils;
import org.dinky.utils.JSONUtil;
import org.dinky.utils.UDFUtils;
......@@ -127,6 +130,7 @@ import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import javax.annotation.Resource;
......@@ -176,6 +180,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
private final FragmentVariableService fragmentVariableService;
private final UDFTemplateService udfTemplateService;
private final DataSourceProperties dataSourceProperties;
private final UserService userService;
@Resource @Lazy private CatalogueService catalogueService;
......@@ -1029,6 +1034,21 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
config.setSavePointPath(null);
}
config.setVariables(fragmentVariableService.listEnabledVariables());
List<RoleSelectPermissions> currentRoleSelectPermissions =
userService.getCurrentRoleSelectPermissions();
if (Asserts.isNotNullCollection(currentRoleSelectPermissions)) {
ConcurrentHashMap<String, String> permission = new ConcurrentHashMap<>();
for (RoleSelectPermissions roleSelectPermissions : currentRoleSelectPermissions) {
if (Asserts.isAllNotNullString(
roleSelectPermissions.getTableName(),
roleSelectPermissions.getExpression())) {
permission.put(
roleSelectPermissions.getTableName(),
roleSelectPermissions.getExpression());
}
}
RowLevelPermissionsContext.set(permission);
}
return config;
}
......
......@@ -21,6 +21,7 @@ package org.dinky.service.impl;
import org.dinky.db.service.impl.SuperServiceImpl;
import org.dinky.mapper.UserRoleMapper;
import org.dinky.model.Role;
import org.dinky.model.UserRole;
import org.dinky.service.UserRoleService;
......@@ -56,4 +57,9 @@ public class UserRoleServiceImpl extends SuperServiceImpl<UserRoleMapper, UserRo
public boolean deleteByRoleIds(List<Integer> roleIds) {
return baseMapper.deleteByRoleIds(roleIds) > 0;
}
@Override
public List<Role> getRoleByUserId(Integer userId) {
return baseMapper.getRoleByUserId(userId);
}
}
......@@ -29,11 +29,13 @@ import org.dinky.dto.ModifyPasswordDTO;
import org.dinky.dto.UserDTO;
import org.dinky.mapper.UserMapper;
import org.dinky.model.Role;
import org.dinky.model.RoleSelectPermissions;
import org.dinky.model.Tenant;
import org.dinky.model.User;
import org.dinky.model.UserRole;
import org.dinky.model.UserTenant;
import org.dinky.params.AssignRoleParams;
import org.dinky.service.RoleSelectPermissionsService;
import org.dinky.service.RoleService;
import org.dinky.service.TenantService;
import org.dinky.service.UserRoleService;
......@@ -44,6 +46,7 @@ import org.dinky.utils.MessageResolverUtils;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
......@@ -76,6 +79,8 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen
private final TenantService tenantService;
private final RoleSelectPermissionsService roleSelectPermissionsService;
@Override
public Result<Void> registerUser(User user) {
User userByUsername = getUserByUsername(user.getUsername());
......@@ -293,4 +298,19 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen
User user = getById(id);
return "admin".equals(user.getUsername());
}
@Override
public List<Role> getCurrentRole() {
return roleService.getRoleByUserId(StpUtil.getLoginIdAsInt());
}
@Override
public List<RoleSelectPermissions> getCurrentRoleSelectPermissions() {
List<Role> currentRole = getCurrentRole();
if (Asserts.isNullCollection(currentRole)) {
return new ArrayList<>();
}
List<Integer> roleIds = currentRole.stream().map(Role::getId).collect(Collectors.toList());
return roleSelectPermissionsService.listRoleSelectPermissionsByRoleIds(roleIds);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.dinky.mapper.RoleSelectPermissionsMapper">
<select id="selectForProTable" resultType="org.dinky.model.RoleSelectPermissions">
select
a.*,
b.role_code,
b.role_name
from
dinky_role_select_permissions a
left join dinky_role b on b.id = a.role_id
<where>
1=1
<if test='param.roleId!=null and param.roleId!=""'>
and a.role_id = #{param.roleId}
</if>
<if test='param.tableName!=null and param.tableName!=""'>
and a.table_name like "%${param.tableName}%"
</if>
<if test='ew.sqlSegment!=null and ew.sqlSegment!="" and !ew.sqlSegment.startsWith(" ORDER BY")'>
and
</if>
<if test='ew.sqlSegment!=null and ew.sqlSegment!=""'>
${ew.sqlSegment}
</if>
</where>
</select>
<delete id="deleteByRoleIds" parameterType="java.util.List">
DELETE FROM dinky_role_select_permissions
WHERE role_id IN
<foreach collection="roleIds" item="item" open="(" separator="," close=")">
${item}
</foreach>
</delete>
<select id="listRoleSelectPermissionsByRoleIds" resultType="org.dinky.model.RoleSelectPermissions">
select
a.*,
b.role_code,
b.role_name
from
dinky_role_select_permissions a, dinky_role b
WHERE
b.id = a.role_id
and a.role_id IN
<foreach collection="roleIds" item="item" open="(" separator="," close=")">
${item}
</foreach>
order by a.id asc
</select>
</mapper>
\ No newline at end of file
......@@ -31,7 +31,7 @@
<include refid="baseSql"/>
from
dinky_user_role
where user_id = (#{userId})
where user_id = #{userId}
</select>
<delete id="deleteBathRelation" parameterType="java.util.List">
......@@ -49,4 +49,21 @@
${item}
</foreach>
</delete>
<select id="getRoleByUserId" resultType="org.dinky.model.Role">
select
distinct
b.id
,b.role_code
,b.role_name
,b.is_delete
,b.note
,b.create_time
,b.update_time
from
dinky_user_role a
inner join dinky_role b on b.id = a.role_id
where a.user_id = #{userId}
and b.is_delete = 0
</select>
</mapper>
\ No newline at end of file
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.calcite.sql;
import org.dinky.context.CustomTableEnvironmentContext;
import org.dinky.context.RowLevelPermissionsContext;
import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.sql.validate.SqlValidator;
import org.apache.calcite.sql.validate.SqlValidatorScope;
import org.apache.calcite.util.ImmutableNullableList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableList;
/**
* A <code>SqlSelect</code> is a node of a parse tree which represents a select statement. It
* warrants its own node type just because we have a lot of methods to put somewhere.
*
* @description: Modify the value method of where to addCondition() to support row-level permission
* filtering
*/
public class SqlSelect extends SqlCall {
private static final Logger LOG = LoggerFactory.getLogger(SqlSelect.class);
public static final int FROM_OPERAND = 2;
public static final int WHERE_OPERAND = 3;
public static final int HAVING_OPERAND = 5;
SqlNodeList keywordList;
SqlNodeList selectList;
SqlNode from;
SqlNode where;
SqlNodeList groupBy;
SqlNode having;
SqlNodeList windowDecls;
SqlNodeList orderBy;
SqlNode offset;
SqlNode fetch;
SqlNodeList hints;
public SqlSelect(
SqlParserPos pos,
SqlNodeList keywordList,
SqlNodeList selectList,
SqlNode from,
SqlNode where,
SqlNodeList groupBy,
SqlNode having,
SqlNodeList windowDecls,
SqlNodeList orderBy,
SqlNode offset,
SqlNode fetch,
SqlNodeList hints) {
super(pos);
this.keywordList =
Objects.requireNonNull(keywordList != null ? keywordList : new SqlNodeList(pos));
this.selectList = selectList;
this.from = from;
this.groupBy = groupBy;
this.having = having;
this.windowDecls =
Objects.requireNonNull(windowDecls != null ? windowDecls : new SqlNodeList(pos));
this.orderBy = orderBy;
this.offset = offset;
this.fetch = fetch;
this.hints = hints;
// add row level filter condition for where clause
this.where = addCondition(from, where, false);
}
/** The main process of controlling row-level permissions */
private SqlNode addCondition(SqlNode from, SqlNode where, boolean fromJoin) {
if (from instanceof SqlIdentifier) {
String tableName = from.toString();
// the table name is used as an alias for join
String tableAlias = fromJoin ? tableName : null;
return addPermission(where, tableName, tableAlias);
} else if (from instanceof SqlJoin) {
SqlJoin sqlJoin = (SqlJoin) from;
// support recursive processing, such as join for three tables, process left sqlNode
where = addCondition(sqlJoin.getLeft(), where, true);
// process right sqlNode
return addCondition(sqlJoin.getRight(), where, true);
} else if (from instanceof SqlBasicCall) {
// Table has an alias or comes from a subquery
SqlNode[] tableNodes = ((SqlBasicCall) from).getOperands();
/**
* If there is a subquery in the Join, row-level filtering has been appended to the
* subquery. What is returned here is the SqlSelect type, just return the original where
* directly
*/
if (!(tableNodes[0] instanceof SqlIdentifier)) {
return where;
}
String tableName = tableNodes[0].toString();
String tableAlias = tableNodes[1].toString();
return addPermission(where, tableName, tableAlias);
}
return where;
}
/** Add row-level filtering based on user-configured permission points */
private SqlNode addPermission(SqlNode where, String tableName, String tableAlias) {
SqlBasicCall permissions = null;
ConcurrentHashMap<String, String> permissionsMap = RowLevelPermissionsContext.get();
if (permissionsMap != null) {
String permissionsStatement = permissionsMap.get(tableName);
if (permissionsStatement != null && !"".equals(permissionsStatement)) {
permissions =
(SqlBasicCall)
CustomTableEnvironmentContext.get()
.getParser()
.parseExpression(permissionsStatement);
}
}
// add an alias
if (permissions != null && tableAlias != null) {
ImmutableList<String> namesList =
ImmutableList.of(tableAlias, permissions.getOperands()[0].toString());
permissions.getOperands()[0] =
new SqlIdentifier(namesList, null, new SqlParserPos(0, 0), null);
}
return buildWhereClause(where, permissions);
}
/** Rebuild the where clause */
private SqlNode buildWhereClause(SqlNode where, SqlBasicCall permissions) {
if (permissions != null) {
if (where == null) {
return permissions;
}
SqlBinaryOperator sqlBinaryOperator =
new SqlBinaryOperator(
SqlKind.AND.name(), SqlKind.AND, 0, true, null, null, null);
SqlNode[] operands = new SqlNode[2];
operands[0] = where;
operands[1] = permissions;
SqlParserPos sqlParserPos = new SqlParserPos(0, 0);
return new SqlBasicCall(sqlBinaryOperator, operands, sqlParserPos);
}
return where;
}
@Override
public SqlOperator getOperator() {
return SqlSelectOperator.INSTANCE;
}
@Override
public SqlKind getKind() {
return SqlKind.SELECT;
}
@Override
public List<SqlNode> getOperandList() {
return ImmutableNullableList.of(
keywordList,
selectList,
from,
where,
groupBy,
having,
windowDecls,
orderBy,
offset,
fetch,
hints);
}
@Override
public void setOperand(int i, SqlNode operand) {
switch (i) {
case 0:
keywordList = Objects.requireNonNull((SqlNodeList) operand);
break;
case 1:
selectList = (SqlNodeList) operand;
break;
case 2:
from = operand;
break;
case 3:
where = operand;
break;
case 4:
groupBy = (SqlNodeList) operand;
break;
case 5:
having = operand;
break;
case 6:
windowDecls = Objects.requireNonNull((SqlNodeList) operand);
break;
case 7:
orderBy = (SqlNodeList) operand;
break;
case 8:
offset = operand;
break;
case 9:
fetch = operand;
break;
default:
throw new AssertionError(i);
}
}
public final boolean isDistinct() {
return getModifierNode(SqlSelectKeyword.DISTINCT) != null;
}
public final SqlNode getModifierNode(SqlSelectKeyword modifier) {
for (SqlNode keyword : keywordList) {
SqlSelectKeyword keyword2 = ((SqlLiteral) keyword).symbolValue(SqlSelectKeyword.class);
if (keyword2 == modifier) {
return keyword;
}
}
return null;
}
public final SqlNode getFrom() {
return from;
}
public void setFrom(SqlNode from) {
this.from = from;
}
public final SqlNodeList getGroup() {
return groupBy;
}
public void setGroupBy(SqlNodeList groupBy) {
this.groupBy = groupBy;
}
public final SqlNode getHaving() {
return having;
}
public void setHaving(SqlNode having) {
this.having = having;
}
public final SqlNodeList getSelectList() {
return selectList;
}
public void setSelectList(SqlNodeList selectList) {
this.selectList = selectList;
}
public final SqlNode getWhere() {
return where;
}
public void setWhere(SqlNode whereClause) {
this.where = whereClause;
}
@Nonnull
public final SqlNodeList getWindowList() {
return windowDecls;
}
public final SqlNodeList getOrderList() {
return orderBy;
}
public void setOrderBy(SqlNodeList orderBy) {
this.orderBy = orderBy;
}
public final SqlNode getOffset() {
return offset;
}
public void setOffset(SqlNode offset) {
this.offset = offset;
}
public final SqlNode getFetch() {
return fetch;
}
public void setFetch(SqlNode fetch) {
this.fetch = fetch;
}
public void setHints(SqlNodeList hints) {
this.hints = hints;
}
public SqlNodeList getHints() {
return this.hints;
}
public boolean hasHints() {
// The hints may be passed as null explicitly.
return this.hints != null && this.hints.size() > 0;
}
@Override
public void validate(SqlValidator validator, SqlValidatorScope scope) {
validator.validateQuery(this, scope, validator.getUnknownType());
}
/** Override SqlCall, to introduce a sub-query frame. */
@Override
public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {
if (!writer.inQuery()) {
// If this SELECT is the topmost item in a sub-query, introduce a new
// frame. (The topmost item in the sub-query might be a UNION or
// ORDER. In this case, we don't need a wrapper frame.)
final SqlWriter.Frame frame =
writer.startList(SqlWriter.FrameTypeEnum.SUB_QUERY, "(", ")");
writer.getDialect().unparseCall(writer, this, 0, 0);
writer.endList(frame);
} else {
writer.getDialect().unparseCall(writer, this, leftPrec, rightPrec);
}
}
public boolean hasOrderBy() {
return orderBy != null && orderBy.size() != 0;
}
public boolean hasWhere() {
return where != null;
}
public boolean isKeywordPresent(SqlSelectKeyword targetKeyWord) {
return getModifierNode(targetKeyWord) != null;
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.flink.table.delegation;
import org.apache.calcite.sql.SqlNode;
import org.apache.flink.annotation.Internal;
import org.apache.flink.table.api.SqlParserException;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import org.apache.flink.table.expressions.ResolvedExpression;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.operations.QueryOperation;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.RowType;
import java.util.List;
import javax.annotation.Nullable;
/** Provides methods for parsing SQL objects from a SQL string. */
@Internal
public interface Parser {
/**
* Entry point for parsing SQL queries expressed as a String.
*
* <p><b>Note:</b>If the created {@link Operation} is a {@link QueryOperation} it must be in a
* form that will be understood by the {@link Planner#translate(List)} method.
*
* <p>The produced Operation trees should already be validated.
*
* @param statement the SQL statement to evaluate
* @return parsed queries as trees of relational {@link Operation}s
* @throws SqlParserException when failed to parse the statement
*/
List<Operation> parse(String statement);
/**
* Entry point for parsing SQL identifiers expressed as a String.
*
* @param identifier the SQL identifier to parse
* @return parsed identifier
* @throws SqlParserException when failed to parse the identifier
*/
UnresolvedIdentifier parseIdentifier(String identifier);
/**
* Entry point for parsing SQL expressions expressed as a String.
*
* @param sqlExpression the SQL expression to parse
* @param inputRowType the fields available in the SQL expression
* @param outputType expected top-level output type if available
* @return resolved expression
* @throws SqlParserException when failed to parse the sql expression
*/
ResolvedExpression parseSqlExpression(
String sqlExpression, RowType inputRowType, @Nullable LogicalType outputType);
/**
* Returns completion hints for the given statement at the given cursor position. The completion
* happens case insensitively.
*
* @param statement Partial or slightly incorrect SQL statement
* @param position cursor position
* @return completion hints that fit at the current cursor position
*/
String[] getCompletionHints(String statement, int position);
/**
* Parses a SQL expression into a {@link SqlNode}. The {@link SqlNode} is not yet validated.
*
* @param sqlExpression a SQL expression string to parse
* @return a parsed SQL node
* @throws SqlParserException if an exception is thrown when parsing the statement
*/
SqlNode parseExpression(String sqlExpression);
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.flink.table.planner.delegation;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.sql.SqlIdentifier;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.advise.SqlAdvisor;
import org.apache.calcite.sql.advise.SqlAdvisorValidator;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.catalog.CatalogManager;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import org.apache.flink.table.delegation.Parser;
import org.apache.flink.table.expressions.ResolvedExpression;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.planner.calcite.FlinkPlannerImpl;
import org.apache.flink.table.planner.calcite.FlinkTypeFactory;
import org.apache.flink.table.planner.calcite.SqlExprToRexConverter;
import org.apache.flink.table.planner.calcite.SqlExprToRexConverterFactory;
import org.apache.flink.table.planner.expressions.RexNodeExpression;
import org.apache.flink.table.planner.operations.SqlToOperationConverter;
import org.apache.flink.table.planner.parse.CalciteParser;
import org.apache.flink.table.planner.parse.ExtendedParser;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.RowType;
import org.apache.flink.table.types.utils.TypeConversions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
/** Implementation of {@link Parser} that uses Calcite. */
public class ParserImpl implements Parser {
private final CatalogManager catalogManager;
// we use supplier pattern here in order to use the most up to
// date configuration. Users might change the parser configuration in a TableConfig in between
// multiple statements parsing
private final Supplier<FlinkPlannerImpl> validatorSupplier;
private final Supplier<CalciteParser> calciteParserSupplier;
private final SqlExprToRexConverterFactory sqlExprToRexConverterFactory;
private static final ExtendedParser EXTENDED_PARSER = ExtendedParser.INSTANCE;
public ParserImpl(
CatalogManager catalogManager,
Supplier<FlinkPlannerImpl> validatorSupplier,
Supplier<CalciteParser> calciteParserSupplier,
SqlExprToRexConverterFactory sqlExprToRexConverterFactory) {
this.catalogManager = catalogManager;
this.validatorSupplier = validatorSupplier;
this.calciteParserSupplier = calciteParserSupplier;
this.sqlExprToRexConverterFactory = sqlExprToRexConverterFactory;
}
/**
* When parsing statement, it first uses {@link ExtendedParser} to parse statements. If {@link
* ExtendedParser} fails to parse statement, it uses the {@link CalciteParser} to parse
* statements.
*
* @param statement input statement.
* @return parsed operations.
*/
@Override
public List<Operation> parse(String statement) {
CalciteParser parser = calciteParserSupplier.get();
FlinkPlannerImpl planner = validatorSupplier.get();
Optional<Operation> command = EXTENDED_PARSER.parse(statement);
if (command.isPresent()) {
return Collections.singletonList(command.get());
}
// parse the sql query
SqlNode parsed = parser.parse(statement);
Operation operation =
SqlToOperationConverter.convert(planner, catalogManager, parsed)
.orElseThrow(() -> new TableException("Unsupported query: " + statement));
return Collections.singletonList(operation);
}
@Override
public UnresolvedIdentifier parseIdentifier(String identifier) {
CalciteParser parser = calciteParserSupplier.get();
SqlIdentifier sqlIdentifier = parser.parseIdentifier(identifier);
return UnresolvedIdentifier.of(sqlIdentifier.names);
}
@Override
public ResolvedExpression parseSqlExpression(
String sqlExpression, RowType inputRowType, @Nullable LogicalType outputType) {
final SqlExprToRexConverter sqlExprToRexConverter =
sqlExprToRexConverterFactory.create(inputRowType, outputType);
final RexNode rexNode = sqlExprToRexConverter.convertToRexNode(sqlExpression);
final LogicalType logicalType = FlinkTypeFactory.toLogicalType(rexNode.getType());
// expand expression for serializable expression strings similar to views
final String sqlExpressionExpanded = sqlExprToRexConverter.expand(sqlExpression);
return new RexNodeExpression(
rexNode,
TypeConversions.fromLogicalToDataType(logicalType),
sqlExpression,
sqlExpressionExpanded);
}
public String[] getCompletionHints(String statement, int cursor) {
List<String> candidates =
new ArrayList<>(
Arrays.asList(EXTENDED_PARSER.getCompletionHints(statement, cursor)));
// use sql advisor
SqlAdvisorValidator validator = validatorSupplier.get().getSqlAdvisorValidator();
SqlAdvisor advisor =
new SqlAdvisor(validator, validatorSupplier.get().config().getParserConfig());
String[] replaced = new String[1];
List<String> sqlHints =
advisor.getCompletionHints(statement, cursor, replaced).stream()
.map(item -> item.toIdentifier().toString())
.collect(Collectors.toList());
candidates.addAll(sqlHints);
return candidates.toArray(new String[0]);
}
public CatalogManager getCatalogManager() {
return catalogManager;
}
@Override
public SqlNode parseExpression(String sqlExpression) {
return calciteParserSupplier.get().parseExpression(sqlExpression);
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.calcite.sql;
import org.dinky.context.CustomTableEnvironmentContext;
import org.dinky.context.RowLevelPermissionsContext;
import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.sql.validate.SqlValidator;
import org.apache.calcite.sql.validate.SqlValidatorScope;
import org.apache.calcite.util.ImmutableNullableList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableList;
/**
* A <code>SqlSelect</code> is a node of a parse tree which represents a select statement. It
* warrants its own node type just because we have a lot of methods to put somewhere.
*
* @description: Modify the value method of where to addCondition() to support row-level permission
* filtering
*/
public class SqlSelect extends SqlCall {
private static final Logger LOG = LoggerFactory.getLogger(SqlSelect.class);
public static final int FROM_OPERAND = 2;
public static final int WHERE_OPERAND = 3;
public static final int HAVING_OPERAND = 5;
SqlNodeList keywordList;
SqlNodeList selectList;
SqlNode from;
SqlNode where;
SqlNodeList groupBy;
SqlNode having;
SqlNodeList windowDecls;
SqlNodeList orderBy;
SqlNode offset;
SqlNode fetch;
SqlNodeList hints;
public SqlSelect(
SqlParserPos pos,
SqlNodeList keywordList,
SqlNodeList selectList,
SqlNode from,
SqlNode where,
SqlNodeList groupBy,
SqlNode having,
SqlNodeList windowDecls,
SqlNodeList orderBy,
SqlNode offset,
SqlNode fetch,
SqlNodeList hints) {
super(pos);
this.keywordList =
Objects.requireNonNull(keywordList != null ? keywordList : new SqlNodeList(pos));
this.selectList = selectList;
this.from = from;
this.groupBy = groupBy;
this.having = having;
this.windowDecls =
Objects.requireNonNull(windowDecls != null ? windowDecls : new SqlNodeList(pos));
this.orderBy = orderBy;
this.offset = offset;
this.fetch = fetch;
this.hints = hints;
// add row level filter condition for where clause
this.where = addCondition(from, where, false);
}
/** The main process of controlling row-level permissions */
private SqlNode addCondition(SqlNode from, SqlNode where, boolean fromJoin) {
if (from instanceof SqlIdentifier) {
String tableName = from.toString();
// the table name is used as an alias for join
String tableAlias = fromJoin ? tableName : null;
return addPermission(where, tableName, tableAlias);
} else if (from instanceof SqlJoin) {
SqlJoin sqlJoin = (SqlJoin) from;
// support recursive processing, such as join for three tables, process left sqlNode
where = addCondition(sqlJoin.getLeft(), where, true);
// process right sqlNode
return addCondition(sqlJoin.getRight(), where, true);
} else if (from instanceof SqlBasicCall) {
// Table has an alias or comes from a subquery
SqlNode[] tableNodes = ((SqlBasicCall) from).getOperands();
/**
* If there is a subquery in the Join, row-level filtering has been appended to the
* subquery. What is returned here is the SqlSelect type, just return the original where
* directly
*/
if (!(tableNodes[0] instanceof SqlIdentifier)) {
return where;
}
String tableName = tableNodes[0].toString();
String tableAlias = tableNodes[1].toString();
return addPermission(where, tableName, tableAlias);
}
return where;
}
/** Add row-level filtering based on user-configured permission points */
private SqlNode addPermission(SqlNode where, String tableName, String tableAlias) {
SqlBasicCall permissions = null;
ConcurrentHashMap<String, String> permissionsMap = RowLevelPermissionsContext.get();
if (permissionsMap != null) {
String permissionsStatement = permissionsMap.get(tableName);
if (permissionsStatement != null && !"".equals(permissionsStatement)) {
permissions =
(SqlBasicCall)
CustomTableEnvironmentContext.get()
.getParser()
.parseExpression(permissionsStatement);
}
}
// add an alias
if (permissions != null && tableAlias != null) {
ImmutableList<String> namesList =
ImmutableList.of(tableAlias, permissions.getOperands()[0].toString());
permissions.getOperands()[0] =
new SqlIdentifier(namesList, null, new SqlParserPos(0, 0), null);
}
return buildWhereClause(where, permissions);
}
/** Rebuild the where clause */
private SqlNode buildWhereClause(SqlNode where, SqlBasicCall permissions) {
if (permissions != null) {
if (where == null) {
return permissions;
}
SqlBinaryOperator sqlBinaryOperator =
new SqlBinaryOperator(
SqlKind.AND.name(), SqlKind.AND, 0, true, null, null, null);
SqlNode[] operands = new SqlNode[2];
operands[0] = where;
operands[1] = permissions;
SqlParserPos sqlParserPos = new SqlParserPos(0, 0);
return new SqlBasicCall(sqlBinaryOperator, operands, sqlParserPos);
}
return where;
}
@Override
public SqlOperator getOperator() {
return SqlSelectOperator.INSTANCE;
}
@Override
public SqlKind getKind() {
return SqlKind.SELECT;
}
@Override
public List<SqlNode> getOperandList() {
return ImmutableNullableList.of(
keywordList,
selectList,
from,
where,
groupBy,
having,
windowDecls,
orderBy,
offset,
fetch,
hints);
}
@Override
public void setOperand(int i, SqlNode operand) {
switch (i) {
case 0:
keywordList = Objects.requireNonNull((SqlNodeList) operand);
break;
case 1:
selectList = (SqlNodeList) operand;
break;
case 2:
from = operand;
break;
case 3:
where = operand;
break;
case 4:
groupBy = (SqlNodeList) operand;
break;
case 5:
having = operand;
break;
case 6:
windowDecls = Objects.requireNonNull((SqlNodeList) operand);
break;
case 7:
orderBy = (SqlNodeList) operand;
break;
case 8:
offset = operand;
break;
case 9:
fetch = operand;
break;
default:
throw new AssertionError(i);
}
}
public final boolean isDistinct() {
return getModifierNode(SqlSelectKeyword.DISTINCT) != null;
}
public final SqlNode getModifierNode(SqlSelectKeyword modifier) {
for (SqlNode keyword : keywordList) {
SqlSelectKeyword keyword2 = ((SqlLiteral) keyword).symbolValue(SqlSelectKeyword.class);
if (keyword2 == modifier) {
return keyword;
}
}
return null;
}
public final SqlNode getFrom() {
return from;
}
public void setFrom(SqlNode from) {
this.from = from;
}
public final SqlNodeList getGroup() {
return groupBy;
}
public void setGroupBy(SqlNodeList groupBy) {
this.groupBy = groupBy;
}
public final SqlNode getHaving() {
return having;
}
public void setHaving(SqlNode having) {
this.having = having;
}
public final SqlNodeList getSelectList() {
return selectList;
}
public void setSelectList(SqlNodeList selectList) {
this.selectList = selectList;
}
public final SqlNode getWhere() {
return where;
}
public void setWhere(SqlNode whereClause) {
this.where = whereClause;
}
@Nonnull
public final SqlNodeList getWindowList() {
return windowDecls;
}
public final SqlNodeList getOrderList() {
return orderBy;
}
public void setOrderBy(SqlNodeList orderBy) {
this.orderBy = orderBy;
}
public final SqlNode getOffset() {
return offset;
}
public void setOffset(SqlNode offset) {
this.offset = offset;
}
public final SqlNode getFetch() {
return fetch;
}
public void setFetch(SqlNode fetch) {
this.fetch = fetch;
}
public void setHints(SqlNodeList hints) {
this.hints = hints;
}
public SqlNodeList getHints() {
return this.hints;
}
public boolean hasHints() {
// The hints may be passed as null explicitly.
return this.hints != null && this.hints.size() > 0;
}
@Override
public void validate(SqlValidator validator, SqlValidatorScope scope) {
validator.validateQuery(this, scope, validator.getUnknownType());
}
/** Override SqlCall, to introduce a sub-query frame. */
@Override
public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {
if (!writer.inQuery()) {
// If this SELECT is the topmost item in a sub-query, introduce a new
// frame. (The topmost item in the sub-query might be a UNION or
// ORDER. In this case, we don't need a wrapper frame.)
final SqlWriter.Frame frame =
writer.startList(SqlWriter.FrameTypeEnum.SUB_QUERY, "(", ")");
writer.getDialect().unparseCall(writer, this, 0, 0);
writer.endList(frame);
} else {
writer.getDialect().unparseCall(writer, this, leftPrec, rightPrec);
}
}
public boolean hasOrderBy() {
return orderBy != null && orderBy.size() != 0;
}
public boolean hasWhere() {
return where != null;
}
public boolean isKeywordPresent(SqlSelectKeyword targetKeyWord) {
return getModifierNode(targetKeyWord) != null;
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.flink.table.delegation;
import org.apache.calcite.sql.SqlNode;
import org.apache.flink.annotation.Internal;
import org.apache.flink.table.api.SqlParserException;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import org.apache.flink.table.expressions.ResolvedExpression;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.operations.QueryOperation;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.RowType;
import java.util.List;
import javax.annotation.Nullable;
/** Provides methods for parsing SQL objects from a SQL string. */
@Internal
public interface Parser {
/**
* Entry point for parsing SQL queries expressed as a String.
*
* <p><b>Note:</b>If the created {@link Operation} is a {@link QueryOperation} it must be in a
* form that will be understood by the {@link Planner#translate(List)} method.
*
* <p>The produced Operation trees should already be validated.
*
* @param statement the SQL statement to evaluate
* @return parsed queries as trees of relational {@link Operation}s
* @throws SqlParserException when failed to parse the statement
*/
List<Operation> parse(String statement);
/**
* Entry point for parsing SQL identifiers expressed as a String.
*
* @param identifier the SQL identifier to parse
* @return parsed identifier
* @throws SqlParserException when failed to parse the identifier
*/
UnresolvedIdentifier parseIdentifier(String identifier);
/**
* Entry point for parsing SQL expressions expressed as a String.
*
* @param sqlExpression the SQL expression to parse
* @param inputRowType the fields available in the SQL expression
* @param outputType expected top-level output type if available
* @return resolved expression
* @throws SqlParserException when failed to parse the sql expression
*/
ResolvedExpression parseSqlExpression(
String sqlExpression, RowType inputRowType, @Nullable LogicalType outputType);
/**
* Returns completion hints for the given statement at the given cursor position. The completion
* happens case insensitively.
*
* @param statement Partial or slightly incorrect SQL statement
* @param position cursor position
* @return completion hints that fit at the current cursor position
*/
String[] getCompletionHints(String statement, int position);
/**
* Parses a SQL expression into a {@link SqlNode}. The {@link SqlNode} is not yet validated.
*
* @param sqlExpression a SQL expression string to parse
* @return a parsed SQL node
* @throws SqlParserException if an exception is thrown when parsing the statement
*/
SqlNode parseExpression(String sqlExpression);
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.flink.table.planner.delegation;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.sql.SqlIdentifier;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.SqlNodeList;
import org.apache.calcite.sql.advise.SqlAdvisor;
import org.apache.calcite.sql.advise.SqlAdvisorValidator;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.catalog.CatalogManager;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import org.apache.flink.table.delegation.Parser;
import org.apache.flink.table.expressions.ResolvedExpression;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.planner.calcite.FlinkPlannerImpl;
import org.apache.flink.table.planner.calcite.FlinkTypeFactory;
import org.apache.flink.table.planner.calcite.SqlExprToRexConverter;
import org.apache.flink.table.planner.calcite.SqlExprToRexConverterFactory;
import org.apache.flink.table.planner.expressions.RexNodeExpression;
import org.apache.flink.table.planner.operations.SqlToOperationConverter;
import org.apache.flink.table.planner.parse.CalciteParser;
import org.apache.flink.table.planner.parse.ExtendedParser;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.RowType;
import org.apache.flink.table.types.utils.TypeConversions;
import org.apache.flink.util.Preconditions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
/** Implementation of {@link Parser} that uses Calcite. */
public class ParserImpl implements Parser {
private final CatalogManager catalogManager;
// we use supplier pattern here in order to use the most up to
// date configuration. Users might change the parser configuration in a TableConfig in between
// multiple statements parsing
private final Supplier<FlinkPlannerImpl> validatorSupplier;
private final Supplier<CalciteParser> calciteParserSupplier;
private final SqlExprToRexConverterFactory sqlExprToRexConverterFactory;
private static final ExtendedParser EXTENDED_PARSER = ExtendedParser.INSTANCE;
public ParserImpl(
CatalogManager catalogManager,
Supplier<FlinkPlannerImpl> validatorSupplier,
Supplier<CalciteParser> calciteParserSupplier,
SqlExprToRexConverterFactory sqlExprToRexConverterFactory) {
this.catalogManager = catalogManager;
this.validatorSupplier = validatorSupplier;
this.calciteParserSupplier = calciteParserSupplier;
this.sqlExprToRexConverterFactory = sqlExprToRexConverterFactory;
}
/**
* When parsing statement, it first uses {@link ExtendedParser} to parse statements. If {@link
* ExtendedParser} fails to parse statement, it uses the {@link CalciteParser} to parse
* statements.
*
* @param statement input statement.
* @return parsed operations.
*/
@Override
public List<Operation> parse(String statement) {
CalciteParser parser = calciteParserSupplier.get();
FlinkPlannerImpl planner = validatorSupplier.get();
Optional<Operation> command = EXTENDED_PARSER.parse(statement);
if (command.isPresent()) {
return Collections.singletonList(command.get());
}
// parse the sql query
// use parseSqlList here because we need to support statement end with ';' in sql client.
SqlNodeList sqlNodeList = parser.parseSqlList(statement);
List<SqlNode> parsed = sqlNodeList.getList();
Preconditions.checkArgument(parsed.size() == 1, "only single statement supported");
return Collections.singletonList(
SqlToOperationConverter.convert(planner, catalogManager, parsed.get(0))
.orElseThrow(() -> new TableException("Unsupported query: " + statement)));
}
@Override
public UnresolvedIdentifier parseIdentifier(String identifier) {
CalciteParser parser = calciteParserSupplier.get();
SqlIdentifier sqlIdentifier = parser.parseIdentifier(identifier);
return UnresolvedIdentifier.of(sqlIdentifier.names);
}
@Override
public ResolvedExpression parseSqlExpression(
String sqlExpression, RowType inputRowType, @Nullable LogicalType outputType) {
final SqlExprToRexConverter sqlExprToRexConverter =
sqlExprToRexConverterFactory.create(inputRowType, outputType);
final RexNode rexNode = sqlExprToRexConverter.convertToRexNode(sqlExpression);
final LogicalType logicalType = FlinkTypeFactory.toLogicalType(rexNode.getType());
// expand expression for serializable expression strings similar to views
final String sqlExpressionExpanded = sqlExprToRexConverter.expand(sqlExpression);
return new RexNodeExpression(
rexNode,
TypeConversions.fromLogicalToDataType(logicalType),
sqlExpression,
sqlExpressionExpanded);
}
public String[] getCompletionHints(String statement, int cursor) {
List<String> candidates =
new ArrayList<>(
Arrays.asList(EXTENDED_PARSER.getCompletionHints(statement, cursor)));
// use sql advisor
SqlAdvisorValidator validator = validatorSupplier.get().getSqlAdvisorValidator();
SqlAdvisor advisor =
new SqlAdvisor(validator, validatorSupplier.get().config().getParserConfig());
String[] replaced = new String[1];
List<String> sqlHints =
advisor.getCompletionHints(statement, cursor, replaced).stream()
.map(item -> item.toIdentifier().toString())
.collect(Collectors.toList());
candidates.addAll(sqlHints);
return candidates.toArray(new String[0]);
}
public CatalogManager getCatalogManager() {
return catalogManager;
}
@Override
public SqlNode parseExpression(String sqlExpression) {
return calciteParserSupplier.get().parseExpression(sqlExpression);
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.calcite.sql;
import org.dinky.context.CustomTableEnvironmentContext;
import org.dinky.context.RowLevelPermissionsContext;
import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.sql.validate.SqlValidator;
import org.apache.calcite.sql.validate.SqlValidatorScope;
import org.apache.calcite.util.ImmutableNullableList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableList;
/**
* A <code>SqlSelect</code> is a node of a parse tree which represents a select statement. It
* warrants its own node type just because we have a lot of methods to put somewhere.
*
* @description: Modify the value method of where to addCondition() to support row-level permission
* filtering
*/
public class SqlSelect extends SqlCall {
private static final Logger LOG = LoggerFactory.getLogger(SqlSelect.class);
public static final int FROM_OPERAND = 2;
public static final int WHERE_OPERAND = 3;
public static final int HAVING_OPERAND = 5;
SqlNodeList keywordList;
SqlNodeList selectList;
SqlNode from;
SqlNode where;
SqlNodeList groupBy;
SqlNode having;
SqlNodeList windowDecls;
SqlNodeList orderBy;
SqlNode offset;
SqlNode fetch;
SqlNodeList hints;
public SqlSelect(
SqlParserPos pos,
SqlNodeList keywordList,
SqlNodeList selectList,
SqlNode from,
SqlNode where,
SqlNodeList groupBy,
SqlNode having,
SqlNodeList windowDecls,
SqlNodeList orderBy,
SqlNode offset,
SqlNode fetch,
SqlNodeList hints) {
super(pos);
this.keywordList =
Objects.requireNonNull(keywordList != null ? keywordList : new SqlNodeList(pos));
this.selectList = selectList;
this.from = from;
this.groupBy = groupBy;
this.having = having;
this.windowDecls =
Objects.requireNonNull(windowDecls != null ? windowDecls : new SqlNodeList(pos));
this.orderBy = orderBy;
this.offset = offset;
this.fetch = fetch;
this.hints = hints;
// add row level filter condition for where clause
this.where = addCondition(from, where, false);
}
/** The main process of controlling row-level permissions */
private SqlNode addCondition(SqlNode from, SqlNode where, boolean fromJoin) {
if (from instanceof SqlIdentifier) {
String tableName = from.toString();
// the table name is used as an alias for join
String tableAlias = fromJoin ? tableName : null;
return addPermission(where, tableName, tableAlias);
} else if (from instanceof SqlJoin) {
SqlJoin sqlJoin = (SqlJoin) from;
// support recursive processing, such as join for three tables, process left sqlNode
where = addCondition(sqlJoin.getLeft(), where, true);
// process right sqlNode
return addCondition(sqlJoin.getRight(), where, true);
} else if (from instanceof SqlBasicCall) {
// Table has an alias or comes from a subquery
SqlNode[] tableNodes = ((SqlBasicCall) from).getOperands();
/**
* If there is a subquery in the Join, row-level filtering has been appended to the
* subquery. What is returned here is the SqlSelect type, just return the original where
* directly
*/
if (!(tableNodes[0] instanceof SqlIdentifier)) {
return where;
}
String tableName = tableNodes[0].toString();
String tableAlias = tableNodes[1].toString();
return addPermission(where, tableName, tableAlias);
}
return where;
}
/** Add row-level filtering based on user-configured permission points */
private SqlNode addPermission(SqlNode where, String tableName, String tableAlias) {
SqlBasicCall permissions = null;
ConcurrentHashMap<String, String> permissionsMap = RowLevelPermissionsContext.get();
if (permissionsMap != null) {
String permissionsStatement = permissionsMap.get(tableName);
if (permissionsStatement != null && !"".equals(permissionsStatement)) {
permissions =
(SqlBasicCall)
CustomTableEnvironmentContext.get()
.getParser()
.parseExpression(permissionsStatement);
}
}
// add an alias
if (permissions != null && tableAlias != null) {
ImmutableList<String> namesList =
ImmutableList.of(tableAlias, permissions.getOperands()[0].toString());
permissions.getOperands()[0] =
new SqlIdentifier(namesList, null, new SqlParserPos(0, 0), null);
}
return buildWhereClause(where, permissions);
}
/** Rebuild the where clause */
private SqlNode buildWhereClause(SqlNode where, SqlBasicCall permissions) {
if (permissions != null) {
if (where == null) {
return permissions;
}
SqlBinaryOperator sqlBinaryOperator =
new SqlBinaryOperator(
SqlKind.AND.name(), SqlKind.AND, 0, true, null, null, null);
SqlNode[] operands = new SqlNode[2];
operands[0] = where;
operands[1] = permissions;
SqlParserPos sqlParserPos = new SqlParserPos(0, 0);
return new SqlBasicCall(sqlBinaryOperator, operands, sqlParserPos);
}
return where;
}
@Override
public SqlOperator getOperator() {
return SqlSelectOperator.INSTANCE;
}
@Override
public SqlKind getKind() {
return SqlKind.SELECT;
}
@Override
public List<SqlNode> getOperandList() {
return ImmutableNullableList.of(
keywordList,
selectList,
from,
where,
groupBy,
having,
windowDecls,
orderBy,
offset,
fetch,
hints);
}
@Override
public void setOperand(int i, SqlNode operand) {
switch (i) {
case 0:
keywordList = Objects.requireNonNull((SqlNodeList) operand);
break;
case 1:
selectList = (SqlNodeList) operand;
break;
case 2:
from = operand;
break;
case 3:
where = operand;
break;
case 4:
groupBy = (SqlNodeList) operand;
break;
case 5:
having = operand;
break;
case 6:
windowDecls = Objects.requireNonNull((SqlNodeList) operand);
break;
case 7:
orderBy = (SqlNodeList) operand;
break;
case 8:
offset = operand;
break;
case 9:
fetch = operand;
break;
default:
throw new AssertionError(i);
}
}
public final boolean isDistinct() {
return getModifierNode(SqlSelectKeyword.DISTINCT) != null;
}
public final SqlNode getModifierNode(SqlSelectKeyword modifier) {
for (SqlNode keyword : keywordList) {
SqlSelectKeyword keyword2 = ((SqlLiteral) keyword).symbolValue(SqlSelectKeyword.class);
if (keyword2 == modifier) {
return keyword;
}
}
return null;
}
public final SqlNode getFrom() {
return from;
}
public void setFrom(SqlNode from) {
this.from = from;
}
public final SqlNodeList getGroup() {
return groupBy;
}
public void setGroupBy(SqlNodeList groupBy) {
this.groupBy = groupBy;
}
public final SqlNode getHaving() {
return having;
}
public void setHaving(SqlNode having) {
this.having = having;
}
public final SqlNodeList getSelectList() {
return selectList;
}
public void setSelectList(SqlNodeList selectList) {
this.selectList = selectList;
}
public final SqlNode getWhere() {
return where;
}
public void setWhere(SqlNode whereClause) {
this.where = whereClause;
}
@Nonnull
public final SqlNodeList getWindowList() {
return windowDecls;
}
public final SqlNodeList getOrderList() {
return orderBy;
}
public void setOrderBy(SqlNodeList orderBy) {
this.orderBy = orderBy;
}
public final SqlNode getOffset() {
return offset;
}
public void setOffset(SqlNode offset) {
this.offset = offset;
}
public final SqlNode getFetch() {
return fetch;
}
public void setFetch(SqlNode fetch) {
this.fetch = fetch;
}
public void setHints(SqlNodeList hints) {
this.hints = hints;
}
public SqlNodeList getHints() {
return this.hints;
}
public boolean hasHints() {
// The hints may be passed as null explicitly.
return this.hints != null && this.hints.size() > 0;
}
@Override
public void validate(SqlValidator validator, SqlValidatorScope scope) {
validator.validateQuery(this, scope, validator.getUnknownType());
}
/** Override SqlCall, to introduce a sub-query frame. */
@Override
public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {
if (!writer.inQuery()) {
// If this SELECT is the topmost item in a sub-query, introduce a new
// frame. (The topmost item in the sub-query might be a UNION or
// ORDER. In this case, we don't need a wrapper frame.)
final SqlWriter.Frame frame =
writer.startList(SqlWriter.FrameTypeEnum.SUB_QUERY, "(", ")");
writer.getDialect().unparseCall(writer, this, 0, 0);
writer.endList(frame);
} else {
writer.getDialect().unparseCall(writer, this, leftPrec, rightPrec);
}
}
public boolean hasOrderBy() {
return orderBy != null && orderBy.size() != 0;
}
public boolean hasWhere() {
return where != null;
}
public boolean isKeywordPresent(SqlSelectKeyword targetKeyWord) {
return getModifierNode(targetKeyWord) != null;
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.flink.table.delegation;
import org.apache.calcite.sql.SqlNode;
import org.apache.flink.annotation.Internal;
import org.apache.flink.table.api.SqlParserException;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import org.apache.flink.table.expressions.ResolvedExpression;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.operations.QueryOperation;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.RowType;
import java.util.List;
import javax.annotation.Nullable;
/** Provides methods for parsing SQL objects from a SQL string. */
@Internal
public interface Parser {
/**
* Entry point for parsing SQL queries expressed as a String.
*
* <p><b>Note:</b>If the created {@link Operation} is a {@link QueryOperation} it must be in a
* form that will be understood by the {@link Planner#translate(List)} method.
*
* <p>The produced Operation trees should already be validated.
*
* @param statement the SQL statement to evaluate
* @return parsed queries as trees of relational {@link Operation}s
* @throws SqlParserException when failed to parse the statement
*/
List<Operation> parse(String statement);
/**
* Entry point for parsing SQL identifiers expressed as a String.
*
* @param identifier the SQL identifier to parse
* @return parsed identifier
* @throws SqlParserException when failed to parse the identifier
*/
UnresolvedIdentifier parseIdentifier(String identifier);
/**
* Entry point for parsing SQL expressions expressed as a String.
*
* @param sqlExpression the SQL expression to parse
* @param inputRowType the fields available in the SQL expression
* @param outputType expected top-level output type if available
* @return resolved expression
* @throws SqlParserException when failed to parse the sql expression
*/
ResolvedExpression parseSqlExpression(
String sqlExpression, RowType inputRowType, @Nullable LogicalType outputType);
/**
* Returns completion hints for the given statement at the given cursor position. The completion
* happens case insensitively.
*
* @param statement Partial or slightly incorrect SQL statement
* @param position cursor position
* @return completion hints that fit at the current cursor position
*/
String[] getCompletionHints(String statement, int position);
/**
* Parses a SQL expression into a {@link SqlNode}. The {@link SqlNode} is not yet validated.
*
* @param sqlExpression a SQL expression string to parse
* @return a parsed SQL node
* @throws SqlParserException if an exception is thrown when parsing the statement
*/
SqlNode parseExpression(String sqlExpression);
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.flink.table.planner.delegation;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.sql.SqlIdentifier;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.SqlNodeList;
import org.apache.calcite.sql.advise.SqlAdvisor;
import org.apache.calcite.sql.advise.SqlAdvisorValidator;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.api.ValidationException;
import org.apache.flink.table.catalog.CatalogManager;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import org.apache.flink.table.delegation.Parser;
import org.apache.flink.table.expressions.ResolvedExpression;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.planner.calcite.FlinkPlannerImpl;
import org.apache.flink.table.planner.calcite.FlinkTypeFactory;
import org.apache.flink.table.planner.calcite.RexFactory;
import org.apache.flink.table.planner.calcite.SqlToRexConverter;
import org.apache.flink.table.planner.expressions.RexNodeExpression;
import org.apache.flink.table.planner.operations.SqlToOperationConverter;
import org.apache.flink.table.planner.parse.CalciteParser;
import org.apache.flink.table.planner.parse.ExtendedParser;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.RowType;
import org.apache.flink.table.types.utils.TypeConversions;
import org.apache.flink.util.Preconditions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
/** Implementation of {@link Parser} that uses Calcite. */
public class ParserImpl implements Parser {
private final CatalogManager catalogManager;
// we use supplier pattern here in order to use the most up to
// date configuration. Users might change the parser configuration in a TableConfig in between
// multiple statements parsing
private final Supplier<FlinkPlannerImpl> validatorSupplier;
private final Supplier<CalciteParser> calciteParserSupplier;
private final RexFactory rexFactory;
private static final ExtendedParser EXTENDED_PARSER = ExtendedParser.INSTANCE;
public ParserImpl(
CatalogManager catalogManager,
Supplier<FlinkPlannerImpl> validatorSupplier,
Supplier<CalciteParser> calciteParserSupplier,
RexFactory rexFactory) {
this.catalogManager = catalogManager;
this.validatorSupplier = validatorSupplier;
this.calciteParserSupplier = calciteParserSupplier;
this.rexFactory = rexFactory;
}
/**
* When parsing statement, it first uses {@link ExtendedParser} to parse statements. If {@link
* ExtendedParser} fails to parse statement, it uses the {@link CalciteParser} to parse
* statements.
*
* @param statement input statement.
* @return parsed operations.
*/
@Override
public List<Operation> parse(String statement) {
CalciteParser parser = calciteParserSupplier.get();
FlinkPlannerImpl planner = validatorSupplier.get();
Optional<Operation> command = EXTENDED_PARSER.parse(statement);
if (command.isPresent()) {
return Collections.singletonList(command.get());
}
// parse the sql query
// use parseSqlList here because we need to support statement end with ';' in sql client.
SqlNodeList sqlNodeList = parser.parseSqlList(statement);
List<SqlNode> parsed = sqlNodeList.getList();
Preconditions.checkArgument(parsed.size() == 1, "only single statement supported");
return Collections.singletonList(
SqlToOperationConverter.convert(planner, catalogManager, parsed.get(0))
.orElseThrow(() -> new TableException("Unsupported query: " + statement)));
}
@Override
public UnresolvedIdentifier parseIdentifier(String identifier) {
CalciteParser parser = calciteParserSupplier.get();
SqlIdentifier sqlIdentifier = parser.parseIdentifier(identifier);
return UnresolvedIdentifier.of(sqlIdentifier.names);
}
@Override
public ResolvedExpression parseSqlExpression(
String sqlExpression, RowType inputRowType, @Nullable LogicalType outputType) {
try {
final SqlToRexConverter sqlToRexConverter =
rexFactory.createSqlToRexConverter(inputRowType, outputType);
final RexNode rexNode = sqlToRexConverter.convertToRexNode(sqlExpression);
final LogicalType logicalType = FlinkTypeFactory.toLogicalType(rexNode.getType());
// expand expression for serializable expression strings similar to views
final String sqlExpressionExpanded = sqlToRexConverter.expand(sqlExpression);
return new RexNodeExpression(
rexNode,
TypeConversions.fromLogicalToDataType(logicalType),
sqlExpression,
sqlExpressionExpanded);
} catch (Throwable t) {
throw new ValidationException(
String.format("Invalid SQL expression: %s", sqlExpression), t);
}
}
public String[] getCompletionHints(String statement, int cursor) {
List<String> candidates =
new ArrayList<>(
Arrays.asList(EXTENDED_PARSER.getCompletionHints(statement, cursor)));
// use sql advisor
SqlAdvisorValidator validator = validatorSupplier.get().getSqlAdvisorValidator();
SqlAdvisor advisor =
new SqlAdvisor(validator, validatorSupplier.get().config().getParserConfig());
String[] replaced = new String[1];
List<String> sqlHints =
advisor.getCompletionHints(statement, cursor, replaced).stream()
.map(item -> item.toIdentifier().toString())
.collect(Collectors.toList());
candidates.addAll(sqlHints);
return candidates.toArray(new String[0]);
}
public CatalogManager getCatalogManager() {
return catalogManager;
}
@Override
public SqlNode parseExpression(String sqlExpression) {
return calciteParserSupplier.get().parseExpression(sqlExpression);
}
}
......@@ -19,6 +19,7 @@
package org.dinky.executor;
import org.apache.calcite.sql.SqlNode;
import org.apache.flink.table.catalog.UnresolvedIdentifier;
import org.apache.flink.table.delegation.Parser;
import org.apache.flink.table.expressions.ResolvedExpression;
......@@ -64,4 +65,9 @@ public class ParserWrapper implements Parser {
public String[] getCompletionHints(String statement, int position) {
return parser.getCompletionHints(statement, position);
}
@Override
public SqlNode parseExpression(String sqlExpression) {
return parser.parseExpression(sqlExpression);
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.context;
import org.dinky.executor.CustomTableEnvironment;
/** CustomTableEnvironmentContext */
public class CustomTableEnvironmentContext {
private static final ThreadLocal<CustomTableEnvironment> CUSTOM_TABLE_ENVIRONMENT_CONTEXT =
new ThreadLocal<>();
public static void set(CustomTableEnvironment value) {
CUSTOM_TABLE_ENVIRONMENT_CONTEXT.set(value);
}
public static CustomTableEnvironment get() {
return CUSTOM_TABLE_ENVIRONMENT_CONTEXT.get();
}
public static void clear() {
CUSTOM_TABLE_ENVIRONMENT_CONTEXT.remove();
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.context;
import java.util.concurrent.ConcurrentHashMap;
/** RowLevelPermissionsContext */
public class RowLevelPermissionsContext {
private static final ThreadLocal<ConcurrentHashMap<String, String>>
ROW_LEVEL_PERMISSIONS_CONTEXT = new ThreadLocal<>();
public static void set(ConcurrentHashMap<String, String> value) {
ROW_LEVEL_PERMISSIONS_CONTEXT.set(value);
}
public static ConcurrentHashMap<String, String> get() {
return ROW_LEVEL_PERMISSIONS_CONTEXT.get();
}
public static void clear() {
ROW_LEVEL_PERMISSIONS_CONTEXT.remove();
}
}
......@@ -26,8 +26,10 @@ import static org.dinky.function.util.UDFUtil.YARN;
import org.dinky.api.FlinkAPI;
import org.dinky.assertion.Asserts;
import org.dinky.constant.FlinkSQLConstant;
import org.dinky.context.CustomTableEnvironmentContext;
import org.dinky.context.DinkyClassLoaderContextHolder;
import org.dinky.context.JarPathContextHolder;
import org.dinky.context.RowLevelPermissionsContext;
import org.dinky.executor.EnvironmentSetting;
import org.dinky.executor.Executor;
import org.dinky.executor.ExecutorSetting;
......@@ -361,6 +363,8 @@ public class JobManager {
public boolean close() {
JobContextHolder.clear();
CustomTableEnvironmentContext.clear();
RowLevelPermissionsContext.clear();
return false;
}
......
......@@ -20,6 +20,7 @@
package org.dinky.executor;
import org.dinky.assertion.Asserts;
import org.dinky.context.CustomTableEnvironmentContext;
import org.dinky.context.DinkyClassLoaderContextHolder;
import org.dinky.interceptor.FlinkInterceptor;
import org.dinky.interceptor.FlinkInterceptorResult;
......@@ -185,6 +186,7 @@ public abstract class Executor {
private void initExecutionEnvironment() {
useSqlFragment = executorSetting.isUseSqlFragment();
tableEnvironment = createCustomTableEnvironment();
CustomTableEnvironmentContext.set(tableEnvironment);
tableEnvironment.injectParser(new CustomParserImpl());
tableEnvironment.injectExtendedExecutor(new CustomExtendedOperationExecutorImpl(this));
Configuration configuration = tableEnvironment.getConfig().getConfiguration();
......
......@@ -170,6 +170,12 @@ export default [
icon: 'TeamOutlined',
component: './AuthenticationCenter/RoleManager',
},
{
path: '/authenticationCenter/roleSelectPermissions',
name: 'roleSelectPermissions',
icon: 'FundViewOutlined',
component: './AuthenticationCenter/RoleSelectPermissions',
},
{
path: '/authenticationCenter/namespaceManager',
name: 'namespaceManager',
......
......@@ -51,6 +51,7 @@ export default {
'menu.authenticationCenter.userManager': 'User Management',
'menu.authenticationCenter.namespaceManager': 'NameSpace Management',
'menu.authenticationCenter.roleManager': 'Role Management',
'menu.authenticationCenter.roleSelectPermissions': 'Role Data Permissions',
'menu.authenticationCenter.tenantManager': 'Tenant Management',
'menu.settings': 'Setting Center',
......
......@@ -202,11 +202,11 @@ export default {
'pages.user.UserUpdateUser': 'Update User',
'pages.user.AssignRole': 'Assign Role',
'pages.user.delete': 'Delete User',
'pages.user.deleteConfirm': 'Are you sure you want to delete this User?',
'pages.user.deleteConfirm': 'Are you sure you want to delete this User?',
'pages.user.enable': 'Enable User',
'pages.user.enableConfirm': 'Are you sure you want to enable this User?',
'pages.user.enableConfirm': 'Are you sure you want to enable this User?',
'pages.user.disable': 'Disable User',
'pages.user.disableConfirm': 'Are you sure you want to disable this User?',
'pages.user.disableConfirm': 'Are you sure you want to disable this User?',
'pages.user.UserEnterUserName': 'Please enter user name',
'pages.user.UserEnterUniqueUserName': 'Please enter unique user name',
'pages.user.UserEnterJobNumber': 'Please enter job number',
......@@ -231,22 +231,22 @@ export default {
'pages.tenant.EnterTenantCode': 'Please enter Tenant Code!',
'pages.tenant.EnterTenantNote': 'Please enter Tenant Note!',
'pages.tenant.delete': 'Delete Tenant',
'pages.tenant.deleteConfirm': 'Are you sure you want to delete this Tenant?',
'pages.tenant.deleteConfirm': 'Are you sure you want to delete this Tenant?',
'pages.tenant.enable': 'Enable Tenant',
'pages.tenant.enableConfirm': 'Are you sure you want to enable this Tenant?',
'pages.tenant.enableConfirm': 'Are you sure you want to enable this Tenant?',
'pages.tenant.disable': 'Disable Tenant',
'pages.tenant.disableConfirm': 'Are you sure you want to disable this Tenant?',
'pages.tenant.disableConfirm': 'Are you sure you want to disable this Tenant?',
'pages.nameSpace.NameSpaceManagement': 'NameSpace Management',
'pages.nameSpace.NameSpaceCode': 'NameSpace Code',
'pages.nameSpace.belongTenant': 'Belong Tenant',
'pages.nameSpace.deleteNameSpace': 'Delete NameSpace',
'pages.nameSpace.deleteNameSpaceConfirm': 'Are you sure you want to delete this NameSpace?',
'pages.nameSpace.deleteNameSpaceConfirm': 'Are you sure you want to delete this NameSpace?',
'pages.nameSpace.enableNameSpace': 'Enable NameSpace',
'pages.nameSpace.enableNameSpaceConfirm': 'Are you sure you want to enable this NameSpace?',
'pages.nameSpace.enableNameSpaceConfirm': 'Are you sure you want to enable this NameSpace?',
'pages.nameSpace.disableNameSpace': 'Disable NameSpace',
'pages.nameSpace.disableNameSpaceConfirm': 'Are you sure you want to disable this NameSpace?',
'pages.nameSpace.disableNameSpaceConfirm': 'Are you sure you want to disable this NameSpace?',
'pages.nameSpace.create': 'Create NameSpace',
'pages.nameSpace.update': 'Update NameSpace',
'pages.nameSpace.EnterNameSpaceCode': 'Please enter NameSpace Code!',
......@@ -260,16 +260,23 @@ export default {
'pages.role.belongTenant': 'Belong Tenant',
'pages.role.create': 'Create Role',
'pages.role.update': 'Update Role',
'pages.role.selectRole': 'Please select Role!',
'pages.role.EnterRoleCode': 'Please enter Role Code!',
'pages.role.EnterRoleName': 'Please enter Role Name!',
'pages.role.selectNameSpace': 'Please select NameSpace!',
'pages.role.EnterNote': 'Please enter Role Note!',
'pages.role.delete': 'Delete Role',
'pages.role.deleteConfirm': 'Are you sure you want to delete this Role?',
'pages.role.deleteConfirm': 'Are you sure you want to delete this Role?',
'pages.role.enable': 'Enable Role',
'pages.role.enableConfirm': 'Are you sure you want to enable this Role?',
'pages.role.enableConfirm': 'Are you sure you want to enable this Role?',
'pages.role.disable': 'Disable Role',
'pages.role.disableConfirm': 'Are you sure you want to disable this Role?',
'pages.role.disableConfirm': 'Are you sure you want to disable this Role?',
'pages.roleSelectPermissions.roleSelectPermissionsManagement': 'Role select permissions management',
'pages.roleSelectPermissions.tableName': 'Table name',
'pages.roleSelectPermissions.expression': 'Expression',
'pages.roleSelectPermissions.delete': 'Delete role data permissions',
'pages.roleSelectPermissions.deleteConfirm': 'Are you sure you want to delete this role select permissions?',
'pages.regist.openAPI': 'OpenAPI Document',
'pages.regist.BusinessComponent': 'Business Component Document',
......
......@@ -50,6 +50,7 @@ export default {
'menu.authenticationCenter.userManager': '用户管理',
'menu.authenticationCenter.namespaceManager': '命名空间管理',
'menu.authenticationCenter.roleManager': '角色管理',
'menu.authenticationCenter.roleSelectPermissions': '角色数据权限',
'menu.authenticationCenter.tenantManager': '租户管理',
'menu.settings': '配置中心',
......
......@@ -262,6 +262,7 @@ export default {
'pages.role.update': '修改角色',
'pages.role.EnterRoleCode': '请输入角色编码!',
'pages.role.EnterRoleName': '请输入角色名称!',
'pages.role.selectRole': '请选择角色!',
'pages.role.selectNameSpace': '请选择命名空间!',
'pages.role.EnterNote': '请输入角色的备注/描述信息!',
'pages.role.delete': '删除角色',
......@@ -271,11 +272,18 @@ export default {
'pages.role.disable': '禁用角色',
'pages.role.disableConfirm': '您确定要禁用此角色吗?',
'pages.roleSelectPermissions.roleSelectPermissionsManagement': '角色数据权限管理',
'pages.roleSelectPermissions.roleId': '角色 ID',
'pages.roleSelectPermissions.tableName': '表名',
'pages.roleSelectPermissions.expression': '表达式',
'pages.roleSelectPermissions.EnterTableName': '请输入表名称!',
'pages.roleSelectPermissions.EnterExpression': '请输入表达式!',
'pages.roleSelectPermissions.delete': '删除角色数据权限',
'pages.roleSelectPermissions.deleteConfirm': '您确定要删除此角色数据权限吗?',
'pages.regist.openAPI': 'OpenAPI 文档',
'pages.regist.BusinessComponent': '业务组件文档',
'pages.metadata.NoDatabaseSelected': '未选择数据源',
'pages.metadata.Application': 'Application',
'pages.metadata.TableInfo': '表信息',
......
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import React, {useState} from 'react';
import {Button, Form, Input, Modal, Select, Tag} from 'antd';
import {
RoleSelectPermissionsTableListItem,
RoleTableListItem
} from "@/pages/AuthenticationCenter/data.d";
import {connect} from "umi";
import {NameSpaceStateType} from "@/pages/AuthenticationCenter/RoleManager/model";
import {buildFormData, getFormData} from "@/pages/AuthenticationCenter/function";
import {l} from "@/utils/intl";
export type RoleSelectPermissionsFormProps = {
onCancel: (flag?: boolean) => void;
onSubmit: (values: Partial<RoleSelectPermissionsTableListItem>) => void;
modalVisible: boolean;
values: Partial<RoleSelectPermissionsTableListItem>;
role: RoleTableListItem[];
};
const formLayout = {
labelCol: {span: 7},
wrapperCol: {span: 13},
};
const Option = Select.Option;
const RoleSelectPermissionsForm: React.FC<RoleSelectPermissionsFormProps> = (props) => {
const [form] = Form.useForm();
const [formVals, setFormVals] = useState<Partial<RoleSelectPermissionsTableListItem>>({
id: props.values?.id,
roleId: props.values?.roleId,
tableName: props.values?.tableName,
roleName: props.values?.roleName,
expression: props.values?.expression,
createTime: props.values?.createTime,
updateTime: props.values?.updateTime,
});
const {
onSubmit: handleSubmit,
onCancel: handleModalVisible,
modalVisible,
role,
} = props;
const getRoleOptions = () => {
const itemList: JSX.Element[] = [];
for (const item of role) {
const tag = (
<>
<Tag color="processing">
{item.roleName}
</Tag>
</>);
itemList.push(<Option key={item.id} value={item.id} label={tag}>
{tag}
</Option>)
}
return itemList;
};
const submitForm = async () => {
const fieldsValue = await form.validateFields();
if(fieldsValue.roleId.length > 0){
fieldsValue.roleId = fieldsValue.roleId[0];
}else{
fieldsValue.roleId = null;
}
setFormVals(buildFormData(formVals, fieldsValue));
handleSubmit(buildFormData(formVals, fieldsValue));
};
const renderContent = (formVals) => {
return (
<>
<Form.Item
name="roleId"
label={l('pages.role.roleName')}
rules={[{required: true, message: l('pages.role.selectRole')}]}
>
<Select
mode="multiple"
style={{width: '100%'}}
placeholder={l('pages.role.selectRole')}
optionLabelProp="label"
>
{getRoleOptions()}
</Select>
</Form.Item>
<Form.Item
name="tableName"
label={l('pages.roleSelectPermissions.tableName')}
rules={[{required: true, message: l('pages.roleSelectPermissions.EnterTableName')}]}>
<Input placeholder={l('pages.roleSelectPermissions.EnterTableName')}/>
</Form.Item>
<Form.Item
name="expression"
label={l('pages.roleSelectPermissions.expression')}
>
<Input.TextArea placeholder={l('pages.roleSelectPermissions.EnterExpression')} allowClear
autoSize={{minRows: 3, maxRows: 10}}/>
</Form.Item>
</>
);
};
const renderFooter = () => {
return (
<>
<Button onClick={() => handleModalVisible(false)}>{l('button.cancel')}</Button>
<Button type="primary" onClick={() => submitForm()}>
{l('button.finish')}
</Button>
</>
);
};
return (
<Modal
width={"40%"}
bodyStyle={{padding: '32px 40px 48px'}}
destroyOnClose
title={formVals.id ? l('pages.role.update') : l('pages.role.create')}
visible={modalVisible}
footer={renderFooter()}
onCancel={() => handleModalVisible()}
>
<Form
{...formLayout}
form={form}
initialValues={getFormData(formVals)}
>
{renderContent(getFormData(formVals))}
</Form>
</Modal>
);
};
export default connect(({NameSpace}: { NameSpace: NameSpaceStateType }) => ({
role: NameSpace.role,
}))(RoleSelectPermissionsForm);
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import React, {useEffect, useRef, useState} from "react";
import {DownOutlined, PlusOutlined} from '@ant-design/icons';
import ProTable, {ActionType, ProColumns} from "@ant-design/pro-table";
import {Button, Dropdown, Menu, Modal} from 'antd';
import {FooterToolbar, PageContainer} from '@ant-design/pro-layout';
import {handleAddOrUpdate, handleRemove, queryData} from "@/components/Common/crud";
import {RoleSelectPermissionsTableListItem} from "@/pages/AuthenticationCenter/data.d";
import RoleSelectPermissionsForm from "@/pages/AuthenticationCenter/RoleSelectPermissions/components/RoleSelectPermissionsForm";
import {getRoleList} from "@/pages/AuthenticationCenter/service";
import {connect} from "umi";
import {l} from "@/utils/intl";
const url = '/api/roleSelectPermissions';
const RoleSelectPermissionsFormList: React.FC<{}> = (props: any) => {
const {dispatch} = props;
const [formValues, setFormValues] = useState<RoleSelectPermissionsTableListItem>();
const [modalVisible, handleModalVisible] = useState<boolean>(false);
const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
const actionRef = useRef<ActionType>();
const [selectedRowsState, setSelectedRows] = useState<RoleSelectPermissionsTableListItem[]>([]);
useEffect(() => {
getRoleList(dispatch);
}, []);
const editAndDelete = (key: string | number, currentItem: RoleSelectPermissionsTableListItem) => {
if (key === 'edit') {
setFormValues(currentItem);
handleUpdateModalVisible(true);
} else if (key === 'delete') {
Modal.confirm({
title: l('pages.role.delete'),
content: l('pages.role.deleteConfirm'),
okText: l('button.confirm'),
cancelText: l('button.cancel'),
onOk: async () => {
await handleRemove(url, [currentItem]);
actionRef.current?.reloadAndRest?.();
}
});
}
};
const MoreBtn: React.FC<{
item: RoleSelectPermissionsTableListItem;
}> = ({item}) => (
<Dropdown
overlay={
<Menu onClick={({key}) => editAndDelete(key, item)}>
<Menu.Item key="edit">{l('button.edit')}</Menu.Item>
<Menu.Item key="delete">{l('button.delete')}</Menu.Item>
</Menu>
}
>
<a>
{l('button.more')} <DownOutlined/>
</a>
</Dropdown>
);
const columns: ProColumns<RoleSelectPermissionsTableListItem>[] = [
{
title: 'ID',
dataIndex: 'id',
hideInTable: true,
hideInSearch: true,
sorter: true,
},
{
title: l('pages.roleSelectPermissions.roleId'),
dataIndex: 'roleId',
hideInTable: true,
hideInSearch: true,
},
{
title: l('pages.role.roleCode'),
dataIndex: 'roleCode',
},
{
title: l('pages.role.roleName'),
sorter: true,
dataIndex: 'roleName',
},
{
title: l('pages.roleSelectPermissions.tableName'),
sorter: true,
dataIndex: 'tableName',
},
{
title: l('pages.roleSelectPermissions.expression'),
dataIndex: 'expression',
hideInSearch: true,
ellipsis: true,
},
{
title: l('global.table.createTime'),
dataIndex: 'createTime',
sorter: true,
valueType: 'dateTime',
},
{
title: l('global.table.updateTime'),
dataIndex: 'updateTime',
sorter: true,
valueType: 'dateTime',
},
{
title: l('global.table.operate'),
dataIndex: 'option',
valueType: 'option',
render: (_, record) => [
<Button type={"link"}
onClick={() => {
handleUpdateModalVisible(true);
setFormValues(record);
}}
>
{l('button.config')}
</Button>,
<MoreBtn key="more" item={record}/>,
],
},
];
return (
<PageContainer title={false}>
<ProTable<RoleSelectPermissionsTableListItem>
headerTitle={l('pages.roleSelectPermissions.roleSelectPermissionsManagement')}
actionRef={actionRef}
rowKey="id"
search={{
labelWidth: 120,
}}
toolBarRender={() => [
<Button type="primary" onClick={() => handleModalVisible(true)}>
<PlusOutlined/> {l('button.create')}
</Button>,
]}
request={(params, sorter, filter) => queryData(url, {...params, sorter, filter})}
columns={columns}
rowSelection={{
onChange: (_, selectedRows) => setSelectedRows(selectedRows),
}}
pagination={{
defaultPageSize: 10,
showSizeChanger: true,
}}
/>
{selectedRowsState?.length > 0 && (
<FooterToolbar
extra={
<div>
{l('tips.selected', '',
{
total: <a
style={{fontWeight: 600}}>{selectedRowsState.length}</a>
})} &nbsp;&nbsp; </div>
}
>
<Button type="primary" danger
onClick={() => {
Modal.confirm({
title: l('pages.roleSelectPermissions.delete'),
content: l('pages.roleSelectPermissions.deleteConfirm'),
okText: l('button.confirm'),
cancelText: l('button.cancel'),
onOk: async () => {
await handleRemove(url, selectedRowsState);
setSelectedRows([]);
actionRef.current?.reloadAndRest?.();
}
});
}}
>
{l('button.batchDelete')}
</Button>
</FooterToolbar>
)}
<RoleSelectPermissionsForm
onSubmit={async (value) => {
const success = await handleAddOrUpdate(url, value);
if (success) {
handleModalVisible(false);
setFormValues({});
if (actionRef.current) {
actionRef.current.reload();
}
}
}}
onCancel={() => {
handleModalVisible(false);
}}
modalVisible={modalVisible}
values={{}}
/>
{
formValues && Object.keys(formValues).length ? (
<RoleSelectPermissionsForm
onSubmit={async (value) => {
const success = await handleAddOrUpdate(url, value);
if (success) {
handleUpdateModalVisible(false);
setFormValues({});
if (actionRef.current) {
actionRef.current.reload();
}
}
}}
onCancel={() => {
handleUpdateModalVisible(false);
setFormValues({});
}}
modalVisible={updateModalVisible}
values={formValues}
/>
) : undefined
}
</PageContainer>
);
};
export default connect()(RoleSelectPermissionsFormList);
......@@ -64,6 +64,16 @@ export type RoleTableListItem = {
updateTime?: Date;
};
export type RoleSelectPermissionsTableListItem = {
id?: number;
roleId?: number;
roleCode?: string;
roleName?: string;
tableName?: string;
expression?: string;
createTime?: Date;
updateTime?: Date;
};
export type NameSpaceTableListItem = {
id?: number;
......
......@@ -37,7 +37,7 @@ export function getRoleList(dispatch: any) {
const res = queryData('/api/role');
res.then((result) => {
result.data && dispatch && dispatch({
type: "Role/getRoleList",
type: "NameSpace/saveRole",
payload: result.data,
});
});
......
......@@ -1030,5 +1030,19 @@ CREATE TABLE `metadata_table_property` (
-- ----------------------------
-- ----------------------------
-- Table structure for dinky_role_select_permissions
-- ----------------------------
CREATE TABLE dinky_role_select_permissions
(
id int auto_increment comment 'ID'
primary key,
role_id int not null comment '角色ID',
table_name varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL comment '表名',
expression varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL comment '表达式',
create_time datetime null comment '创建时间',
update_time datetime null comment '更新时间'
)
COMMENT '角色数据查询权限' COLLATE = utf8mb4_general_ci;
SET FOREIGN_KEY_CHECKS = 1;
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
-- 0.7.2 2023-2-12
-- ----------------------------
-- ----------------------------
-- Table structure for dlink_role_select_permissions
-- ----------------------------
CREATE TABLE dlink_role_select_permissions
(
id int auto_increment comment 'ID'
primary key,
role_id int not null comment '角色ID',
table_name varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL comment '表名',
expression varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL comment '表达式',
create_time datetime null comment '创建时间',
update_time datetime null comment '更新时间'
)
COMMENT '角色数据查询权限' COLLATE = utf8mb4_general_ci;
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment