
package org.eclipse.birt.tests.data.engine.acceptance;

import java.util.HashMap;

import org.eclipse.birt.data.engine.api.IBaseExpression;
import org.eclipse.birt.data.engine.api.IPreparedQuery;
import org.eclipse.birt.data.engine.api.IQueryResults;
import org.eclipse.birt.data.engine.api.IResultIterator;
import org.eclipse.birt.data.engine.api.querydefn.FilterDefinition;
import org.eclipse.birt.data.engine.api.querydefn.GroupDefinition;
import org.eclipse.birt.data.engine.api.querydefn.OdaDataSetDesign;
import org.eclipse.birt.data.engine.api.querydefn.QueryDefinition;
import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression;
import org.eclipse.birt.data.engine.api.querydefn.SortDefinition;

import testutil.APITestCase;
import testutil.ConfigText;

public class testPassThruContext extends APITestCase
{

	/*
	 * @see org.eclipse.birt.data.engine.api.APITestCase#getDataSourceInfo()
	 */
	protected DataSourceInfo getDataSourceInfo( )
	{
		return new DataSourceInfo( ConfigText
				.getString( "Api.TestData.TableName" ), ConfigText
				.getString( "Api.TestData.TableSQL" ), ConfigText
				.getString( "Api.TestData.TestDataFileName" ) );
	}

	public void test( ) throws Exception
	{
		String testSQL = "select COUNTRY, CITY from " + getTestTableName( );
		( (OdaDataSetDesign) this.dataSet ).setQueryText( testSQL );

		IBaseExpression[] expressions = new IBaseExpression[]{
				new ScriptExpression( "row.COUNTRY", 0 ),
				new ScriptExpression( "row.CITY", 0 )};

		QueryDefinition queryDefn = createQueryDefn( expressions, null, null,
				null );

		// pass in an application context to the underlying ODA driver;
		// limited testing here to make sure normal processing succeeds
		HashMap appContext = new HashMap( );
		appContext.put( dataSet.getDataSourceName( ), testSQL );
		IPreparedQuery preparedQuery = dataEngine.prepare( queryDefn,
				appContext );

		IQueryResults queryResults = preparedQuery.execute( null );
		IResultIterator resultIt = queryResults.getResultIterator( );
		assertTrue( resultIt.next( ) );

		resultIt.getValue( expressions[0].toString( ) );
		resultIt.getValue( expressions[1].toString( ) );
	}

	private QueryDefinition createQueryDefn( IBaseExpression[] expressions,
			GroupDefinition[] groupDefn, SortDefinition[] sortDefn,
			FilterDefinition[] filters )
	{
		// define a query design
		QueryDefinition queryDefn = newReportQuery( );

		if ( groupDefn != null )
			for ( int i = 0; i < groupDefn.length; i++ )
				queryDefn.addGroup( groupDefn[i] );
		if ( sortDefn != null )
			for ( int i = 0; i < sortDefn.length; i++ )
				queryDefn.addSort( sortDefn[i] );
		if ( expressions != null )
			for ( int i = 0; i < expressions.length; i++ )
				queryDefn.addResultSetExpression( expressions[i].toString( ),
						expressions[i] );
		if ( filters != null )
			for ( int i = 0; i < filters.length; i++ )
				queryDefn.addFilter( filters[i] );

		return queryDefn;
	}

}
