'Update the realm entity for records, will also update the
realm in all configured realm-entities, see:
http://eden.sahanafoundation.org/wiki/S3AAA/OrgAuth#Realms1
To be called by CRUD and Importer during record update.
@param table: the Table (or tablename)
@param records: - a single record
- a single record ID
- a list of records, or a Rows object
- a list of record IDs
- a query to find records in table
@param entity: - an entity ID
- a tuple (table, instance_id)
- 0 for default lookup'

def set_realm_entity(self, table, records, entity=0, force_update=False):

    db = current.db
    s3db = current.s3db
    REALM = 'realm_entity'
    EID = 'pe_id'
    OID = 'organisation_id'
    SID = 'site_id'
    GID = 'group_id'
    entity_fields = (EID, OID, SID, GID)
    if hasattr(table, '_tablename'):
        tablename = original_tablename(table)
    else:
        tablename = table
        table = s3db.table(tablename)
    if ((not table) or (REALM not in table.fields)):
        return
    fields_in_table = ([table._id.name, REALM] + [f for f in entity_fields if (f in table.fields)])
    fields_to_load = [table[f] for f in fields_in_table]
    realm_entity = entity
    if isinstance(realm_entity, tuple):
        realm_entity = s3db.pr_get_pe_id(realm_entity)
        if (not realm_entity):
            return
    if isinstance(records, Query):
        query = records
    else:
        query = None
    if ((realm_entity != 0) and force_update and (query is not None)):
        data = {REALM: realm_entity}
        db(query).update(**data)
        self.update_shared_fields(table, query, **data)
        return
    if (query is not None):
        if (not force_update):
            query &= (table[REALM] == None)
        records = db(query).select(*fields_to_load)
    elif (not isinstance(records, (list, Rows))):
        records = [records]
    if (not records):
        return
    get_realm_entity = self.get_realm_entity
    s3_update_record_owner = self.s3_update_record_owner
    for record in records:
        if (not isinstance(record, (Row, Storage))):
            record_id = record
            row = Storage()
        else:
            row = record
            if (table._id.name not in record):
                continue
            record_id = row[table._id.name]
        q = (table._id == record_id)
        fields_missing = [f for f in fields_in_table if (f not in row)]
        if fields_missing:
            row = db(q).select(limitby=(0, 1), *fields_to_load).first()
            if (not row):
                continue
        if (row[REALM] and (not force_update)):
            continue
        _realm_entity = get_realm_entity(table, row, entity=realm_entity)
        data = {REALM: _realm_entity}
        s3_update_record_owner(table, row, update=force_update, **data)
    return
