use of com.rebuild.core.service.query.AdvFilterParser in project rebuild by getrebuild.
the class BulkOperator method prepareRecords.
/**
* 获取待操作记录
*
* @return
*/
protected ID[] prepareRecords() {
if (this.records != null) {
return this.records;
}
if (context.getRecords() != null) {
this.records = context.getRecords();
setTotal(this.records.length);
return this.records;
}
JSONObject asFilterExp = (JSONObject) context.getExtraParams().get("customData");
AdvFilterParser filterParser = new AdvFilterParser(asFilterExp);
String sqlWhere = filterParser.toSqlWhere();
// `(1=1)`.length < 10
if (sqlWhere.length() < 10) {
throw new FilterParseException("Must specify items of filter : " + sqlWhere);
}
Entity entity = MetadataHelper.getEntity(asFilterExp.getString("entity"));
String sql = String.format("select %s from %s where (1=1) and %s", entity.getPrimaryField().getName(), entity.getName(), sqlWhere);
// NOTE 注意没有分页
Query query = Application.createQuery(sql, context.getOpUser());
Object[][] array = QueryHelper.readArray(query);
Set<ID> ids = new HashSet<>();
for (Object[] o : array) {
ids.add((ID) o[0]);
}
return ids.toArray(new ID[0]);
}
use of com.rebuild.core.service.query.AdvFilterParser in project rebuild by getrebuild.
the class ProtocolFilterParser method parseVia.
/**
* @param viaId
* @param refField
* @return
*/
public String parseVia(String viaId, String refField) {
final ID anyId = ID.isId(viaId) ? ID.valueOf(viaId) : null;
if (anyId == null)
return null;
JSONObject filterExp = null;
// via Charts
if (anyId.getEntityCode() == EntityHelper.ChartConfig) {
ConfigBean chart = ChartManager.instance.getChart(anyId);
if (chart != null)
filterExp = ((JSONObject) chart.getJSON("config")).getJSONObject("filter");
} else // via AdvFilter
if (anyId.getEntityCode() == EntityHelper.FilterConfig) {
ConfigBean filter = AdvFilterManager.instance.getAdvFilter(anyId);
if (filter != null)
filterExp = (JSONObject) filter.getJSON("filter");
} else // via OTHERS
if (refField != null) {
String[] entityAndField = refField.split("\\.");
Assert.isTrue(entityAndField.length == 2, "Bad `via` filter defined");
JSONObject item = JSONUtils.toJSONObject(new String[] { "field", "op", "value" }, new Object[] { entityAndField[1], ParseHelper.EQ, anyId });
filterExp = JSONUtils.toJSONObject("entity", entityAndField[0]);
filterExp.put("items", Collections.singletonList(item));
}
return filterExp == null ? null : new AdvFilterParser(filterExp).toSqlWhere();
}
use of com.rebuild.core.service.query.AdvFilterParser in project rebuild by getrebuild.
the class QueryParser method doParseIfNeed.
/**
* 解析 SQL
*/
private void doParseIfNeed() {
if (sql != null)
return;
StringBuilder fullSql = new StringBuilder("select ");
JSONArray fieldsNode = queryExpr.getJSONArray("fields");
int fieldIndex = -1;
Set<String> queryJoinFields = new HashSet<>();
for (Object o : fieldsNode) {
// 在 DataListManager 中已验证字段有效,此处不再次验证
String field = o.toString().trim();
fullSql.append(field).append(',');
fieldIndex++;
// 仅支持两级验证
if (field.split("\\.").length > 1) {
queryJoinFields.add(field.split("\\.")[0]);
}
this.queryFields.add(field);
}
// 最后增加一个主键列
String pkName = entity.getPrimaryField().getName();
fullSql.append(pkName);
fieldIndex++;
// 追加关联查询记录 ID 以便验证权限
if (!queryJoinFields.isEmpty()) {
this.queryJoinFields = new HashMap<>();
for (String field : queryJoinFields) {
fullSql.append(',').append(field);
fieldIndex++;
this.queryJoinFields.put(field, fieldIndex);
}
}
fullSql.append(" from ").append(entity.getName());
// 过滤器
List<String> wheres = new ArrayList<>();
// Default
String defaultFilter = dataListBuilder == null ? null : dataListBuilder.getDefaultFilter();
if (StringUtils.isNotBlank(defaultFilter)) {
wheres.add(defaultFilter);
}
// appends ProtocolFilter
String protocolFilter = queryExpr.getString("protocolFilter");
if (StringUtils.isNotBlank(protocolFilter)) {
String where = new ProtocolFilterParser(protocolFilter).toSqlWhere();
if (StringUtils.isNotBlank(where))
wheres.add(where);
}
// appends AdvFilter
String advFilter = queryExpr.getString("advFilter");
if (ID.isId(advFilter)) {
String where = parseAdvFilter(ID.valueOf(advFilter));
if (StringUtils.isNotBlank(where))
wheres.add(where);
}
// appends QuickQuery
JSONObject quickFilter = queryExpr.getJSONObject("filter");
if (quickFilter != null) {
String where = new AdvFilterParser(entity, quickFilter).toSqlWhere();
if (StringUtils.isNotBlank(where))
wheres.add(where);
}
final String sqlWhere = wheres.isEmpty() ? "1=1" : StringUtils.join(wheres.iterator(), " and ");
fullSql.append(" where ").append(sqlWhere);
// 排序
StringBuilder sqlSort = new StringBuilder(" order by ");
String sortNode = queryExpr.getString("sort");
if (StringUtils.isNotBlank(sortNode)) {
sqlSort.append(StringUtils.defaultString(parseSort(sortNode), ""));
} else if (entity.containsField(EntityHelper.ModifiedOn)) {
sqlSort.append(EntityHelper.ModifiedOn + " desc");
} else if (entity.containsField(EntityHelper.CreatedOn)) {
sqlSort.append(EntityHelper.CreatedOn + " desc");
}
if (sqlSort.length() >= 18)
fullSql.append(sqlSort);
this.sql = fullSql.toString();
this.countSql = this.buildCountSql(pkName) + sqlWhere;
int pageNo = NumberUtils.toInt(queryExpr.getString("pageNo"), 1);
int pageSize = NumberUtils.toInt(queryExpr.getString("pageSize"), 20);
this.limit = new int[] { pageSize, pageNo * pageSize - pageSize };
this.reload = limit[1] == 0;
if (!reload) {
reload = BooleanUtils.toBoolean(queryExpr.getString("reload"));
}
}
use of com.rebuild.core.service.query.AdvFilterParser in project rebuild by getrebuild.
the class RoleBaseQueryFilter method buildCustomFilter.
/**
* 自定义权限
*
* @param ep
* @param dtmField
* @return
* @see PrivilegesManager#andPassCustomFilter(ID, ID, Permission, Privileges)
*/
private String buildCustomFilter(Privileges ep, Field dtmField) {
if (user == null || useAction == null || !(ep instanceof CustomEntityPrivileges))
return null;
JSONObject hasFilter = ((CustomEntityPrivileges) ep).getCustomFilter(useAction);
if (hasFilter == null)
return null;
// 兼容转换(明细实体)
if (dtmField != null) {
final JSONArray items = hasFilter.getJSONArray("items");
JSONArray items2 = new JSONArray();
for (Object item : items) {
JSONObject c = (JSONObject) JSONUtils.clone((JSON) item);
c.put("field", String.format("%s.%s", dtmField.getName(), c.getString("field")));
items2.add(c);
}
hasFilter = JSONUtils.toJSONObject(new String[] { "entity", "items" }, new Object[] { dtmField.getOwnEntity().getName(), items2 });
}
AdvFilterParser advFilterParser = new AdvFilterParser(hasFilter);
advFilterParser.setUser(user.getId());
return advFilterParser.toSqlWhere();
}
use of com.rebuild.core.service.query.AdvFilterParser in project rebuild by getrebuild.
the class FeedsListController method fetchFeeds.
@PostMapping("/feeds/feeds-list")
public RespBody fetchFeeds(HttpServletRequest request) {
final ID user = getRequestUser(request);
JSON filterJson = ServletUtils.getRequestJson(request);
final AdvFilterParser parser = new AdvFilterParser((JSONObject) filterJson);
String sqlWhere = parser.toSqlWhere();
if (sqlWhere == null) {
sqlWhere = "(1=1)";
}
int type = getIntParameter(request, "type", 0);
if (type == 1) {
sqlWhere += String.format(" and exists (select feedsId from FeedsMention where ^feedsId = feedsId and user = '%s')", user);
} else if (type == 2) {
sqlWhere += String.format(" and exists (select feedsId from FeedsComment where ^feedsId = feedsId and createdBy = '%s')", user);
} else if (type == 3) {
sqlWhere += String.format(" and exists (select source from FeedsLike where ^feedsId = source and createdBy = '%s')", user);
} else if (type == 10) {
sqlWhere += String.format(" and createdBy ='%s'", user);
}
// 私密的仅显示在私密标签下
if (type == 11) {
sqlWhere += String.format(" and createdBy ='%s' and scope = 'SELF'", user);
} else if (!parser.getIncludeFields().contains("scope")) {
Set<Team> teams = Application.getUserStore().getUser(user).getOwningTeams();
List<String> in = new ArrayList<>();
in.add("scope = 'ALL'");
for (Team t : teams) {
in.add(String.format("scope = '%s'", t.getIdentity()));
}
sqlWhere += " and ( " + StringUtils.join(in, " or ") + " )";
}
int pageNo = getIntParameter(request, "pageNo", 1);
int pageSize = getIntParameter(request, "pageSize", 40);
String sort = getParameter(request, "sort");
long count = -1;
if (pageNo == 1) {
count = (Long) Application.createQueryNoFilter("select count(feedsId) from Feeds where " + sqlWhere).unique()[0];
if (count == 0) {
return RespBody.ok();
}
}
String sql = ITEM_SQL + sqlWhere;
Object[] foucsFeed = null;
List<ID> userTop = null;
List<Object[]> userTopFeeds = null;
if (pageNo == 1) {
// 焦点动态
ID foucs = getIdParameter(request, "foucs");
if (foucs != null) {
foucsFeed = Application.createQueryNoFilter(sql + " and feedsId = ?").setParameter(1, foucs).unique();
}
// 用户置顶动态
userTop = FeedsPostController.getUserTopFeeds(user);
userTopFeeds = new ArrayList<>();
for (ID s : userTop) {
Object[] o = Application.createQueryNoFilter(sql + " and feedsId = ?").setParameter(1, s).unique();
if (o != null)
userTopFeeds.add(o);
}
}
if ("older".equalsIgnoreCase(sort)) {
sql += " order by createdOn asc";
} else if ("modified".equalsIgnoreCase(sort)) {
sql += " order by modifiedOn desc";
} else {
sql += " order by createdOn desc";
}
Object[][] array = Application.createQueryNoFilter(sql).setLimit(pageSize, pageNo * pageSize - pageSize).array();
array = add2Top(foucsFeed, array);
if (userTopFeeds != null) {
// 最多 3
if (userTopFeeds.size() > 2)
array = add2Top(userTopFeeds.get(2), array);
if (userTopFeeds.size() > 1)
array = add2Top(userTopFeeds.get(1), array);
if (userTopFeeds.size() > 0)
array = add2Top(userTopFeeds.get(0), array);
}
Set<ID> set = new HashSet<>();
List<JSON> list = new ArrayList<>();
for (Object[] o : array) {
if (set.contains((ID) o[0]))
continue;
JSONObject feed = buildItem(o, user);
if (userTop != null && userTop.contains((ID) o[0]))
feed.put("usertop", true);
list.add(feed);
set.add((ID) o[0]);
}
return RespBody.ok(JSONUtils.toJSONObject(new String[] { "total", "data" }, new Object[] { count, list }));
}
Aggregations