Question

I have a module that uses Storm ORM to save data in a local SQLite database. I'm working on another module that will sync the data to a central PostgreSQL server. I thought I would be clever and do the following:

unsynced = localStore.find(MyType, MyType.synced == False)

for assign in unsynced:
    self.remoteStore.add(assign)

This doesn't quite work as hoped, the following error is thrown:

object at 0x18bb4d0 is part of another store

Is there some way to break the association with the local store so I can save the data remotely? This can be complicated slightly by the fact that I need to flip the synced flag in the local copy after successfully saving the data remotely.

Was it helpful?

Solution

There is nothing in Storm to do this automatically, since it isn't always obvious what should be copied:

  1. The model class representing the table may not fully describe the underlying table. There may be additional fields that are not being used from the Python side.
  2. It isn't clear what to do with foreign keys / references. Do you copy the related objects over too? Do you leave the foreign key IDs as is and hope that it doesn't result in an integrity error when inserting into the second database? Do you try to find an equivalent object in the other database to reference? Which key would you use to do that search?

Of course, these issues may not affect your application. In that case, you could write a method to duplicate an object so that it can be added to another store:

def copy(self):
    """Create a new object with the same property values."""
    other = self.__class__()
    # Copy over the relevant fields.  If you're using an integer primary key,
    # then this probably doesn't include that key.
    other.foo = self.foo
    other.bar = self.bar
    ...
    return other

You could then alter your code to do something like:

for assign in unsynced:
    self.remoteStore.add(assign.copy())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top