package com.yhy.module.core.dal.typehandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.*;

/**
 * PostgreSQL text[] 类型处理器
 * 
 * @author yihuiyong
 */
@MappedTypes(String[].class)
public class PostgreSQLTextArrayTypeHandler extends BaseTypeHandler<String[]> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String[] parameter, JdbcType jdbcType) throws SQLException {
        // 将 String[] 转换为 PostgreSQL Array
        Connection conn = ps.getConnection();
        Array array = conn.createArrayOf("text", parameter);
        ps.setArray(i, array);
    }

    @Override
    public String[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return getArray(rs.getArray(columnName));
    }

    @Override
    public String[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return getArray(rs.getArray(columnIndex));
    }

    @Override
    public String[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return getArray(cs.getArray(columnIndex));
    }

    private String[] getArray(Array array) throws SQLException {
        if (array == null) {
            return new String[0];
        }
        Object[] objects = (Object[]) array.getArray();
        if (objects == null) {
            return new String[0];
        }
        String[] result = new String[objects.length];
        for (int i = 0; i < objects.length; i++) {
            result[i] = objects[i] == null ? null : objects[i].toString();
        }
        return result;
    }
}
