aaberg / sql2o

sql2o is a small library, which makes it easy to convert the result of your sql-statements into objects. No resultset hacking required. Kind of like an orm, but without the sql-generation capabilities. Supports named parameters.
http://sql2o.org
MIT License
1.14k stars 229 forks source link

Bug in sql2o StringConverter #185

Open niksabaldun opened 9 years ago

niksabaldun commented 9 years ago

Class org.sql2o.converters.StringConverter, line 55:

    return val.toString().trim();

This causes any varchar field that has leading or trailing whitespace to be retrieved incorrectly (I noticed it with executeScalar). Obviously, the trim() method call needs to be removed. Also, is there any workaround I can use in the mean time?

aaberg commented 9 years ago

Hi,

Until this is fixed, you can write your own string converter. Just create a class that implements Converter<String>, and implement the convert and toDatabaseParam methods. A very simple implementation would look something like this:

public class MyCystomStringConverter implements Converter<String> {
    @Override
    public String convert(Object val) throws ConverterException {
        if (val == null) return null;
        return val.toString();
    }
    @Override
    public Object toDatabaseParam(String val) {
        return val;
    }
}

When you create your sql2o instance, you can register the converter like this:

Sql2o sql2o = new Sql2o(ds, new NoQuirks(new HashMap<Class, Converter>() {{
    put(String.class, new MyCustomStringConverter());
}}));

Regards Lars Aaberg

niksabaldun commented 9 years ago

OK, thanks, Lars.

Nik