写SQL操作HashMap?有应用场景吗

81 阅读1分钟

如题,有需要通过写SQL来操作HashMap的需求吗? 欢迎评论区讨论,如果需求多,可以考虑造个小轮子呢。

类似 Tair 数据库,上层通过写SQL,底层还是k-v存储结构。

不过它是分布式数据库中间件。有时候是不是也有场景,需要操作复杂的内存数据?涉及很多HashMap,如果用SQL语法操作可能会简单很多呢?

下面给出简单的 demo 提供思路。

基于 jsqlparser 组件解析SQL语法树,根据这个语法树来操作HashMap。

依赖

<dependency>  
  <groupId>com.github.jsqlparser</groupId>  
  <artifactId>jsqlparser</artifactId>  
  <version>4.5</version>  
</dependency>

先提前准备两张“表”,其实是两个 HashMap。

// 提前准备两张“表”  
private static Map<String, RowData> table1;  
private static Map<String, RowData> table2;  
  
static {  
    table1 = new HashMap<>();  
    table1.put("key1", new RowData("key1", "value1"));  
    table1.put("key2", new RowData("key2", "value2"));  
    table2 = new HashMap<>();  
}

// 以及一个根据表名取对应的HashMap的方法
private static Map<String, RowData> getTable(String tableName) {  
    if ("table1".equals(tableName)) {  
        return table1;  
    } else {  
        return table2;  
    }  
}

演示1:简单条件查询

"SELECT * FROM table1 WHERE key = 'key1'"

String sql = "SELECT * FROM table1 WHERE key = 'key1'";  
Statement stmt = CCJSqlParserUtil.parse(sql);  
Select selectStatement = (Select) stmt;  
PlainSelect plain = (PlainSelect) selectStatement.getSelectBody();  
FromItem fromItem = plain.getFromItem();  
String tableName = ((Table) fromItem).getName();  
Map<String, RowData> table = getTable(tableName);  
  
Expression where = plain.getWhere();  
EqualsTo where1 = (EqualsTo) where;  
// 拿到 'key1'
String rowKey = where1.getRightExpression().toString().replace("'", "");  
// 相当索引列直接取行数据了
RowData rowData = table.get(rowKey);  
  
System.out.println("=====> " + rowData);

演示2:AND 条件查询

"SELECT * FROM table1 WHERE key = 'key1' AND value = 'value1'"

String sql = "SELECT * FROM table1 WHERE key = 'key1' AND value = 'value1'";  
Statement stmt = CCJSqlParserUtil.parse(sql);  
Select selectStatement = (Select) stmt;  
PlainSelect plain = (PlainSelect) selectStatement.getSelectBody();  
FromItem fromItem = plain.getFromItem();  
String tableName = ((Table) fromItem).getName();  
Map<String, RowData> table = getTable(tableName);  
  
Expression where = plain.getWhere();  
AndExpression and = (AndExpression) where;  
EqualsTo leftExpression = (EqualsTo) and.getLeftExpression();  
EqualsTo rightExpression = (EqualsTo) and.getRightExpression();  
  
String keyCond = leftExpression.getRightExpression().toString().replace("'", "");  
String valueCond = rightExpression.getRightExpression().toString().replace("'", "");  
  
RowData rowData = table.get(keyCond);  
if (rowData!=null) {  
    // 如果匹配到行,则进一步匹配普通字段是否匹配
    if (Objects.equals(rowData.getValue(), valueCond)) {  
        System.out.println("============> " + rowData);  
    }  
}