org.hibernate.param.ParameterSpecification Java Examples

The following examples show how to use org.hibernate.param.ParameterSpecification. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SqlGenerator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void out(AST n) {
	if ( n instanceof Node ) {
		out( ( (Node) n ).getRenderText( sessionFactory ) );
	}
	else {
		super.out( n );
	}

	if ( n instanceof ParameterNode ) {
		collectedParameters.add( ( (ParameterNode) n ).getHqlParameterSpecification() );
	}
	else if ( n instanceof ParameterContainer ) {
		if ( ( (ParameterContainer) n ).hasEmbeddedParameters() ) {
			ParameterSpecification[] specifications = ( (ParameterContainer) n ).getEmbeddedParameters();
			if ( specifications != null ) {
				collectedParameters.addAll( Arrays.asList( specifications ) );
			}
		}
	}
}
 
Example #2
Source File: AbstractTableBasedBulkIdHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Interprets the {@code WHERE} clause from the user-defined update/delete  query
 *
 * @param whereClause The user-defined {@code WHERE} clause
 *
 * @return The bulk-id-ready {@code WHERE} clause representation
 */
@SuppressWarnings("unchecked")
protected ProcessedWhereClause processWhereClause(AST whereClause) {
	if ( whereClause.getNumberOfChildren() != 0 ) {
		// If a where clause was specified in the update/delete query, use it to limit the
		// ids that will be returned and inserted into the id table...
		try {
			SqlGenerator sqlGenerator = new SqlGenerator( sessionFactory );
			sqlGenerator.whereClause( whereClause );
			String userWhereClause = sqlGenerator.getSQL().substring( 7 );  // strip the " where "
			List<ParameterSpecification> idSelectParameterSpecifications = sqlGenerator.getCollectedParameters();

			return new ProcessedWhereClause( userWhereClause, idSelectParameterSpecifications );
		}
		catch ( RecognitionException e ) {
			throw new HibernateException( "Unable to generate id select for DML operation", e );
		}
	}
	else {
		return ProcessedWhereClause.NO_WHERE_CLAUSE;
	}
}
 
Example #3
Source File: QueryParametersAdaptor.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static Object[] toParameterArray(
		QueryParameters queryParameters,
		List<ParameterSpecification> parameterSpecifications,
		SharedSessionContractImplementor session) {
	return PreparedStatementAdaptor.bind( adaptor -> {
		int pos = 1;
		for (ParameterSpecification parameterSpecification: parameterSpecifications) {
			pos += parameterSpecification.bind(adaptor, queryParameters, session, pos);
		}
	} );
}
 
Example #4
Source File: BasicExecutor.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public int execute(QueryParameters parameters, SessionImplementor session) throws HibernateException {

		coordinateSharedCacheCleanup( session );

		PreparedStatement st = null;
		RowSelection selection = parameters.getRowSelection();

		try {
			try {
				st = session.getBatcher().prepareStatement( sql );
				Iterator paramSpecifications = getWalker().getParameters().iterator();
				int pos = 1;
				while ( paramSpecifications.hasNext() ) {
					final ParameterSpecification paramSpec = ( ParameterSpecification ) paramSpecifications.next();
					pos += paramSpec.bind( st, parameters, session, pos );
				}
				if ( selection != null ) {
					if ( selection.getTimeout() != null ) {
						st.setQueryTimeout( selection.getTimeout().intValue() );
					}
				}

				return st.executeUpdate();
			}
			finally {
				if ( st != null ) {
					session.getBatcher().closeStatement( st );
				}
			}
		}
		catch( SQLException sqle ) {
			throw JDBCExceptionHelper.convert(
					getFactory().getSQLExceptionConverter(),
			        sqle,
			        "could not execute update query",
			        sql
				);
		}
	}
 
Example #5
Source File: QueryLoader.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * We specifically override this method here, because in general we know much more
 * about the parameters and their appropriate bind positions here then we do in
 * our super because we track them explciitly here through the ParameterSpecification
 * interface.
 *
 * @param queryParameters The encapsulation of the parameter values to be bound.
 * @param startIndex The position from which to start binding parameter values.
 * @param session The originating session.
 * @return The number of JDBC bind positions actually bound during this method execution.
 * @throws SQLException Indicates problems performing the binding.
 */
protected int bindParameterValues(
		final PreparedStatement statement,
		final QueryParameters queryParameters,
		final int startIndex,
		final SessionImplementor session) throws SQLException {
	int position = bindFilterParameterValues( statement, queryParameters, startIndex, session );
	List parameterSpecs = queryTranslator.getSqlAST().getWalker().getParameters();
	Iterator itr = parameterSpecs.iterator();
	while ( itr.hasNext() ) {
		ParameterSpecification spec = ( ParameterSpecification ) itr.next();
		position += spec.bind( statement, queryParameters, session, position );
	}
	return position - startIndex;
}
 
Example #6
Source File: HqlSqlWalker.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void applyParameterSpecifications(ParameterContainer parameterContainer) {
	if ( parameterContainer.hasEmbeddedParameters() ) {
		ParameterSpecification[] specs = parameterContainer.getEmbeddedParameters();
		for ( ParameterSpecification spec : specs ) {
			applyParameterSpecification( spec );
		}
	}
}
 
Example #7
Source File: FromElement.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public void setIndexCollectionSelectorParamSpec(ParameterSpecification indexCollectionSelectorParamSpec) {
	if ( indexCollectionSelectorParamSpec == null ) {
		if ( elementType.getIndexCollectionSelectorParamSpec() != null ) {
			embeddedParameters.remove( elementType.getIndexCollectionSelectorParamSpec() );
			elementType.setIndexCollectionSelectorParamSpec( null );
		}
	}
	else {
		elementType.setIndexCollectionSelectorParamSpec( indexCollectionSelectorParamSpec );
		addEmbeddedParameter( indexCollectionSelectorParamSpec );
	}
}
 
Example #8
Source File: FromElement.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private List<ParameterSpecification> getParameterSpecification() {
	List<ParameterSpecification> parameterSpecifications =
		embeddedParameters.stream()
				.filter( o -> o instanceof  DynamicFilterParameterSpecification )
				.collect( Collectors.toList() );

	parameterSpecifications.addAll(
		embeddedParameters.stream()
				.filter( o -> ! (o instanceof  DynamicFilterParameterSpecification ) )
				.collect( Collectors.toList() ) );
	return parameterSpecifications;
}
 
Example #9
Source File: IndexNode.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private String collectDisplayInfo() {
	StringBuilder buffer = new StringBuilder();
	for ( ParameterSpecification paramSpec : paramSpecs ) {
		buffer.append( ( paramSpec ).renderDisplayInfo() );
	}
	return buffer.toString();
}
 
Example #10
Source File: IndexNode.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public int bind(PreparedStatement statement, QueryParameters qp, SharedSessionContractImplementor session, int position)
		throws SQLException {
	int bindCount = 0;
	for ( ParameterSpecification paramSpec : paramSpecs ) {
		bindCount += paramSpec.bind( statement, qp, session, position + bindCount );
	}
	return bindCount;
}
 
Example #11
Source File: ReactiveQueryTranslatorImpl.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
private List<ParameterSpecification> getCollectedParameterSpecifications(ReactiveSession session) {
	// Currently, ORM returns null for getCollectedParameterSpecifications() a StatementExecute
	List<ParameterSpecification> parameterSpecifications = getCollectedParameterSpecifications();
	if ( parameterSpecifications == null ) {
		final SqlGenerator gen = new SqlGenerator( session.getFactory() );
		try {
			gen.statement( (AST) getSqlAST() );
			parameterSpecifications = gen.getCollectedParameters();
		} catch (RecognitionException e) {
			throw QuerySyntaxException.convert(e);
		}
	}
	return parameterSpecifications;
}
 
Example #12
Source File: AbstractIdsBulkIdHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected List<Object[]> selectIds(
		SharedSessionContractImplementor session,
		QueryParameters queryParameters) {
	List<Object[]> ids = new ArrayList<>();
	try {
		try (PreparedStatement ps = session.getJdbcCoordinator()
				.getStatementPreparer()
				.prepareStatement( idSelect, false )) {
			int position = 1;
			for ( ParameterSpecification parameterSpecification : idSelectParameterSpecifications ) {
				position += parameterSpecification.bind( ps, queryParameters, session, position );
			}

			Dialect dialect = session.getFactory().getServiceRegistry().getService( JdbcServices.class ).getDialect();

			ResultSet rs = session
					.getJdbcCoordinator()
					.getResultSetReturn()
					.extract( ps );
			while ( rs.next() ) {
				Object[] result = new Object[targetedPersister.getIdentifierColumnNames().length];
				for ( String columnName : targetedPersister.getIdentifierColumnNames() ) {
					int columnIndex = rs.findColumn( StringHelper.unquote( columnName, dialect ) );
					Object column = rs.getObject(columnIndex);
					result[columnIndex - 1] = column;
				}
				ids.add( result );
			}
		}
	}
	catch ( SQLException e ) {
		throw convert( e, "could not select ids for bulk operation", idSelect );
	}

	return ids;
}
 
Example #13
Source File: CteValuesListUpdateHandlerImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public CteValuesListUpdateHandlerImpl(
		SessionFactoryImplementor factory,
		HqlSqlWalker walker,
		String catalog,
		String schema) {
	super( factory, walker, catalog, schema );

	String[] tableNames = getTargetedQueryable().getConstraintOrderedTableNameClosure();
	String[][] columnNames = getTargetedQueryable().getContraintOrderedTableKeyColumnClosure();
	String idSubselect = generateIdSubselect( getTargetedQueryable() );

	updates = new String[tableNames.length];
	assignmentParameterSpecifications = new ParameterSpecification[tableNames.length][];
	for ( int tableIndex = 0; tableIndex < tableNames.length; tableIndex++ ) {
		boolean affected = false;
		final List<ParameterSpecification> parameterList = new ArrayList<>();
		final Update update = new Update( factory.getServiceRegistry().getService( JdbcServices.class ).getDialect() )
				.setTableName( tableNames[tableIndex] )
				.setWhere( "(" + String.join( ", ", (CharSequence[]) columnNames[tableIndex] ) + ") in (" + idSubselect + ")" );
		if ( factory().getSessionFactoryOptions().isCommentsEnabled() ) {
			update.setComment( "bulk update" );
		}
		final List<AssignmentSpecification> assignmentSpecifications = walker.getAssignmentSpecifications();
		for ( AssignmentSpecification assignmentSpecification : assignmentSpecifications ) {
			if ( assignmentSpecification.affectsTable( tableNames[tableIndex] ) ) {
				affected = true;
				update.appendAssignmentFragment( assignmentSpecification.getSqlAssignmentFragment() );
				if ( assignmentSpecification.getParameters() != null ) {
					Collections.addAll( parameterList, assignmentSpecification.getParameters() );
				}
			}
		}
		if ( affected ) {
			updates[tableIndex] = update.toStatementString();
			assignmentParameterSpecifications[tableIndex] = parameterList.toArray( new ParameterSpecification[parameterList.size()] );
		}
	}
}
 
Example #14
Source File: HqlSqlWalker.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected void prepareVersioned(AST updateNode, AST versioned) throws SemanticException {
	UpdateStatement updateStatement = (UpdateStatement) updateNode;
	FromClause fromClause = updateStatement.getFromClause();
	if ( versioned != null ) {
		// Make sure that the persister is versioned
		Queryable persister = fromClause.getFromElement().getQueryable();
		if ( !persister.isVersioned() ) {
			throw new SemanticException( "increment option specified for update of non-versioned entity" );
		}

		VersionType versionType = persister.getVersionType();
		if ( versionType instanceof UserVersionType ) {
			throw new SemanticException( "user-defined version types not supported for increment option" );
		}

		AST eq = getASTFactory().create( HqlSqlTokenTypes.EQ, "=" );
		AST versionPropertyNode = generateVersionPropertyNode( persister );

		eq.setFirstChild( versionPropertyNode );

		AST versionIncrementNode = null;
		if ( isTimestampBasedVersion( versionType ) ) {
			versionIncrementNode = getASTFactory().create( HqlSqlTokenTypes.PARAM, "?" );
			ParameterSpecification paramSpec = new VersionTypeSeedParameterSpecification( versionType );
			( (ParameterNode) versionIncrementNode ).setHqlParameterSpecification( paramSpec );
			parameterSpecs.add( 0, paramSpec );
		}
		else {
			// Not possible to simply re-use the versionPropertyNode here as it causes
			// OOM errors due to circularity :(
			versionIncrementNode = getASTFactory().create( HqlSqlTokenTypes.PLUS, "+" );
			versionIncrementNode.setFirstChild( generateVersionPropertyNode( persister ) );
			versionIncrementNode.addChild( getASTFactory().create( HqlSqlTokenTypes.IDENT, "1" ) );
		}

		eq.addChild( versionIncrementNode );

		evaluateAssignment( eq, persister, 0 );

		AST setClause = updateStatement.getSetClause();
		AST currentFirstSetElement = setClause.getFirstChild();
		setClause.setFirstChild( eq );
		eq.setNextSibling( currentFirstSetElement );
	}
}
 
Example #15
Source File: AssignmentSpecification.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public ParameterSpecification[] getParameters() {
	return hqlParameters;
}
 
Example #16
Source File: BasicExecutor.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
protected int doExecute(QueryParameters parameters, SharedSessionContractImplementor session, String sql,
		List parameterSpecifications) throws HibernateException {
	BulkOperationCleanupAction action = new BulkOperationCleanupAction( session, persister );
	if ( session.isEventSource() ) {
		( (EventSource) session ).getActionQueue().addAction( action );
	}
	else {
		action.getAfterTransactionCompletionProcess().doAfterTransactionCompletion( true, session );
	}

	PreparedStatement st = null;
	RowSelection selection = parameters.getRowSelection();

	try {
		try {
			st = session.getJdbcCoordinator().getStatementPreparer().prepareStatement( sql, false );
			Iterator paramSpecItr = parameterSpecifications.iterator();
			int pos = 1;
			while ( paramSpecItr.hasNext() ) {
				final ParameterSpecification paramSpec = (ParameterSpecification) paramSpecItr.next();
				pos += paramSpec.bind( st, parameters, session, pos );
			}
			if ( selection != null ) {
				if ( selection.getTimeout() != null ) {
					st.setQueryTimeout( selection.getTimeout() );
				}
			}

			return session.getJdbcCoordinator().getResultSetReturn().executeUpdate( st );
		}
		finally {
			if ( st != null ) {
				session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( st );
				session.getJdbcCoordinator().afterStatementExecution();
			}
		}
	}
	catch( SQLException sqle ) {
		throw session.getJdbcServices().getSqlExceptionHelper().convert( sqle, "could not execute update query", sql );
	}
}
 
Example #17
Source File: QueryTranslatorImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public List<ParameterSpecification> getCollectedParameterSpecifications() {
	return collectedParameterSpecifications;
}
 
Example #18
Source File: SqlGenerator.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public List<ParameterSpecification> getCollectedParameters() {
	return collectedParameters;
}
 
Example #19
Source File: TableBasedUpdateHandlerImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public TableBasedUpdateHandlerImpl(
		SessionFactoryImplementor factory,
		HqlSqlWalker walker,
		IdTableInfo idTableInfo) {
	super( factory, walker );

	final Dialect dialect = factory.getJdbcServices().getJdbcEnvironment().getDialect();
	final UpdateStatement updateStatement = (UpdateStatement) walker.getAST();
	final FromElement fromElement = updateStatement.getFromClause().getFromElement();

	this.targetedPersister = fromElement.getQueryable();

	final String bulkTargetAlias = fromElement.getTableAlias();

	final ProcessedWhereClause processedWhereClause = processWhereClause( updateStatement.getWhereClause() );
	this.idSelectParameterSpecifications = processedWhereClause.getIdSelectParameterSpecifications();
	this.idInsertSelect = generateIdInsertSelect( bulkTargetAlias, idTableInfo, processedWhereClause );
	log.tracev( "Generated ID-INSERT-SELECT SQL (multi-table update) : {0}", idInsertSelect );

	String[] tableNames = targetedPersister.getConstraintOrderedTableNameClosure();
	String[][] columnNames = targetedPersister.getContraintOrderedTableKeyColumnClosure();
	String idSubselect = generateIdSubselect( targetedPersister, idTableInfo );

	updates = new String[tableNames.length];
	assignmentParameterSpecifications = new ParameterSpecification[tableNames.length][];
	for ( int tableIndex = 0; tableIndex < tableNames.length; tableIndex++ ) {
		boolean affected = false;
		final List<ParameterSpecification> parameterList = new ArrayList<>();
		final Update update = new Update( dialect )
				.setTableName( tableNames[tableIndex] )
				.setWhere( "(" + String.join( ", ", columnNames[tableIndex] ) + ") IN (" + idSubselect + ")" );
		if ( factory().getSessionFactoryOptions().isCommentsEnabled() ) {
			update.setComment( "bulk update" );
		}
		final List<AssignmentSpecification> assignmentSpecifications = walker.getAssignmentSpecifications();
		for ( AssignmentSpecification assignmentSpecification : assignmentSpecifications ) {
			if ( assignmentSpecification.affectsTable( tableNames[tableIndex] ) ) {
				affected = true;
				update.appendAssignmentFragment( assignmentSpecification.getSqlAssignmentFragment() );
				if ( assignmentSpecification.getParameters() != null ) {
					Collections.addAll( parameterList, assignmentSpecification.getParameters() );
				}
			}
		}
		if ( affected ) {
			updates[tableIndex] = update.toStatementString();
			assignmentParameterSpecifications[tableIndex] = parameterList.toArray( new ParameterSpecification[parameterList.size()] );
		}
	}
}
 
Example #20
Source File: HqlSqlWalker.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private void applyParameterSpecification(ParameterSpecification paramSpec) {
	joinFragment.addEmbeddedParameter( paramSpec );
}
 
Example #21
Source File: HqlSqlWalker.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public ArrayList<ParameterSpecification> getParameterSpecs() {
	return parameterSpecs;
}
 
Example #22
Source File: AssignmentSpecification.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public AssignmentSpecification(AST eq, Queryable persister) {
	if ( eq.getType() != HqlSqlTokenTypes.EQ ) {
		throw new QueryException( "assignment in set-clause not associated with equals" );
	}

	this.eq = eq;
	this.factory = persister.getFactory();

	// Needed to bump this up to DotNode, because that is the only thing which currently
	// knows about the property-ref path in the correct format; it is either this, or
	// recurse over the DotNodes constructing the property path just like DotNode does
	// internally
	final DotNode lhs = (DotNode) eq.getFirstChild();
	final SqlNode rhs = (SqlNode) lhs.getNextSibling();

	validateLhs( lhs );

	final String propertyPath = lhs.getPropertyPath();
	Set<String> temp = new HashSet<String>();
	// yuck!
	if ( persister instanceof UnionSubclassEntityPersister ) {
		final String[] tables = persister.getConstraintOrderedTableNameClosure();
		Collections.addAll( temp, tables );
	}
	else {
		temp.add(
				persister.getSubclassTableName( persister.getSubclassPropertyTableNumber( propertyPath ) )
		);
	}
	this.tableNames = Collections.unmodifiableSet( temp );

	if ( rhs == null ) {
		hqlParameters = new ParameterSpecification[0];
	}
	else if ( isParam( rhs ) ) {
		hqlParameters = new ParameterSpecification[] {( (ParameterNode) rhs ).getHqlParameterSpecification()};
	}
	else {
		List parameterList = ASTUtil.collectChildren(
				rhs,
				new ASTUtil.IncludePredicate() {
					public boolean include(AST node) {
						return isParam( node );
					}
				}
		);
		hqlParameters = new ParameterSpecification[parameterList.size()];
		Iterator itr = parameterList.iterator();
		int i = 0;
		while ( itr.hasNext() ) {
			hqlParameters[i++] = ( (ParameterNode) itr.next() ).getHqlParameterSpecification();
		}
	}
}
 
Example #23
Source File: ParameterNode.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public ParameterSpecification getHqlParameterSpecification() {
	return parameterSpecification;
}
 
Example #24
Source File: ParameterNode.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void setHqlParameterSpecification(ParameterSpecification parameterSpecification) {
	this.parameterSpecification = parameterSpecification;
}
 
Example #25
Source File: AssignmentSpecification.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public ParameterSpecification[] getParameters() {
	return hqlParameters;
}
 
Example #26
Source File: MultiTableUpdateExecutor.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public MultiTableUpdateExecutor(HqlSqlWalker walker) {
	super( walker, log );

	if ( !walker.getSessionFactoryHelper().getFactory().getDialect().supportsTemporaryTables() ) {
		throw new HibernateException( "cannot perform multi-table updates using dialect not supporting temp tables" );
	}

	UpdateStatement updateStatement = ( UpdateStatement ) walker.getAST();
	FromElement fromElement = updateStatement.getFromClause().getFromElement();
	String bulkTargetAlias = fromElement.getTableAlias();
	this.persister = fromElement.getQueryable();

	this.idInsertSelect = generateIdInsertSelect( persister, bulkTargetAlias, updateStatement.getWhereClause() );
	log.trace( "Generated ID-INSERT-SELECT SQL (multi-table update) : " +  idInsertSelect );

	String[] tableNames = persister.getConstraintOrderedTableNameClosure();
	String[][] columnNames = persister.getContraintOrderedTableKeyColumnClosure();

	String idSubselect = generateIdSubselect( persister );
	List assignmentSpecifications = walker.getAssignmentSpecifications();

	updates = new String[tableNames.length];
	hqlParameters = new ParameterSpecification[tableNames.length][];
	for ( int tableIndex = 0; tableIndex < tableNames.length; tableIndex++ ) {
		boolean affected = false;
		List parameterList = new ArrayList();
		Update update = new Update( getFactory().getDialect() )
				.setTableName( tableNames[tableIndex] )
				.setWhere( "(" + StringHelper.join( ", ", columnNames[tableIndex] ) + ") IN (" + idSubselect + ")" );
		if ( getFactory().getSettings().isCommentsEnabled() ) {
			update.setComment( "bulk update" );
		}
		final Iterator itr = assignmentSpecifications.iterator();
		while ( itr.hasNext() ) {
			final AssignmentSpecification specification = ( AssignmentSpecification ) itr.next();
			if ( specification.affectsTable( tableNames[tableIndex] ) ) {
				affected = true;
				update.appendAssignmentFragment( specification.getSqlAssignmentFragment() );
				if ( specification.getParameters() != null ) {
					for ( int paramIndex = 0; paramIndex < specification.getParameters().length; paramIndex++ ) {
						parameterList.add( specification.getParameters()[paramIndex] );
					}
				}
			}
		}
		if ( affected ) {
			updates[tableIndex] = update.toStatementString();
			hqlParameters[tableIndex] = ( ParameterSpecification[] ) parameterList.toArray( new ParameterSpecification[0] );
		}
	}
}
 
Example #27
Source File: ParameterTranslationsImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Constructs a parameter metadata object given a list of parameter
 * specifications.
 * </p>
 * Note: the order in the incoming list denotes the parameter's
 * psudeo-position within the resulting sql statement.
 *
 * @param parameterSpecifications
 */
public ParameterTranslationsImpl(List parameterSpecifications) {

	class NamedParamTempHolder {
		String name;
		Type type;
		List positions = new ArrayList();
	}

	int size = parameterSpecifications.size();
	List ordinalParameterList = new ArrayList();
	Map namedParameterMap = new HashMap();
	for ( int i = 0; i < size; i++ ) {
		final ParameterSpecification spec = ( ParameterSpecification ) parameterSpecifications.get( i );
		if ( PositionalParameterSpecification.class.isAssignableFrom( spec.getClass() ) ) {
			PositionalParameterSpecification ordinalSpec = ( PositionalParameterSpecification ) spec;
			ordinalParameterList.add( new ParameterInfo( i, ordinalSpec.getExpectedType() ) );
		}
		else if ( NamedParameterSpecification.class.isAssignableFrom( spec.getClass() ) ) {
			NamedParameterSpecification namedSpec = ( NamedParameterSpecification ) spec;
			NamedParamTempHolder paramHolder = ( NamedParamTempHolder ) namedParameterMap.get( namedSpec.getName() );
			if ( paramHolder == null ) {
				paramHolder = new NamedParamTempHolder();
				paramHolder.name = namedSpec.getName();
				paramHolder.type = namedSpec.getExpectedType();
				namedParameterMap.put( namedSpec.getName(), paramHolder );
			}
			paramHolder.positions.add( new Integer( i ) );
		}
		else {
			// don't care about other param types here, just those explicitly user-defined...
		}
	}

	ordinalParameters = ( ParameterInfo[] ) ordinalParameterList.toArray( new ParameterInfo[ordinalParameterList.size()] );

	if ( namedParameterMap.isEmpty() ) {
		namedParameters = java.util.Collections.EMPTY_MAP;
	}
	else {
		Map namedParametersBacking = new HashMap( namedParameterMap.size() );
		Iterator itr = namedParameterMap.values().iterator();
		while( itr.hasNext() ) {
			final NamedParamTempHolder holder = ( NamedParamTempHolder ) itr.next();
			namedParametersBacking.put(
					holder.name,
			        new ParameterInfo( ArrayHelper.toIntArray( holder.positions ), holder.type )
			);
		}
		namedParameters = java.util.Collections.unmodifiableMap( namedParametersBacking );
	}
}
 
Example #28
Source File: HqlSqlWalker.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
protected void prepareVersioned(AST updateNode, AST versioned) throws SemanticException {
	UpdateStatement updateStatement = ( UpdateStatement ) updateNode;
	FromClause fromClause = updateStatement.getFromClause();
	if ( versioned != null ) {
		// Make sure that the persister is versioned
		Queryable persister = fromClause.getFromElement().getQueryable();
		if ( !persister.isVersioned() ) {
			throw new SemanticException( "increment option specified for update of non-versioned entity" );
		}

		VersionType versionType = persister.getVersionType();
		if ( versionType instanceof UserVersionType ) {
			throw new SemanticException( "user-defined version types not supported for increment option" );
		}

		AST eq = getASTFactory().create( HqlSqlTokenTypes.EQ, "=" );
		AST versionPropertyNode = generateVersionPropertyNode( persister );

		eq.setFirstChild( versionPropertyNode );

		AST versionIncrementNode = null;
		if ( Date.class.isAssignableFrom( versionType.getReturnedClass() ) ) {
			versionIncrementNode = getASTFactory().create( HqlSqlTokenTypes.PARAM, "?" );
			ParameterSpecification paramSpec = new VersionTypeSeedParameterSpecification( versionType );
			( ( ParameterNode ) versionIncrementNode ).setHqlParameterSpecification( paramSpec );
			parameters.add( 0, paramSpec );
		}
		else {
			// Not possible to simply re-use the versionPropertyNode here as it causes
			// OOM errors due to circularity :(
			versionIncrementNode = getASTFactory().create( HqlSqlTokenTypes.PLUS, "+" );
			versionIncrementNode.setFirstChild( generateVersionPropertyNode( persister ) );
			versionIncrementNode.addChild( getASTFactory().create( HqlSqlTokenTypes.IDENT, "1" ) );
		}

		eq.addChild( versionIncrementNode );

		evaluateAssignment( eq, persister, 0 );

		AST setClause = updateStatement.getSetClause();
		AST currentFirstSetElement = setClause.getFirstChild();
		setClause.setFirstChild( eq );
		eq.setNextSibling( currentFirstSetElement );
	}
}
 
Example #29
Source File: BinaryLogicOperatorNode.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Mutate the subtree relating to a row-value-constructor to instead use
 * a series of ANDed predicates.  This allows multi-column type comparisons
 * and explicit row-value-constructor syntax even on databases which do
 * not support row-value-constructor.
 * <p/>
 * For example, here we'd mutate "... where (col1, col2) = ('val1', 'val2) ..." to
 * "... where col1 = 'val1' and col2 = 'val2' ..."
 *
 * @param valueElements The number of elements in the row value constructor list.
 */
private void mutateRowValueConstructorSyntax(int valueElements) {
	// mutation depends on the types of nodes involved...
	int comparisonType = getType();
	String comparisonText = getText();

	switch ( comparisonType ) {
		case HqlSqlTokenTypes.EQ:
			setType( HqlSqlTokenTypes.AND );
			setText( "AND" );
			break;

		case HqlSqlTokenTypes.NE:
			setType( HqlSqlTokenTypes.OR );
			setText( "OR" );
			break;

		default:
			throw new QuerySyntaxException( comparisonText + " operator not supported on composite types." );
	}

	String[] lhsElementTexts = extractMutationTexts( getLeftHandOperand(), valueElements );
	String[] rhsElementTexts = extractMutationTexts( getRightHandOperand(), valueElements );

	ParameterSpecification lhsEmbeddedCompositeParameterSpecification =
			getLeftHandOperand() == null || ( !ParameterNode.class.isInstance( getLeftHandOperand() ) )
					? null
					: ( (ParameterNode) getLeftHandOperand() ).getHqlParameterSpecification();

	ParameterSpecification rhsEmbeddedCompositeParameterSpecification =
			getRightHandOperand() == null || ( !ParameterNode.class.isInstance( getRightHandOperand() ) )
					? null
					: ( (ParameterNode) getRightHandOperand() ).getHqlParameterSpecification();

	translate(
			valueElements,
			comparisonType,
			comparisonText,
			lhsElementTexts,
			rhsElementTexts,
			lhsEmbeddedCompositeParameterSpecification,
			rhsEmbeddedCompositeParameterSpecification,
			this
	);
}
 
Example #30
Source File: ParameterNode.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public ParameterSpecification getHqlParameterSpecification() {
	return parameterSpecification;
}