點選上方“Java技術驛站”,選擇“置頂公眾號”。
有內涵、有價值的文章第一時間送達!
核心原始碼就在sharding-jdbc-core
模組的com.dangdang.ddframe.rdb.sharding.rewrite
目錄下,包含兩個檔案SQLBuilder和SQLRewriteEngine;測試用例入口為SQLRewriteEngineTest,下麵從SQLRewriteEngineTest中debug原始碼分析sharding-jdbc的重寫是如何實現的:
SQLRewriteEngineTest中某個測試用例如下–主要包括都表名,offset,limit(rowCount)的重寫:
@Test
public void assertRewriteForLimit() {
selectStatement.setLimit(new Limit(true));
// offset的值就是limit offset,rowCount中offset的值
selectStatement.getLimit().setOffset(new LimitValue(2, -1));
// rowCount的值就是limit offset,rowCount中rowCount的值
selectStatement.getLimit().setRowCount(new LimitValue(2, -1));
// TableToken的值表示表名table_x在原始SQL陳述句的偏移量是17的位置
selectStatement.getSqlTokens().add(new TableToken(17, "table_x"));
// OffsetToken的值表示offset在原始SQL陳述句的偏移量是33的位置(2就是offset的值)
selectStatement.getSqlTokens().add(new OffsetToken(33, 2));
// RowCountToken的值表示rowCount在原始SQL陳述句的偏移量是36的位置(2就是rowCount的值)
selectStatement.getSqlTokens().add(new RowCountToken(36, 2));
// selectStatement值模擬過程,實際上是SQL解釋過程(SQL解釋會單獨分析)
SQLRewriteEngine rewriteEngine = new SQLRewriteEngine(shardingRule, "SELECT x.id FROM table_x x LIMIT 2, 2", selectStatement);
// 重寫的核心就是這裡了:rewriteEngine.rewrite(true)
assertThat(rewriteEngine.rewrite(true).toSQL(tableTokens), is("SELECT x.id FROM table_1 x LIMIT 0, 4"));
}
重寫方法核心原始碼: 從這段原始碼可知,sql重寫主要包括對錶名,limit offset, rowNum以及order by的重寫(ItemsToken值對select col1, col2 from… 即查詢結果列的重寫–需要由於ordre by或者group by需要增加一些結果列);
public SQLBuilder rewrite(final boolean isRewriteLimit) {
SQLBuilder result = new SQLBuilder();
if (sqlTokens.isEmpty()) {
result.appendLiterals(originalSQL);
return result;
}
int count = 0;
// 根據Token的beginPosition即出現的位置排序
sortByBeginPosition();
for (SQLToken each : sqlTokens) {
if (0 == count) {
// 第一次處理:擷取從原生SQL的開始位置到第一個token起始位置之間的內容,例如"SELECT x.id FROM table_x x LIMIT 2, 2"這條SQL的第一個token是TableToken,即table_x所在位置,所以擷取內容為"SELECT x.id FROM "
result.appendLiterals(originalSQL.substring(0, each.getBeginPosition()));
}
if (each instanceof TableToken) {
// 看後面的"表名重寫分析"
appendTableToken(result, (TableToken) each, count, sqlTokens);
} else if (each instanceof ItemsToken) {
// ItemsToken是指當邏輯SQL有order by,group by這樣的特殊條件時,需要在select的結果列中增加一些結果列,例如執行邏輯SQL:"SELECT o.* FROM t_order o where o.user_id=? order by o.order_id desc limit 2,3",那麼還需要增加結果列o.order_id AS ORDER_BY_DERIVED_0
appendItemsToken(result, (ItemsToken) each, count, sqlTokens);
} else if (each instanceof RowCountToken) {
// 看後面的"rowCount重寫分析"
appendLimitRowCount(result, (RowCountToken) each, count, sqlTokens, isRewriteLimit);
} else if (each instanceof OffsetToken) {
// 看後面的"offset重寫分析"
appendLimitOffsetToken(result, (OffsetToken) each, count, sqlTokens, isRewriteLimit);
} else if (each instanceof OrderByToken) {
appendOrderByToken(result, count, sqlTokens);
}
count++;
}
return result;
}
private void sortByBeginPosition() {
Collections.sort(sqlTokens, new Comparator<SQLToken>() {
// 生序排列
@Override
public int compare(final SQLToken o1, final SQLToken o2) {
return o1.getBeginPosition() - o2.getBeginPosition();
}
});
}
表名重寫分析
private void appendTableToken(final SQLBuilder sqlBuilder, final TableToken tableToken, final int count, final List<SQLToken> sqlTokens) {
String tableName = sqlStatement.getTables().getTableNames().contains(tableToken.getTableName()) ? tableToken.getTableName() : tableToken.getOriginalLiterals();
// append表名特殊處理
sqlBuilder.appendTable(tableName);
int beginPosition = tableToken.getBeginPosition() + tableToken.getOriginalLiterals().length();
appendRest(sqlBuilder, count, sqlTokens, beginPosition);
}
// append表名特殊處理,把TableToken也要新增到SQLBuilder中(List
public void appendTable(final String tableName) {
segments.add(new TableToken(tableName));
currentSegment = new StringBuilder();
segments.add(currentSegment);
}
offset重寫分析
private void appendLimitOffsetToken(final SQLBuilder sqlBuilder, final OffsetToken offsetToken, final int count, final List<SQLToken> sqlTokens, final boolean isRewrite) {
// offset的重寫比較簡單:如果要重寫,則offset置為0,否則保留offset的值;
sqlBuilder.appendLiterals(isRewrite ? "0" : String.valueOf(offsetToken.getOffset()));
int beginPosition = offsetToken.getBeginPosition() + String.valueOf(offsetToken.getOffset()).length();
appendRest(sqlBuilder, count, sqlTokens, beginPosition);
}
rowCount重寫分析
private void appendLimitRowCount(final SQLBuilder sqlBuilder, final RowCountToken rowCountToken, final int count, final List<SQLToken> sqlTokens, final boolean isRewrite) {
SelectStatement selectStatement = (SelectStatement) sqlStatement;
Limit limit = selectStatement.getLimit();
if (!isRewrite) {
// 如果不需要重寫sql中的limit的話(例如select * from t limit 10),那麼,直接append rowCount的值即可;
sqlBuilder.appendLiterals(String.valueOf(rowCountToken.getRowCount()));
} else if ((!selectStatement.getGroupByItems().isEmpty() || !selectStatement.getAggregationSelectItems().isEmpty()) && !selectStatement.isSameGroupByAndOrderByItems()) {
// 如果要重寫sql中的limit的話,且sql中有group by或者有group by & order by,例如""SELECT o.* FROM t_order o where o.user_id=? group by o.order_id order by o.order_id desc limit 2,3"需要",那麼重寫為Integer.MAX_VALUE,原因在下文分析,請點選連線:
sqlBuilder.appendLiterals(String.valueOf(Integer.MAX_VALUE));
} else {
// 否則只需要將limit offset,rowCount重寫為limit 0, offset+rowCount即可;
sqlBuilder.appendLiterals(String.valueOf(limit.isRowCountRewriteFlag() ? rowCountToken.getRowCount() + limit.getOffsetValue() : rowCountToken.getRowCount()));
}
int beginPosition = rowCountToken.getBeginPosition() + String.valueOf(rowCountToken.getRowCount()).length();
appendRest(sqlBuilder, count, sqlTokens, beginPosition);
}
appendRest分析
private void appendRest(final SQLBuilder sqlBuilder, final int count, final List<SQLToken> sqlTokens, final int beginPosition) {
// 如果SQL解析後只有一個token,那麼結束位置(endPosition)就是sql末尾;否則結束位置就是到下一個token的起始位置
int endPosition = sqlTokens.size() - 1 == count ? originalSQL.length() : sqlTokens.get(count + 1).getBeginPosition();
sqlBuilder.appendLiterals(originalSQL.substring(beginPosition, endPosition));
}
所有重寫最後都會呼叫appendRest(),即附加上餘下部分內容,這個餘下部分內容是指從當前處理的token到下一個token之間的內容,例如SQL為
SELECT x.id FROM table_x x LIMIT5,10
,當遍歷到table_x
,即處理完TableToken後,由於下一個token為OffsetToken,即5,所以appendRest就是append這一段內容:" x LIMIT "--從table_x到5之間的內容;
SQLBuilder.toString()分析
重寫完後,呼叫SQLBuilder的toString()方法生成重寫後最終的SQL陳述句;
public String toSQL(final Map<String, String> tableTokens) {
StringBuilder result = new StringBuilder();
for (Object each : segments) {
// 如果是TableToken,並且是分庫分表相關表,那麼append最終的實際表名,例如t_order的實際表名可能是t_order_1
if (each instanceof TableToken && tableTokens.containsKey(((TableToken) each).tableName)) {
result.append(tableTokens.get(((TableToken) each).tableName));
} else {
result.append(each);
}
}
return result.toString();
}
END
【死磕Sharding-jdbc】---EventBus-輕量級行程內事件分發元件