package xyz.wbsite.frame.schedule;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import xyz.wbsite.frame.auth.LocalData;
import xyz.wbsite.frame.utils.LogUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public abstract class RunSqlTask extends RunFixRepeatTask {

    private Connection connection;

    @Override
    public void run() {
        try {
            if (connection == null || connection.isClosed()) {
                SqlSessionFactory factory = LocalData.getBean(SqlSessionFactory.class);
                SqlSession sqlSession = factory.openSession(true);
                connection = sqlSession.getConnection();
            }
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.e("schedule: get connection failed!");
            return;
        }
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(getSql());
            preparedStatement.execute();
            preparedStatement.close();
        } catch (SQLException e) {
            e.printStackTrace();
            LogUtil.e("RunSqlTask exec failed! SQL:[" + getSql() + "]");
        }
    }

    public abstract String getSql();
}
