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

Ignore field of TableModel - generate code, but do NOT persist the field to database #210

Closed MFlisar closed 8 years ago

MFlisar commented 8 years ago

I want to define a variable in my table with getter and setter (via a ModelMethod). But I want the field to be accessible only and not part of the table itself.

Something like following (I added two comments to describe what I want):

@TableModelSpec(className="GroupedFolder", tableName="groupedFolder")
@Implements(interfaceClasses = {Serializable.class})
public class GroupedFolderEntrySpec
{
    @PrimaryKey
    @ColumnSpec(name = "_id")
    long id;

    @ColumnSpec(name = "fkFolderGroup", defaultValue = "0")
    public long fkFolderGroup;

    // this removes the following from the generated class
            // I would need to only don't consider it for the table columns. How would I do that???
    @Ignore
    public FolderGroup internalFolderGroup;

    @ModelMethod
    public static void setFolderGroup(GroupedFolder item, FolderGroup group) {
        // this setter should somehow set internalFolderGroup value... How?????
                    // this is called from code manually => via a custom query with leftJoin of
                    // two tables and then processing the data and setting the dependent value as well
    }
}
sbosley commented 8 years ago

We don't have something that will do this automatically, but it's actually pretty easy to accomplish with @ModelMethod alone.

Every model has the ability to attach what we call "transitory" metadata. This is basically a key/value store where the keys are strings and the values are any objects. The relevant methods are things like getTransitory(), putTransitory(), hasTransitory(), etc., and exist on all model classes. Transitory metadata is ignored when persisting to the database.

I'd suggest implementing your getters and setters as model methods to store the value as a transitory value. You actually wouldn't even need the FolderGroup field if you did it this way, as you'd be accessing everything via the getters and setters you defined. It would look something like this:

@ModelMethod
public static FolderGroup getFolderGroup(GroupedFolder item) {
    if (!item.hasTransitory(FOLDER_GROUP_TRANSITORY_KEY)) {
        return null; // Or populate it somehow
    }
    return (FolderGroup) item.getTransitory(FOLDER_GROUP_TRANSITORY_KEY);
}

@ModelMethod
public static void setFolderGroup(GroupedFolder item, FolderGroup group) {
    item.putTransitory(FOLDER_GROUP_TRANSITORY_KEY, group);
}
MFlisar commented 8 years ago

Thanks. That works.