package com.atlassian.stash.internal.hibernate.dialect;

import org.hibernate.dialect.PostgreSQL9Dialect;
import org.hibernate.type.descriptor.sql.SqlTypeDescriptor;

import java.sql.Types;

/**
 * Removes Hibernate's {@code Types.BLOB}/{@code Types.CLOB} SQL type overrides when using the Postgres 9 dialect.
 *
 * @since 2.0
 */
public class CustomPostgres9Dialect extends PostgreSQL9Dialect {

    /**
     * Hibernate 4.1 "fixes" Postgres's (lack of) LOB support by overriding whatever SQL type is applied in mappings to
     * use its (broken) {@code BlobTypeDescriptor} and {@code ClobTypeDescriptor}. This breaks all Unicode support when
     * applied to Stash so this method overrides their override, returning {@code null} for those SQL types so that the
     * mapped types will be used as-is.
     * <p>
     * This fix for Hibernate's "fix" assumes that all {@code CLOB} fields in Stash will be explicitly annotated to use
     * {@code ClobTypeDescriptor} to handle the SQL-side of their mapping. As a result, it may be desirable to use this
     * facility to enforce that at the dialect level, since failure to do so will result in a field that does not store
     * Unicode strings correctly.
     *
     * @param sqlCode the SQL code for the column's {@code Types} entry
     * @return the SQL type override to apply, superceding whatever type is applied in mappings
     */
    @Override
    public SqlTypeDescriptor getSqlTypeDescriptorOverride(int sqlCode) {
        if (sqlCode == Types.BLOB || sqlCode == Types.CLOB) {
            return null;
        }
        return super.getSqlTypeDescriptorOverride(sqlCode);
    }
}
