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

import ru.yandex.webmaster3.storage.WebmasterSQLException;

/**
 * @author avhaliullin
 */
public class LightTransactionTemplateImpl implements TransactionTemplate {
    private final IWriteJdbcTemplate template;
    private final ThreadLocal<IWriteJdbcTemplate> lock;

    public LightTransactionTemplateImpl(IWriteJdbcTemplate template, ThreadLocal<IWriteJdbcTemplate> lock) {
        this.template = template;
        this.lock = lock;
    }

    @Override
    public <T> T execute(TransactionCallback<T> transaction) throws WebmasterSQLException {
        boolean alreadyInTransaction = lock.get() != null;
        try {
            if (!alreadyInTransaction) {
                lock.set(template);
            }
            return transaction.doInTransaction(template, null);
        } finally {
            if (!alreadyInTransaction) {
                lock.remove();
            }
        }
    }
}
