/*
 * Copyright 2006 Takahiro Nakamura.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package woolpack.crud;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import woolpack.utils.CheckUtils;

/**
 * 固定の更新系クエリを実行する{@link Updatable}。
 * @author nakamura
 *
 */
public class FixUpdater implements Updatable {
	private final String expression;
	private final DataSource dataSource;
	
	/**
	 * コンストラクタ。
	 * @param expression クエリ。
	 * @param dataSource データソース。
	 * @throws NullPointerException 引数のいずれかが null の場合。
	 * @throws StringIndexOutOfBoundsException expression が null の場合。
	 */
	public FixUpdater(
			final String expression,
			final DataSource dataSource) {
		CheckUtils.checkNotEmpty(expression);
		CheckUtils.checkNotNull(dataSource);
		this.expression = expression;
		this.dataSource = dataSource;
	}

	public int update(final Map<String, List<Object>> map) {
		try {
			final Connection connection = dataSource.getConnection();
			try {
				final Statement statement = connection.createStatement();
				try {
					return statement.executeUpdate(expression);
				} finally {
					statement.close();
				}
			} finally {
				connection.close();
			}
		} catch (final SQLException e) {
			throw new IllegalStateException(e);
		}
	}
}
