All Downloads are FREE. Search and download functionalities are using the official Maven repository.

dk.eobjects.metamodel.dialects.DefaultQueryRewriter Maven / Gradle / Ivy

The newest version!
/**
 *  This file is part of MetaModel.
 *
 *  MetaModel is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  MetaModel is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with MetaModel.  If not, see .
 */
package dk.eobjects.metamodel.dialects;

import java.util.List;

import dk.eobjects.metamodel.JdbcDataContextStrategy;
import dk.eobjects.metamodel.query.FromItem;
import dk.eobjects.metamodel.query.Query;
import dk.eobjects.metamodel.query.SelectItem;

/**
 * Generic query rewriter that adds syntax enhancements that are only possible
 * to resolve just before execution time.
 */
public class DefaultQueryRewriter extends AbstractQueryRewriter {

	private static final String SPECIAL_ALIAS_CHARACTERS = "- ,.|*%()!#¤/\\=?;:~";

	@Override
	protected Query beforeRewrite(JdbcDataContextStrategy strategy, Query query) {
		query = query.clone();

		if (strategy != null) {
			String identifierQuoteString = strategy.getIdentifierQuoteString();
			if (identifierQuoteString != null) {
				List selectItems = query.getSelectClause()
						.getItems();
				for (SelectItem item : selectItems) {
					String alias = item.getAlias();
					if (needsQuoting(alias, identifierQuoteString)) {
						item.setAlias(identifierQuoteString + alias
								+ identifierQuoteString);
					}
				}
				List fromItems = query.getFromClause().getItems();
				for (FromItem item : fromItems) {
					String alias = item.getAlias();
					if (needsQuoting(alias, identifierQuoteString)) {
						item.setAlias(identifierQuoteString + alias
								+ identifierQuoteString);
					}
				}
			}
		}
		return query;
	}

	private boolean needsQuoting(String alias, String identifierQuoteString) {
		boolean result = false;
		if (alias != null && identifierQuoteString != null) {
			if (alias.indexOf(identifierQuoteString) == -1) {
				for (int i = 0; i < SPECIAL_ALIAS_CHARACTERS.length(); i++) {
					char specialCharacter = SPECIAL_ALIAS_CHARACTERS.charAt(i);
					if (alias.indexOf(specialCharacter) != -1) {
						result = true;
						break;
					}
				}
			}
		}
		if (_log.isDebugEnabled()) {
			_log.debug("needsQuoting(" + alias + "," + identifierQuoteString
					+ ") = " + result);
		}
		return result;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy