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

com.jaregu.database.queries.compiling.expr.EvaluationContext Maven / Gradle / Ivy

Go to download

Java based SQL templating project. Store your queries in *.sql files and build queries for execution. Supports simple expressions and conditional clauses and interface proxying for java-sql bridge.

There is a newer version: 1.4.1
Show newest version
package com.jaregu.database.queries.compiling.expr;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;

import com.jaregu.database.queries.building.ParametersResolver;

final class EvaluationContext {

	private static final ThreadLocal CONTEXT = new ThreadLocal<>();

	private ParametersResolver variableResolver;
	private Optional baseExpression;
	private Map outputVariables;

	public static Builder forVariableResolver(ParametersResolver variableResolver) {
		return new Builder(variableResolver);
	}

	private EvaluationContext(ParametersResolver variableResolver) {
		this.variableResolver = variableResolver;
	}

	public ParametersResolver getVariableResolver() {
		return variableResolver;
	}

	public Optional getBaseExpression() {
		return baseExpression;
	}

	public Map getOutputVariables() {
		return outputVariables != null ? Collections.unmodifiableMap(outputVariables) : Collections.emptyMap();
	}

	public void setOutputVariable(String name, Object value) {
		if (outputVariables == null) {
			outputVariables = new LinkedHashMap<>();
		}
		outputVariables.put(name, value);
	}

	public  T withContext(Supplier work) {
		return withContext(this, work);
	}

	public static Optional peekCurrent() {
		return Optional.ofNullable(CONTEXT.get());
	}

	public static EvaluationContext getCurrent() {
		return peekCurrent().orElseThrow(() -> new ExpressionEvalException(
				"Trying to evaluate expression without " + EvaluationContext.class.getSimpleName() + "!"));
	}

	public static  T withContext(EvaluationContext context, Supplier work) {
		EvaluationContext oldContext = CONTEXT.get();
		try {
			CONTEXT.set(context);
			return work.get();
		} finally {
			CONTEXT.set(oldContext);
		}
	}

	public static class Builder {

		private EvaluationContext context;

		private Builder(ParametersResolver variableResolver) {
			context = new EvaluationContext(variableResolver);
		}

		public Builder withBaseExpression(Expression expression) {
			context.baseExpression = Optional.of(expression);
			return this;
		}

		public EvaluationContext build() {
			return context;
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy