yahoo / squidb

SquiDB is a SQLite database library for Android and iOS
https://github.com/yahoo/squidb/wiki
Apache License 2.0
1.31k stars 132 forks source link

Support of custom types #187

Closed aminelaadhari closed 8 years ago

aminelaadhari commented 8 years ago

Is this supported ? I want to use JodaTime DateTime or other types using custom type adapters.

For now I am using ModelMethods as a workaround but it's a lot of boilerplate code:

    @ColumnSpec(name = "createdAt")
    long createdAtMillis;

    @ModelMethod
    public static DateTime getCreatedAt(Habit instance) {
        return new DateTime(instance.get(Habit.CREATED_AT_MILLIS));
    }

    @ModelMethod
    public static Habit setCreatedAt(Habit instance, DateTime dateTime) {
        instance.set(Habit.CREATED_AT_MILLIS, dateTime.getMillis());
        return instance;
    }

Is there a better way to implement this ?

sbosley commented 8 years ago

Indeed there is! You can write a code generation plugin for custom data types as described on this wiki page.

aminelaadhari commented 8 years ago

Thanks @sbosley, I will try to create one for Joda DateTime and post back its github reposiotry link here.

aminelaadhari commented 8 years ago

I followed the wiki page to create a plugin which converts joda DateTime fields: https://github.com/aminelaadhari/squidb-datetime

@DateTimeColumn DateTime createdAt;

and the result is:

    public DateTime getCreatedAt() {
        Long instant = this.get(CREATED_AT);
        return instant == null ? null : new DateTime(instant);
    }

    public Habit setCreatedAt(DateTime createdAt) {
        this.set(CREATED_AT, createdAt == null ? null : createdAt.getMillis());
        return this;
    }

One question though, do you think it's better to have the annotation @DateTimeColumn, or I can remove it ?

aminelaadhari commented 8 years ago

I ended by removing the annotation because I think a type check is sufficient.

sbosley commented 8 years ago

Looks great! I think you're right that in this case the type check is sufficient. Is it ok with you if we add a link to your repo to the wiki so that other users who might be interested can use your plugin?

aminelaadhari commented 8 years ago

Yes, sure !

sbosley commented 8 years ago

👍 awesome! Going to assume that this issue can be closed then; glad this worked for you!