package jp.sourceforge.shovel.dao.impl;

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

import org.seasar.dao.impl.DaoMetaDataImpl;
import org.seasar.dao.impl.SelectDynamicCommand;
import org.seasar.extension.jdbc.ResultSetHandler;

public class DaoMetaDataWrapperImpl extends DaoMetaDataImpl {
    private static final Pattern startWithMySQLUnionPattern = Pattern.compile(
            "^\\s*\\(\\s*SELECT\\s+[\\w\\W]+(?=\\)\\s*UNION(\\s+ALL)?\\s*\\()", Pattern.CASE_INSENSITIVE);
    
    protected static boolean startsWithMySQLUnion(String query) {
        if (query != null) {
            Matcher m = startWithMySQLUnionPattern.matcher(query);
            if (m.lookingAt()) {
                return true;
            }
        }
        return false;
    }
    
    @Override
    protected SelectDynamicCommand createSelectDynamicCommand(
            ResultSetHandler resultSetHandler, String query) {
        SelectDynamicCommand cmd;
        if (startsWithMySQLUnion(query)) {
            cmd = createSelectDynamicCommand(resultSetHandler);
            StringBuilder builder = new StringBuilder(query);
            cmd.setSql(builder.toString());
        } else {
            cmd = super.createSelectDynamicCommand(resultSetHandler, query);
        }
        return cmd;
    }
}
