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

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.QueryDefinition;
import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression;

import testutil.APITestCase;
import testutil.ConfigText;

/**
 * Test cases for data engine scripting features
 */
public class DataSourceTest extends APITestCase {

	private static String dumpDataSourceScript = ConfigText
			.getString("Script.DumpDataSource");

	/*
	 * @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"),
		// "CREATE TABLE ScriptTestTable (COUNTRY varchar(10), CITY varchar(10),
				// SALE_DATE timestamp, AMOUNT int, ORDERED int, NULL_COLUMN
				// varchar(10))",
				ConfigText.getString("Api.TestData.TestDataFileName"));
	}

	/** Test data source script object */
	public void test1_ReadDataSource() throws Exception {
		// Before-Open: read data source properties
		this.dataSource
				.setBeforeOpenScript("testPrintln(\"DataSource.beforeOpen:\"); "
						+ dumpDataSourceScript);

		// After-Open: read data source properties
		this.dataSource
				.setAfterOpenScript("testPrintln(\"DataSource.afterOpen:\"); "
						+ dumpDataSourceScript);

		this.dataSource
				.setBeforeCloseScript("testPrintln(\"DataSource.beforeClose:\"); "
						+ dumpDataSourceScript);

		this.dataSource
				.setAfterCloseScript("testPrintln(\"DataSource.afterClose:\"); "
						+ dumpDataSourceScript);

		createAndRunQuery();
		// Force close data source to verify beforeClose and afterClose
		this.dataEngine.shutdown();

		checkOutputFile();
	}

	private void createAndRunQuery() throws Exception {
		// define a query design
		QueryDefinition queryDefn = newReportQuery();

		ScriptExpression exprs[] = new ScriptExpression[1];
		exprs[0] = new ScriptExpression("dataSetRow.COUNTRY");
		queryDefn.addResultSetExpression(exprs[0].toString(), exprs[0]);

		IPreparedQuery preparedQuery = dataEngine.prepare(queryDefn);
		IQueryResults queryResults = preparedQuery.execute(null);
		IResultIterator it = queryResults.getResultIterator();
		outputQueryResult(it, new String[] { exprs[0].toString() });
		it.close();
		queryResults.close();
	}

}
