DynamicTableNameParser implements ISqlParser { @Override public SqlInfo parser(MetaObject metaObject, String sql) { if (allowProcess(metaObject)) { TableNameParser parser = new TableNameParser(sql); List<TableNameParser.SqlToken> names = new ArrayList<>(); parser.accept(names::add); StringBuilder builder = new StringBuilder(); int last = 0; for (TableNameParser.SqlToken name : names) { int start = name.getStart(); if (start != last) { builder.append(sql, last, start); String value = name.getValue(); ITableNameHandler handler = tableNameHandlerMap.get(value); if (handler != null) { builder.append(handler.dynamicTableName(metaObject, sql, value)); } else { builder.append(value); } } last = name.getEnd(); } if (last != sql.length()) { builder.append(sql.substring(last)); } return SqlInfo.of(builder.toString()); } return null; }  @Override SqlInfo parser(MetaObject metaObject, String sql); boolean allowProcess(MetaObject metaObject);  }
@Test void parser() { DynamicTableNameParser parser = new DynamicTableNameParser(); Map<String, ITableNameHandler> tableNameHandlerMap = new HashMap<>(); tableNameHandlerMap.put("t_user", (metaObject, sql, tableName) -> { if ("t_user".equals(tableName)) { return "t_user_2019"; } return tableName; }); parser.setTableNameHandlerMap(tableNameHandlerMap); String before = "select a.* from t_user a join t_userrole b on b.userid = a.gid"; String after = "select a.* from t_user_2019 a join t_userrole b on b.userid = a.gid"; assertEquals(after, parser.parser(null, before).getSql()); before = "select * from t_user"; after = "select * from t_user_2019"; assertEquals(after, parser.parser(null, before).getSql()); before = "insert into t_user(id,name) values('1','zhangsan')"; after = "insert into t_user_2019(id,name) values('1','zhangsan')"; assertEquals(after, parser.parser(null, before).getSql()); before = "select a.*,\n" + " (select count(1) from t_user) as cnt\n" + " from t_xxx a"; after = "select a.*,\n" + " (select count(1) from t_user_2019) as cnt\n" + " from t_xxx a"; assertEquals(after, parser.parser(null, before).getSql()); }