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

com.jpattern.orm.query.clause.OrmCustomSelect Maven / Gradle / Ivy

There is a newer version: 6.3.0
Show newest version
package com.jpattern.orm.query.clause;

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

import com.jpattern.orm.exception.OrmException;
import com.jpattern.orm.query.NameSolver;
import com.jpattern.orm.query.NameSolverConsumer;
import com.jpattern.orm.query.NullNameSolver;
import com.jpattern.orm.query.SmartRenderableSqlSubElement;
import com.jpattern.orm.query.clause.select.SelectRegexPattern;

/**
 * 
 * @author Francesco Cina
 *
 * 07/lug/2011
 */
public abstract class OrmCustomSelect> extends SmartRenderableSqlSubElement implements Select, NameSolverConsumer {

	//	private static Pattern patternSelectClause = Pattern.compile(ISelectRegexPattern.SQL_SELECT_SPLIT_PATTERN);
	private static Pattern patternProperty = Pattern.compile(SelectRegexPattern.SQL_SELECT_PROPERTY_PATTERN);
	private final String selectClause;
	private NameSolver nameSolver = new NullNameSolver();
	private int versionStatus = 0;
	private boolean distinct = false;

	public OrmCustomSelect(final String selectClause) {
		this.selectClause = selectClause;
	}

	@Override
	public final void doElementRender(final StringBuilder stringBuilder) {
		stringBuilder.append("SELECT ");
		if (this.distinct) {
			stringBuilder.append("DISTINCT ");
		}
		solveProperties( stringBuilder, this.selectClause) ;
		stringBuilder.append(" ");
	}

	@Override
	public final int getElementStatusVersion() {
		return this.versionStatus;
	}

	@Override
	public final void appendElementValues(final List values) {
	}

	@Override
	public void setNameSolver(final NameSolver nameSolver) {
		this.nameSolver = nameSolver;
	}

	private void solveProperties(final StringBuilder stringBuilder, final String token) {
		final Matcher m = patternProperty.matcher(token);
		int beginIndex = 0;

		while (m.find()) {
			stringBuilder.append( token.substring(beginIndex, m.start()) );
			stringBuilder.append( this.nameSolver.solvePropertyName( m.group() , m.group()) );
			beginIndex = m.end();
		}

		stringBuilder.append( token.substring(beginIndex, token.length()) );
	}

	public T setDistinct(final boolean distinct) {
		this.distinct = distinct;
		this.versionStatus++;
		return select();
	}

	public boolean isDistinct() throws OrmException {
		return this.distinct;
	}


	protected abstract T select();

}