<s> import json <EOL> from copy import deepcopy <EOL> class EntityManager ( object ) : <EOL> def __init__ ( self , engine ) : <EOL> self . engine = engine <EOL> self . _entities = engine [ '<STR_LIT>' ] <EOL> self . _other_names = engine [ '<STR_LIT>' ] <EOL> self . _identities = engine [ '<STR_LIT>' ] <EOL> self . _addresses = engine [ '<STR_LIT>' ] <EOL> def _clear_table ( self , table , uids ) : <EOL> if '<STR_LIT>' not in table . table . c : <EOL> return <EOL> q = table . table . delete ( ) . where ( table . table . c . uid . in_ ( uids ) ) <EOL> self . engine . executable . execute ( q ) <EOL> def _pad_rows ( self , rows ) : <EOL> keys = set ( [ ] ) <EOL> for row in rows : <EOL> keys . update ( row . keys ( ) ) <EOL> for row in rows : <EOL> for key in keys : <EOL> if key not in row : <EOL> row [ key ] = None <EOL> return rows <EOL> def clear_entities ( self , entities ) : <EOL> uids = [ e . get ( '<STR_LIT>' ) for e in entities ] <EOL> self . _clear_table ( self . _entities , uids ) <EOL> self . _clear_table ( self . _identities , uids ) <EOL> self . _clear_table ( self . _other_names , uids ) <EOL> self . _clear_table ( self . _addresses , uids ) <EOL> def save_entities ( self , entities ) : <EOL> self . clear_entities ( entities ) <EOL> identities = [ ] <EOL> other_names = [ ] <EOL> addresses = [ ] <EOL> for entity in entities : <EOL> entity [ '<STR_LIT>' ] = json . dumps ( entity ) <EOL> base = { <EOL> '<STR_LIT>' : entity . get ( '<STR_LIT>' ) , <EOL> '<STR_LIT:name>' : entity . get ( '<STR_LIT:name>' ) <EOL> } <EOL> for identity in entity . pop ( '<STR_LIT>' , [ ] ) : <EOL> identity . update ( base ) <EOL> identities . append ( identity ) <EOL> for other_name in entity . pop ( '<STR_LIT>' , [ ] ) : <EOL> other_name . update ( base ) <EOL> other_names . append ( other_name ) <EOL> for address in entity . pop ( '<STR_LIT>' , [ ] ) : <EOL> address . update ( base ) <EOL> addresses . append ( address ) <EOL> self . _entities . insert_many ( self . _pad_rows ( entities ) ) <EOL> self . _identities . insert_many ( self . _pad_rows ( identities ) ) <EOL> self . _other_names . insert_many ( self . _pad_rows ( other_names ) ) <EOL> self . _addresses . insert_many ( self . _pad_rows ( addresses ) ) </s>
