/*
 * JBoss, Home of Professional Open Source.
 * See the COPYRIGHT.txt file distributed with this work for information
 * regarding copyright ownership.  Some portions may be licensed
 * to Red Hat, Inc. under one or more contributor license agreements.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 */

package org.teiid.translator.jdbc;

import static org.junit.Assert.*;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.junit.Test;
import org.mockito.Mockito;
import org.teiid.core.types.DataTypeManager;
import org.teiid.dqp.internal.datamgr.FakeExecutionContextImpl;
import org.teiid.language.BatchedUpdates;
import org.teiid.language.Command;
import org.teiid.language.Expression;
import org.teiid.language.ExpressionValueSource;
import org.teiid.language.Insert;
import org.teiid.language.Literal;
import org.teiid.language.Parameter;

@SuppressWarnings("nls")
public class TestJDBCUpdateExecution {

	@Test public void testInsertIteratorUpdate() throws Exception {
		Insert command = (Insert)TranslationHelper.helpTranslate(TranslationHelper.BQT_VDB, "insert into BQT1.SmallA (IntKey, IntNum) values (1, 2)"); //$NON-NLS-1$
		Parameter param = new Parameter();
		param.setType(DataTypeManager.DefaultDataClasses.INTEGER);
		param.setValueIndex(0);
		List<Expression> values = ((ExpressionValueSource)command.getValueSource()).getValues();
		values.set(0, param);
		param = new Parameter();
		param.setType(DataTypeManager.DefaultDataClasses.INTEGER);
		param.setValueIndex(1);
		values.set(1, param);
		command.setParameterValues(Arrays.asList(Arrays.asList(1, 2), Arrays.asList(1, 2)).iterator());
		Connection connection = Mockito.mock(Connection.class);
		PreparedStatement p = Mockito.mock(PreparedStatement.class);
		Mockito.stub(p.executeBatch()).toReturn(new int [] {1, 1});
		Mockito.stub(connection.prepareStatement("INSERT INTO SmallA (IntKey, IntNum) VALUES (?, ?)")).toReturn(p); //$NON-NLS-1$
		
		JDBCExecutionFactory config = new JDBCExecutionFactory();
		
		JDBCUpdateExecution updateExecution = new JDBCUpdateExecution(command, connection, new FakeExecutionContextImpl(), config);
		updateExecution.execute();
		Mockito.verify(p, Mockito.times(2)).addBatch();
	}
	
	@Test public void testAutoGeneretionKeys() throws Exception {
		Insert command = (Insert)TranslationHelper.helpTranslate("create foreign table SmallA (IntKey integer primary key, IntNum integer)", "insert into SmallA (IntKey, IntNum) values (1, 2)"); //$NON-NLS-1$
				
		Connection connection = Mockito.mock(Connection.class);
		Statement s = Mockito.mock(Statement.class);
		Mockito.stub(connection.createStatement()).toReturn(s);
		
		JDBCExecutionFactory config = new JDBCExecutionFactory() {
			@Override
			public boolean supportsGeneratedKeys() {
				return true;
			}
			
			@Override
			public boolean useColumnNamesForGeneratedKeys() {
				return true;
			}
		};
		ResultSet r = Mockito.mock(ResultSet.class);
		ResultSetMetaData rs = Mockito.mock(ResultSetMetaData.class);
		Mockito.stub(r.getMetaData()).toReturn(rs);
		
		Mockito.stub(s.getGeneratedKeys()).toReturn(r);
		
		FakeExecutionContextImpl context = new FakeExecutionContextImpl();
		((org.teiid.query.util.CommandContext)context.getCommandContext()).setReturnAutoGeneratedKeys(true);
		
		JDBCUpdateExecution updateExecution = new JDBCUpdateExecution(command, connection, context, config);
		updateExecution.execute();
		Mockito.verify(s, Mockito.times(1)).getGeneratedKeys();
		Mockito.verify(s, Mockito.times(1)).executeUpdate("INSERT INTO SmallA (IntKey, IntNum) VALUES (1, 2)", new String[] {"IntKey"});
		
		config = new JDBCExecutionFactory() {
			@Override
			public boolean supportsGeneratedKeys() {
				return true;
			}
		};
		
		s = Mockito.mock(Statement.class);
		Mockito.stub(connection.createStatement()).toReturn(s);
		Mockito.stub(s.getGeneratedKeys()).toReturn(r);
		
		updateExecution = new JDBCUpdateExecution(command, connection, context, config);
		updateExecution.execute();
		Mockito.verify(s, Mockito.times(1)).getGeneratedKeys();
		Mockito.verify(s, Mockito.times(1)).executeUpdate("INSERT INTO SmallA (IntKey, IntNum) VALUES (1, 2)", Statement.RETURN_GENERATED_KEYS);
	}
	
	@Test public void testAutoGeneretionKeysPrepared() throws Exception {
		Insert command = (Insert)TranslationHelper.helpTranslate("create foreign table SmallA (IntKey integer primary key, IntNum integer)", "insert into SmallA (IntKey, IntNum) values (1, 2)"); //$NON-NLS-1$
		((Literal)((ExpressionValueSource)command.getValueSource()).getValues().get(0)).setBindEligible(true);
		Connection connection = Mockito.mock(Connection.class);
		PreparedStatement s = Mockito.mock(PreparedStatement.class);
		Mockito.stub(connection.prepareStatement("INSERT INTO SmallA (IntKey, IntNum) VALUES (?, 2)", new String[] {"IntKey"})).toReturn(s);
		
		JDBCExecutionFactory config = new JDBCExecutionFactory() {
			@Override
			public boolean supportsGeneratedKeys() {
				return true;
			}
			
			@Override
			public boolean useColumnNamesForGeneratedKeys() {
				return true;
			}
		};
		ResultSet r = Mockito.mock(ResultSet.class);
		Mockito.stub(r.next()).toReturn(true).toReturn(false);
		
		ResultSetMetaData rs = Mockito.mock(ResultSetMetaData.class);
		Mockito.stub(r.getMetaData()).toReturn(rs);
		
		Mockito.stub(s.getGeneratedKeys()).toReturn(r);
		
		FakeExecutionContextImpl context = new FakeExecutionContextImpl();
		((org.teiid.query.util.CommandContext)context.getCommandContext()).setReturnAutoGeneratedKeys(true);
		
		JDBCUpdateExecution updateExecution = new JDBCUpdateExecution(command, connection, context, config);
		updateExecution.execute();
		Mockito.verify(s, Mockito.times(1)).getGeneratedKeys();
		Mockito.verify(s, Mockito.times(1)).executeUpdate();
		
		config = new JDBCExecutionFactory() {
			@Override
			public boolean supportsGeneratedKeys() {
				return true;
			}
		};
		
		assertEquals(0, context.getCommandContext().getGeneratedKeys().getKeyIterator().next().get(0));
	}
	
	@Test public void testBulkUpdate() throws Exception {
		Insert command = (Insert)TranslationHelper.helpTranslate(TranslationHelper.BQT_VDB, "insert into BQT1.SmallA (IntKey) values (1)"); //$NON-NLS-1$
		Parameter param = new Parameter();
		param.setType(Integer.class);
		param.setValueIndex(0);
		ExpressionValueSource evs = new ExpressionValueSource(Arrays.asList((Expression)param));
		command.setValueSource(evs);
		List<List<?>> vals = new ArrayList<List<?>>();
		for (int i = 0; i < 8; i++) {
			vals.add(Arrays.asList(i));
		}
		command.setParameterValues(vals.iterator());
		Connection connection = Mockito.mock(Connection.class);
		PreparedStatement p = Mockito.mock(PreparedStatement.class);
		Mockito.stub(p.executeBatch()).toReturn(new int[] {1, 1});
		Mockito.stub(connection.prepareStatement("INSERT INTO SmallA (IntKey) VALUES (?)")).toReturn(p); //$NON-NLS-1$
		
		JDBCExecutionFactory config = new JDBCExecutionFactory();
		config.setMaxPreparedInsertBatchSize(2);
		ResultSet r = Mockito.mock(ResultSet.class);
		ResultSetMetaData rs = Mockito.mock(ResultSetMetaData.class);
		Mockito.stub(r.getMetaData()).toReturn(rs);
		
		Mockito.stub(p.getGeneratedKeys()).toReturn(r);
		
		FakeExecutionContextImpl context = new FakeExecutionContextImpl();
		((org.teiid.query.util.CommandContext)context.getCommandContext()).setReturnAutoGeneratedKeys(true);
		
		JDBCUpdateExecution updateExecution = new JDBCUpdateExecution(command, connection, context, config);
		updateExecution.execute();
		assertArrayEquals(new int[] {1, 1, 1, 1, 1, 1, 1, 1}, updateExecution.getUpdateCounts());
	}
	
	@Test public void testBatchedUpdate() throws Exception {
		Insert command = (Insert)TranslationHelper.helpTranslate(TranslationHelper.BQT_VDB, "insert into BQT1.SmallA (IntKey) values (1)"); //$NON-NLS-1$
		Insert command1 = (Insert)TranslationHelper.helpTranslate(TranslationHelper.BQT_VDB, "insert into BQT1.SmallA (StringKey) values ('1')"); //$NON-NLS-1$
		Connection connection = Mockito.mock(Connection.class);
		Statement s = Mockito.mock(Statement.class);
		Mockito.stub(s.executeBatch()).toReturn(new int[] {1, 1});
		Mockito.stub(connection.createStatement()).toReturn(s); 
		
		JDBCExecutionFactory config = new JDBCExecutionFactory();
		ResultSet r = Mockito.mock(ResultSet.class);
		ResultSetMetaData rs = Mockito.mock(ResultSetMetaData.class);
		Mockito.stub(r.getMetaData()).toReturn(rs);
		
		Mockito.stub(s.getGeneratedKeys()).toReturn(r);
		
		FakeExecutionContextImpl context = new FakeExecutionContextImpl();
		((org.teiid.query.util.CommandContext)context.getCommandContext()).setReturnAutoGeneratedKeys(true);
		
		JDBCUpdateExecution updateExecution = new JDBCUpdateExecution(new BatchedUpdates(Arrays.asList((Command)command, command1)), connection, context, config);
		updateExecution.execute();
		assertArrayEquals(new int[] {1, 1}, updateExecution.getUpdateCounts());
	}
}
