def org_service_root_service(service_id):
 db = current.db
 table = current.s3db.org_service
 record = db((table.id == service_id)).select(table.id, table.root_service, table.parent).first()
 try:
  parent = record.parent
  current_root = record.root_service
 except AttributeError:
  current.log.error(('Cannot find record with service_id: %s' % service_id))
  raise
 if parent:
  if (parent == service_id):
   raise KeyError(('Service #%s showing with parent #%s' % (service_id, parent)))
  new_root = org_service_root_service(parent)
 else:
  new_root = service_id
 if (current_root != new_root):
  def descendants(ids):
   rows = db(table.parent.belongs(ids)).select(table.id)
   children = set((row.id for row in rows))
   if children:
    children |= descendants(children)
    return (ids | children)
   else:
    return ids
  nodes = descendants(set([service_id]))
  db(table.id.belongs(nodes)).update(root_service=new_root)
 return new_root

def org_service_root_service ( service_id ) : db = current . db table = current . s3db . org_service record = db ( ( table . id == service_id ) ) . select ( table . id , table . root_service , table . parent ) . first ( ) try : parent = record . parent current_root = record . root_service except AttributeError : current . log . error ( ( 'Cannot find record with service_id: %s' % service_id ) ) raise if parent : if ( parent == service_id ) : raise KeyError ( ( 'Service #%s showing with parent #%s' % ( service_id , parent ) ) ) new_root = org_service_root_service ( parent ) else : new_root = service_id if ( current_root != new_root ) : def descendants ( ids ) : rows = db ( table . parent . belongs ( ids ) ) . select ( table . id ) children = set ( ( row . id for row in rows ) ) if children : children |= descendants ( children ) return ( ids | children ) else : return ids nodes = descendants ( set ( [ service_id ] ) ) db ( table . id . belongs ( nodes ) ) . update ( root_service = new_root ) return new_root
update the root_service .