BindEnumValue.java

package net.morimekta.providence.jdbi.v2.annotations;

import net.morimekta.providence.PEnumValue;
import net.morimekta.providence.jdbi.v2.EnumValueArgument;
import net.morimekta.providence.jdbi.v2.util.NullArgument;
import org.skife.jdbi.v2.sqlobject.Binder;
import org.skife.jdbi.v2.sqlobject.BinderFactory;
import org.skife.jdbi.v2.sqlobject.BindingAnnotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.sql.Types;

@Target(value = ElementType.PARAMETER)
@Retention(value = RetentionPolicy.RUNTIME)
@BindingAnnotation(BindEnumValue.Factory.class)
public @interface BindEnumValue {
    String value();

    class Factory implements BinderFactory<BindEnumValue> {
        @Override
        public Binder<BindEnumValue, Object> build(BindEnumValue bind) {
            return (sqlStatement, annotation, arg) -> {
                if (arg instanceof PEnumValue) {
                    PEnumValue value = (PEnumValue) arg;
                    sqlStatement.bind(annotation.value(), new EnumValueArgument(value));
                } else if (arg == null){
                    sqlStatement.bind(annotation.value(), new NullArgument(Types.INTEGER));
                } else {
                    throw new IllegalArgumentException("Not a providence enum value: " + arg.getClass().toString());
                }
            };
        }
    }

}