marcoarment / FCModel

An alternative to Core Data for people who like having direct SQL access.
MIT License
1.65k stars 173 forks source link

Use existsInDatabase property during save to allow overriding #110

Closed jsclayton closed 1 month ago

jsclayton commented 9 years ago

Small change to use the existsInDatabase property instead of checking the same thing.

The reason for the change is that I'd like to be able to have models inserted as new instead of updated when they have changes like so:

override var existsInDatabase: Bool {
    return super.existsInDatabase & !self.hasUnsavedChanges
}

override func save() -> Bool {
    if self.hasUnsavedChanges {
        self.loadId = Load.primaryKeyValueForNewInstance().longLongValue
    }
    return super.save()
}
marcoarment commented 9 years ago

To be clear, in your use-case, is loadId the primary key, so it's avoiding duplicate-insert errors by changing the primary key on every save?

Seems like a really bad idea that could cause weird bugs, since the assumption is that an instance's primary key value never changes after creation. Wouldn't a better pattern be to make a new instance and copy any relevant values from the old one?

jsclayton commented 9 years ago

Yes loadId is the primary key. The goal is immutable objects to maintain a history. I'm loading the model, presenting an edit form, and if the user changed something saving a new revision instead of overwriting the prior version.

Copying values to a new object is the other option I'd considered, but with these non-unique instances changing the primary key on save and inserting seemed like it would be the least error prone approach.