package ru.yandex.webmaster3.storage.util.sql;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.jdbc.core.RowMapper;

import ru.yandex.webmaster3.storage.WebmasterSQLException;

/**
 * @author avhaliullin
 */
public abstract class AbstractDBService {
    private JdbcProvider jdbcProvider;

    public <T> T executeInTransaction(TransactionTemplate template, TransactionCallback<T> callback) throws WebmasterSQLException {
        return template.execute(callback);
    }

    protected <T> T safeQueryAtLeastOne(IReadJdbcTemplate template, String query, RowMapper<T> mapper, Object... params) throws WebmasterSQLException {
        List<T> res = template.query(query, mapper, params);
        if (res.isEmpty()) {
            return null;
        } else {
            return res.get(0);
        }
    }

    protected IReadJdbcTemplate getReadTemplate() {
        return jdbcProvider.getReadTemplate();
    }

    protected IWriteJdbcTemplate getWriteTemplate() {
        return jdbcProvider.getWriteTemplate();
    }

    protected TransactionTemplate getTransactionTemplate() {
        return jdbcProvider.getTransactionTemplate();
    }

    public JdbcProvider getJdbcProvider() {
        return jdbcProvider;
    }

    protected static String escapeSql(String str) {
        if (str == null) {
            return null;
        }
        return StringUtils.replace(str, "'", "''");
    }

    @Required
    public void setJdbcProvider(JdbcProvider jdbcProvider) {
        this.jdbcProvider = jdbcProvider;
    }
}
