package io.mycat.server.interceptor.impl;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.mycat.server.interceptor.SQLInterceptor;

public class DefaultSqlInterceptor implements SQLInterceptor {
	private static final Pattern p = Pattern.compile("\\'", Pattern.LITERAL);

	private static final String TARGET_STRING = "''";

	private static final char ESCAPE_CHAR = '\\';

	private static final int TARGET_STRING_LENGTH = 2;

	/**
	 * mysql driver对'转义与\',解析前改为foundationdb parser支持的'' add by sky
	 * 
	 * @param stmt
	 * @return
	 */
	public static String processEscape(String sql) {
		int firstIndex = -1;
		if ((sql == null) || ((firstIndex = sql.indexOf(ESCAPE_CHAR)) == -1)) {
			return sql;
		} else {
			int lastIndex = sql.lastIndexOf(ESCAPE_CHAR, sql.length() - 2);// 不用考虑结尾字符为转义符
			Matcher matcher = p.matcher(sql.substring(firstIndex, lastIndex
					+ TARGET_STRING_LENGTH));
			String replacedStr = (lastIndex == firstIndex) ? matcher
					.replaceFirst(TARGET_STRING) : matcher
					.replaceAll(TARGET_STRING);
			StringBuilder sb = new StringBuilder(sql);
			sb.replace(firstIndex, lastIndex + TARGET_STRING_LENGTH,
					replacedStr);
			return sb.toString();
		}
	}

	/**
	 * escape mysql escape letter sql type ServerParse.UPDATE,ServerParse.INSERT
	 * etc
	 */
	@Override
	public String interceptSQL(String sql, int sqlType) {
		return processEscape(sql);
	}

}

@@ -548,16 +548,142 @@
 @return%0A
+%09 * @note: %E8%AF%A5%E5%87%BD%E6%95%B0%E4%BC%9A%E5%AF%BC%E8%87%B4%E6%97%A0%E6%B3%95%E6%AD%A3%E7%A1%AE%E7%9A%84%E6%8F%92%E5%85%A5 %5C %E5%AD%97%E7%AC%A6%E7%9A%84%E9%97%AE%E9%A2%98%EF%BC%9A%0A%09 * update travelrecord set name='test%5C%5C' where id=1;%0A%09 * %E6%8F%92%E5%85%A5%E7%9A%84name%E7%9A%84%E5%80%BC%E4%BC%9A%E5%8F%98%E6%88%90%EF%BC%9Atest' %E8%80%8C%E4%B8%8D%E6%98%AF%E6%88%91%E4%BB%AC%E6%9C%9F%E6%9C%9B%E7%9A%84 test%5C%0A
 %09 */%0A%09pu
@@ -1489,24 +1489,25 @@
 Type) %7B%0A
-%09%09return
+//%09%09sql =
  process
@@ -1519,14 +1519,28 @@
 e(sql);%0A
+%09%09return sql;%0A
 %09%7D%0A%0A%7D%0A

fix DefaultSqlInterceptor中为了支持foundationdb parser而进行的字符转换，导致无法插入 \ 字符的问题。