package com.s24.search.solr.analysis.jdbc;

import org.apache.commons.io.IOUtils;
import org.h2.jdbcx.JdbcDataSource;
import org.junit.Test;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.io.Reader;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.Statement;

import static org.junit.Assert.assertEquals;

/**
 * Test for {@link SimpleJdbcReader}.
 */
public class SimpleJdbcReaderTest {

   /**
    * Test for {@link SimpleJdbcReader#getReader()}.
    */
   @Test
   public void getReader() throws Exception {

      // Create H2 database instance
      JdbcDataSource dataSource = new JdbcDataSource();
      dataSource.setURL("jdbc:h2:mem:reader;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false");
      dataSource.setUser("sa");
      dataSource.setPassword("");

      // Add synonym table with some content
      try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) {
         statement.addBatch("CREATE TABLE synonyms(synonyms VARCHAR(255))");
         statement.addBatch("INSERT INTO synonyms VALUES ('test1=>testA,testB')");
         statement.addBatch("INSERT INTO synonyms VALUES ('test2=>testC,testD')");
         statement.executeBatch();
      }
      // Register data source with JNDI
      Context context = new InitialContext();
      context.bind("java:comp/env/dataSource", dataSource);

      Reader reader = new SimpleJdbcReader(dataSource, "select synonyms from synonyms", false).getReader();
      StringWriter synonyms = new StringWriter();
      IOUtils.copy(reader, synonyms);

      assertEquals("test1=>testA,testB\ntest2=>testC,testD", synonyms.toString());
   }

   /**
    * Test for {@link SimpleJdbcReader#SimpleJdbcReader(DataSource, String, boolean)}.
    */
   @Test
   public void ignore() {
      // Missing data source will be ignored
      new SimpleJdbcReader(null, "sql", true);
   }

}
