def on_update(item, new_attr, old_attr):
        # remove duplicates
        new_attr.value = list(set(new_attr.value))

        # get previous value
        if old_attr:
            prv_value = set(old_attr.value)
            no_access_list = [id for id in old_attr.value
                              if db.get_item(id) is None]
        else:
            prv_value = set()
            no_access_list = []

        # get current value
        current_value = set(new_attr.value + no_access_list)

        if current_value != prv_value:
            # calculate added references
            ids_added = list(current_value - prv_value)
            if ids_added:
                RelatorNEventHandler._add_references(new_attr, ids_added,
                                                     item._id)
            # calculate removed references
            ids_removed = list(prv_value - current_value)
            if ids_removed:
                RelatorNEventHandler._remove_references(new_attr, ids_removed,
                                                        item._id)
Exemplo n.º 2
0
    def on_update(item, new_attr, old_attr):
        # remove duplicates
        new_attr.value = list(set(new_attr.value))

        # get previous value
        if old_attr:
            prv_value = set(old_attr.value)
            no_access_list = [
                id for id in old_attr.value if db.get_item(id) is None
            ]
        else:
            prv_value = set()
            no_access_list = []

        # get current value
        current_value = set(new_attr.value + no_access_list)

        if current_value != prv_value:
            # calculate added references
            ids_added = list(current_value - prv_value)
            if ids_added:
                RelatorNEventHandler._add_references(new_attr, ids_added,
                                                     item._id)
            # calculate removed references
            ids_removed = list(prv_value - current_value)
            if ids_removed:
                RelatorNEventHandler._remove_references(
                    new_attr, ids_removed, item._id)
Exemplo n.º 3
0
 def get_item(self):
     item = None
     if self.value:
         item = db.get_item(self.value)
         if self.relAttr not in item.__props__:
             return None
     return item
Exemplo n.º 4
0
 def get_item(self):
     item = None
     if self.value:
         item = db.get_item(self.value)
         if self.relAttr not in item.__props__:
             return None
     return item
Exemplo n.º 5
0
    def get_parent(self):
        """
        Returns the parent container

        @return: the parent container object
        @rtype: type
        """
        return db.get_item(self._pid)
Exemplo n.º 6
0
    def get_parent(self):
        """
        Returns the parent container

        @return: the parent container object
        @rtype: type
        """
        return db.get_item(self._pid)
Exemplo n.º 7
0
    def get_items(self):
        """
        This method returns the items that this data type
        instance references.

        @rtype: L{ObjectSet<porcupine.core.objectSet.ObjectSet>}
        """
        items = [db.get_item(id) for id in self.value]
        return ObjectSet([item for item in items if item is not None])
def login(self, username, password):
    "Remote method for authenticating users"
    users_container = db.get_item('users')
    user = users_container.get_child_by_name(username)
    if user and hasattr(user, 'authenticate'):
        if user.authenticate(password):
            context.session.userid = user.id
            return True
    return False
 def get_parent(self, trans=None):
     """
     Returns the parent container.
             
     @param trans: A valid transaction handle
     @return: the parent container object
     @rtype: type
     """
     return db.get_item(self._parentid, trans)
Exemplo n.º 10
0
def login(self, username, password):
    "Remote method for authenticating users"
    users_container = db.get_item('users')
    user = users_container.get_child_by_name(username)
    if user and hasattr(user, 'authenticate'):
        if user.authenticate(password):
            context.session.userid = user.id
            return True
    return False
def selectcontainer(self):
    "Displays a dialog for selecting the destination container"
    rootFolder = db.get_item("")
    params = {"ROOT_ID": "/", "ROOT_IMG": rootFolder.__image__, "ROOT_DN": rootFolder.displayName.value, "ID": self.id}
    sAction = context.request.queryString["action"][0]
    params["TITLE"] = "@@%s@@" % sAction.upper()
    if sAction != "select_folder":
        params["TITLE"] += " &quot;%s&quot;" % self.displayName.value
    return params
Exemplo n.º 12
0
    def get_items(self):
        """
        This method returns the items that this data type
        instance references.

        @rtype: L{ObjectSet<porcupine.core.objectSet.ObjectSet>}
        """
        items = [db.get_item(id) for id in self.value]
        return ObjectSet([item for item in items
                          if item is not None])
 def get_items(self, trans=None):
     """
     This method returns the items that this data type
     instance references.
     
     @param trans: A valid transaction handle
     
     @rtype: list}
     """
     return filter(None, [db.get_item(id, trans)
                          for id in self.value])
def getSecurity(self):
    "Returns information about the object's security descriptor"
    l = []
    for sID in self.security:
        oUser = db.get_item(sID)
        if oUser is not None:
            dn = oUser.displayName.value
        else:
            dn = sID
        l.append({"id": sID, "displayName": dn, "role": str(self.security[sID])})
    return l
Exemplo n.º 15
0
    def get_item(self):
        """
        This method returns the object that this data type
        instance references. If the current user has no read
        permission on the referenced item or it has been deleted
        then it returns None.

        @rtype: L{GenericItem<porcupine.systemObjects.GenericItem>}
        @return: The referenced object, otherwise None
        """
        item = None
        if self.value:
            item = db.get_item(self.value)
        return item
Exemplo n.º 16
0
    def get_item(self):
        """
        This method returns the object that this data type
        instance references. If the current user has no read
        permission on the referenced item or it has been deleted
        then it returns None.

        @rtype: L{GenericItem<porcupine.systemObjects.GenericItem>}
        @return: The referenced object, otherwise None
        """
        item = None
        if self.value:
            item = db.get_item(self.value)
        return item
Exemplo n.º 17
0
def selectcontainer(self):
    "Displays a dialog for selecting the destination container"
    rootFolder = db.get_item('')
    params = {
        'ROOT_ID': '',
        'ROOT_IMG': rootFolder.__image__,
        'ROOT_DN': rootFolder.displayName.value,
        'ID': self.id
    }
    sAction = context.request.queryString['action'][0]
    params['TITLE'] = '@@%s@@' % sAction.upper()
    if sAction != 'select_folder':
        params['TITLE'] += ' &quot;%s&quot;' % self.displayName.value
    return params
Exemplo n.º 18
0
 def test():
     schema.TestFolder.__props__['z'] = (datatypes.String, [],
                                         {'value': 'default'})
     # create new folder
     folder = self._get_folder()
     # add it to the root folder
     folder.append_to('')
     try:
         # reload it
         folder2 = db.get_item(folder.id)
         self.assertEqual(folder2.z.value, 'default')
     finally:
         folder.delete()
         # remove added attribute from schema
         del schema.TestFolder.__props__['z']
Exemplo n.º 19
0
def getSecurity(self):
    "Returns information about the object's security descriptor"
    l = []
    for sID in self.security:
        oUser = db.get_item(sID)
        if oUser is not None:
            dn = oUser.displayName.value
        else:
            dn = sID
        l.append({
            'id': sID,
            'displayName': dn,
            'role': str(self.security[sID])
        })
    return l
Exemplo n.º 20
0
 def test():
     schema.TestFolder.__props__['z'] = (datatypes.String, [], {
         'value': 'default'
     })
     # create new folder
     folder = self._get_folder()
     # add it to the root folder
     folder.append_to('')
     try:
         # reload it
         folder2 = db.get_item(folder.id)
         self.assertEqual(folder2.z.value, 'default')
     finally:
         folder.delete()
         # remove added attribute from schema
         del schema.TestFolder.__props__['z']
 def get_item(self, trans=None):
     """
     This method returns the object that this data type
     instance references. If the current user has no read
     permission on the referenced item or it has been deleted
     then it returns None.
     
     @param trans: A valid transaction handle
     
     @rtype: type
     @return: The referenced object, otherwise None
     """
     item = None
     if self.value:
         item = db.get_item(self.value, trans)
     return item
Exemplo n.º 22
0
def __blank__(self):
    "Displays the desktop"
    oUser = context.user
    params = {
        'USER': oUser.displayName.value,
        'ROOT_NAME': self.displayName.value,
        'AUTO_RUN': '',
        'RUN_MAXIMIZED': 0,
        'SETTINGS_DISABLED': '',
        'LOGOFF_DISABLED': ''
    }
    if hasattr(oUser, 'authenticate'):
        settings = oUser.settings
        params['AUTO_RUN'] = \
            settings.value.setdefault('AUTO_RUN', '')
        params['RUN_MAXIMIZED'] = \
            int(settings.value.setdefault('RUN_MAXIMIZED', False))
        taskbar_position = \
            settings.value.get('TASK_BAR_POS', 'bottom')
    else:
        taskbar_position = 'bottom'
        params['SETTINGS_DISABLED'] = 'true'
        params['LOGOFF_DISABLED'] = 'true'

    params['REPOSITORY_DISABLED'] = 'true'
    params['PERSONAL_FOLDER'] = ''
    if hasattr(oUser, 'personalFolder'):
        params['REPOSITORY_DISABLED'] = 'false'
        params['PERSONAL_FOLDER'] = oUser.personalFolder.value

    # has the user access to recycle bin?
    rb = db.get_item('rb')
    if rb:
        params['RB_NAME'] = rb.displayName.value
    else:
        params['RB_NAME'] = None

    params['BOTTOM'] = taskbar_position == 'bottom'

    # get applications
    sOql = "select launchUrl, displayName, icon from 'apps' " + \
           "order by displayName asc"
    params['APPS'] = command.execute(sOql)

    return params
def __blank__(self):
    "Displays the desktop"
    oUser = context.user
    params = {
        'USER': oUser.displayName.value,
        'ROOT_NAME': self.displayName.value,
        'AUTO_RUN': '',
        'RUN_MAXIMIZED': 0,
        'SETTINGS_DISABLED': '',
        'LOGOFF_DISABLED': ''}
    if hasattr(oUser, 'authenticate'):
        settings = oUser.settings
        params['AUTO_RUN'] = \
            settings.value.setdefault('AUTO_RUN', '')
        params['RUN_MAXIMIZED'] = \
            int(settings.value.setdefault('RUN_MAXIMIZED', False))
        taskbar_position = \
            settings.value.get('TASK_BAR_POS', 'bottom')
    else:
        taskbar_position = 'bottom'
        params['SETTINGS_DISABLED'] = 'true'
        params['LOGOFF_DISABLED'] = 'true'

    params['REPOSITORY_DISABLED'] = 'true'
    params['PERSONAL_FOLDER'] = ''
    if hasattr(oUser, 'personalFolder'):
        params['REPOSITORY_DISABLED'] = 'false'
        params['PERSONAL_FOLDER'] = oUser.personalFolder.value

    # has the user access to recycle bin?
    rb = db.get_item('rb')
    if rb:
        params['RB_NAME'] = rb.displayName.value
    else:
        params['RB_NAME'] = None

    params['BOTTOM'] = taskbar_position == 'bottom'

    # get applications
    sOql = "select launchUrl, displayName, icon from 'apps' " + \
           "order by displayName asc"
    params['APPS'] = command.execute(sOql)

    return params
Exemplo n.º 24
0
        def test():
            # create a new folder
            folder = self._get_folder()
            # now remove the description data type
            description = schema.TestFolder.__props__.pop('x')
            # add it to the root folder
            folder.append_to('')
            try:
                # update it in order for schema updates to persist
                folder.update()

                # reload it
                folder2 = db.get_item(folder.id)
                self.assertRaises(AttributeError, getattr, folder2, 'x')
            finally:
                # remove item
                folder.delete()
                # add description back
                schema.TestFolder.__props__['x'] = description
Exemplo n.º 25
0
        def test():
            # create a new folder
            folder = self._get_folder()
            # now remove the description data type
            description = schema.TestFolder.__props__.pop('x')
            # add it to the root folder
            folder.append_to('')
            try:
                # update it in order for schema updates to persist
                folder.update()

                # reload it
                folder2 = db.get_item(folder.id)
                self.assertRaises(AttributeError, getattr, folder2, 'x')
            finally:
                # remove item
                folder.delete()
                # add description back
                schema.TestFolder.__props__['x'] = description
Exemplo n.º 26
0
def h_200(params, variables, forObject = None):
    select_fields = params[0]
    
    # get aliases
    aliases = []
    for expr, alias, aggr in select_fields:
        if expr != alias:
            variables[alias] = (expr, None, None)
            aliases.append(alias)

    field_names = [ x[1] for x in select_fields ]
    expressions = [ tuple(x[0::2]) for x in select_fields ]
    
    select_from = params[1]
    where_condition = params[2]
    
    if params[3]:
        sort_order, order_by = params[3]
        
        for ind, order_field in enumerate(order_by):
            expr, alias, aggr = order_field
            if alias in aliases:
                order_by[ind] = select_fields[ field_names.index(alias) ]
            elif expr != alias:
                if (expr, aggr) in expressions:
                    order_by[ind] = select_fields[expressions.index((expr,
                                                                     aggr))]
                else:
                    variables[alias] = (expr, None, None)
                    aliases.append(alias)
    else:
        order_by = []

    group_by = params[4]
    if group_by:
        for ind, group_field in enumerate(group_by):
            expr, alias, aggr = group_field
            if alias in aliases:
                group_by[ind] = select_fields[field_names.index(alias)]
            elif expr != alias:
                if (expr, aggr) in expressions:
                    group_by[ind] = select_fields[expressions.index((expr,
                                                                     aggr))]
                else:
                    variables[alias] = (expr, None, None)
                    aliases.append(alias)

    if select_fields:
        all_fields = select_fields + order_by + group_by
    else:
        all_fields = [['**', '**', '']] + order_by + group_by
    
    aggregates = [x[2] for x in all_fields]
    results = []
    
    for deep, object_id in select_from:
        if deep==2:
            # this:attr
            if not forObject:
                raise TypeError, \
                    'Inner scopes using "this:" are valid only in sub-queries'
            if hasattr(forObject, object_id):
                attr = getattr(forObject, object_id)
                if isinstance(attr, datatypes.ReferenceN):
                    refObjects = attr.get_items()
                elif isinstance(attr, datatypes.Reference1):
                    refObjects = [attr.get_item()]
                else:
                    raise TypeError, ('Inner scopes using "this:" are ' +
                                      'valid only ReferenceN or Reference1 ' +
                                      'data types')
                r = select(False, refObjects, all_fields,
                           where_condition, variables)
                results.extend(r)
        else:
            # swallow-deep
            obj = db.get_item(object_id)
            if obj != None and obj.isCollection:
                children = obj.get_children()
                r = select(deep, children, all_fields,
                           where_condition, variables)
                results.extend(r)
    #print results
    if results:
        if group_by:
            if select_fields:
                #construct groups
                group_dict = {}
                igrpstart = len(select_fields) + len(order_by)
                igrpend = igrpstart + len(group_by)
                for rec in results:
                    group_value = tuple(rec[igrpstart:igrpend])
                    group_dict[group_value] = \
                        group_dict.setdefault(group_value, [])
                    group_dict[group_value].append(rec)
                groups = [tuple(g) for g in group_dict.values()]
            else:
                raise TypeError, \
                    'GROUP BY clause is incompatible with SELECT *'
        else:
            groups = [results]
        
        #print len(groups)
        results = []
        
        if aggregates != [''] * len(aggregates) or group_by:
            for ind, group in enumerate(groups):
                group_sum = []
                for aggr_index, aggr_type in enumerate(aggregates):
                    # aggregates exclude None values
                    group_sum.append(computeAggregate(
                        aggr_type,
                        [x[aggr_index]
                         for x in group
                         if x[aggr_index] != None]))
                groups[ind] = (tuple(group_sum),)
        
        for group in groups:
            results.extend(group)
        
        if order_by:
            # extract sort values
            istart = 1
            if select_fields:
                istart = len(select_fields)
            sortlist = tuple([x[istart:istart + len(order_by)]
                              for x in results])
            results = sortList(sortlist, results)
            # if it is descending reverse the result list
            if not sort_order: results.reverse()
    
    # remove aliases
    for alias in aliases:
        del variables[alias]
    
    if select_fields:
        schema = field_names
        # truncate to keep only select fields
        iend = len(select_fields)
        results = tuple([x[:iend] for x in results])
    else:
        schema = None
        results = tuple([x[:1][0] for x in results])
        
#    print results

    return ObjectSet(tuple(results), schema)
Exemplo n.º 27
0
def h_200(prepared, variables, for_object=None):
    select_fields = prepared["select_fields"]
    field_names = prepared["field_names"]
    all_fields = prepared["all_fields"]
    select_from = prepared["select_from"]
    select_range = prepared["select_range"]
    where_condition = prepared["where_condition"]
    aliases = prepared["aliases"]
    order_by = prepared["order_by"]
    sort_order = prepared["sort_order"]
    group_by = prepared["group_by"]

    variables = variables.copy()
    variables.update(aliases)

    aggregates = [x[2] for x in all_fields]

    # print order_by
    # print len(optimized)
    # print('opt: %s' % optimized)

    results = ObjectSet()
    for deep, object_id in select_from:
        if deep == 2:
            # this:attr
            if not for_object:
                raise TypeError('Inner scopes using "this:" are valid only in sub-queries')
            if hasattr(for_object, object_id):
                attr = getattr(for_object, object_id)
                if isinstance(attr, (datatypes.ReferenceN, datatypes.Composition)):
                    ref_objects = attr.get_items()
                elif isinstance(attr, datatypes.Reference1):
                    ref_objects = [attr.get_item()]
                else:
                    raise TypeError(
                        'Inner scopes using "this:" are '
                        + "valid only ReferenceN, Reference1 "
                        + "and Composition data types"
                    )
                r = select(for_object._id, False, [[ref_objects, where_condition]], all_fields, variables)
                results |= r
        else:
            # swallow-deep
            if len(object_id) > 0 and object_id[0] == "$":
                # parameter
                try:
                    object_id = variables[object_id[1:]]
                except KeyError as e:
                    raise NameError('Undefined variable "%s"' % e.args[0])

            obj = db.get_item(object_id)
            if obj is not None and obj.isCollection:
                optimized = prepared["optimized"]
                select_top = prepared["select_top"]
                top_accumulative = prepared["top_accumulative"]

                # print(optimized)

                cp_optimized = copy.deepcopy(optimized)
                # create cursors
                for l in cp_optimized:
                    if l[0] is None:
                        l[0] = db._db.get_children(obj._id)
                    else:
                        # replace any given parameters
                        try:
                            for indexed_lookup in l[0]:
                                index_value = indexed_lookup[1]
                                if isinstance(index_value, (bytes, str)) and index_value[0] == "$":
                                    # equality cursor
                                    indexed_lookup[1] = variables[index_value[1:]]
                                elif isinstance(index_value, tuple):
                                    # range cursor
                                    for limit in index_value:
                                        if isinstance(limit, list) and isinstance(limit[0], str) and limit[0][0] == "$":
                                            limit[0] = variables[limit[0][1:]]
                        except KeyError as e:
                            raise NameError('Undefined variable "%s"' % e.args[0])

                        l[0] = db._db.query(l[0])
                        l[0].set_scope(obj._id)

                r = select(
                    obj._id,
                    deep,
                    cp_optimized,
                    all_fields,
                    variables,
                    top=select_top,
                    top_accumulative=top_accumulative,
                )

                # close cursors
                cp_optimized.reverse()
                [l[0].close() for l in cp_optimized]
                results |= r

                if select_top is not None and top_accumulative:
                    if len(results) >= select_top:
                        break

    results = results.to_list()

    if results:
        if group_by:
            if select_fields:
                # construct groups
                group_dict = {}
                igrpstart = len(select_fields) + len(order_by)
                igrpend = igrpstart + len(group_by)
                for rec in results:
                    group_value = tuple(rec[igrpstart:igrpend])
                    group_dict[group_value] = group_dict.setdefault(group_value, [])
                    group_dict[group_value].append(rec)
                groups = [tuple(g) for g in group_dict.values()]
            else:
                raise TypeError("GROUP BY clause is incompatible with SELECT *")
        else:
            groups = [results]

        results = []

        if any(aggregates) or group_by:
            for ind, group in enumerate(groups):
                group_sum = []
                for aggr_index, aggr_type in enumerate(aggregates):
                    if aggr_type is not None:
                        # aggregates exclude None values
                        group_sum.append(
                            compute_aggregate(aggr_type, [x[aggr_index] for x in group if x[aggr_index] is not None])
                        )
                groups[ind] = (tuple(group_sum),)

        for group in groups:
            results.extend(group)

        if order_by:
            # extract sort values
            istart = 1
            if select_fields:
                istart = len(select_fields)
            sortlist = tuple([x[istart : istart + len(order_by)] for x in results])
            results = sort_list(sortlist, results)
            # if it is descending reverse the result list
            if not sort_order:
                results.reverse()

    # remove aliases
    for alias in aliases:
        del variables[alias]

    if select_fields:
        schema = field_names
        # truncate to keep only select fields
        iend = len(select_fields)
        results = tuple([x[:iend] for x in results])
    else:
        schema = None
        results = tuple([x[:1][0] for x in results])

    # print(len(results))

    if select_range:
        results = results[slice(select_range[0] - 1, select_range[1])]

    results = ObjectSet(results)
    results.schema = schema
    return results
def __blank__(self):
    "Displays the desktop"
    context = HttpContext.current()
    oUser = context.user
    
    params = {
        'USER' : oUser.displayName.value,
        'AUTO_RUN' : '',
        'RUN_MAXIMIZED' : 0,
        'SETTINGS_DISABLED' : '',
        'LOGOFF_DISABLED' : ''
    }
    if hasattr(oUser, 'authenticate'):
        settings = oUser.settings
        params['AUTO_RUN'] = \
            settings.value.setdefault('AUTO_RUN', '')
        params['RUN_MAXIMIZED'] = \
            int(settings.value.setdefault('RUN_MAXIMIZED', False))
        taskbar_position = \
            settings.value.setdefault('TASK_BAR_POS', 'bottom')
    else:
        taskbar_position = 'bottom'
        params['SETTINGS_DISABLED'] = 'true'
        params['LOGOFF_DISABLED'] = 'true'
    
    params['REPOSITORY_DISABLED'] = 'true'
    params['PERSONAL_FOLDER'] = ''
    if hasattr(oUser, 'personalFolder'):
        params['REPOSITORY_DISABLED'] = 'false'
        params['PERSONAL_FOLDER'] = oUser.personalFolder.value
    
    # has the user access to recycle bin?
    rb_icon = ''
    rb = db.get_item('rb')
    if rb:
        rb_icon = '''
            <icon top="80" left="10" width="80" height="80"
                imgalign="top" ondblclick="generic.openContainer"
                img="desktop/images/trashcan_full.gif" color="white"
                caption="%s">
                    <prop name="folderID" value="rb"></prop>
            </icon>
        ''' % rb.displayName.value
    
    desktop_pane = DESKSTOP_PANE % (self.displayName.value, rb_icon)
    
    if taskbar_position == 'bottom':
        params['TOP'] = desktop_pane
        params['BOTTOM'] = ''
    else:
        params['TOP'] = ''
        params['BOTTOM'] = desktop_pane
    
    # get applications
    oCmd = OqlCommand()
    sOql = "select launchUrl,displayName,icon from 'apps' " + \
           "order by displayName asc"
    apps = oCmd.execute(sOql)
    sApps = ''
    if len(apps) > 0:
        for app in apps:
            sApps += '''<menuoption img="%s" caption="%s"
                onclick="generic.runApp">
                    <prop name="url" value="%s"></prop>
                </menuoption>''' % \
                (app['icon'], app['displayName'], app['launchUrl'])
        params['APPS'] = sApps
    else:
        params['APPS'] = '<menuoption caption="@@EMPTY@@"' + \
                         ' disabled="true"></menuoption>'

    return params
Exemplo n.º 29
0
def h_200(prepared, variables, for_object=None):
    select_fields = prepared['select_fields']
    field_names = prepared['field_names']
    all_fields = prepared['all_fields']
    select_from = prepared['select_from']
    select_range = prepared['select_range']
    where_condition = prepared['where_condition']
    aliases = prepared['aliases']
    order_by = prepared['order_by']
    sort_order = prepared['sort_order']
    group_by = prepared['group_by']

    variables = variables.copy()
    variables.update(aliases)

    aggregates = [x[2] for x in all_fields]

    #print order_by
    #print len(optimized)
    #print('opt: %s' % optimized)

    results = ObjectSet()
    for deep, object_id in select_from:
        if deep == 2:
            # this:attr
            if not for_object:
                raise TypeError(
                    'Inner scopes using "this:" are valid only in sub-queries')
            if hasattr(for_object, object_id):
                attr = getattr(for_object, object_id)
                if isinstance(attr, (datatypes.ReferenceN,
                                     datatypes.Composition)):
                    ref_objects = attr.get_items()
                elif isinstance(attr, datatypes.Reference1):
                    ref_objects = [attr.get_item()]
                else:
                    raise TypeError('Inner scopes using "this:" are ' +
                                    'valid only ReferenceN, Reference1 ' +
                                    'and Composition data types')
                r = select(for_object._id, False,
                           [[ref_objects, where_condition]],
                           all_fields, variables)
                results |= r
        else:
            # swallow-deep
            if len(object_id) > 0 and object_id[0] == '$':
                # parameter
                try:
                    object_id = variables[object_id[1:]]
                except KeyError as e:
                    raise NameError('Undefined variable "%s"' % e.args[0])

            obj = db.get_item(object_id)
            if obj is not None and obj.isCollection:
                optimized = prepared['optimized']
                select_top = prepared['select_top']
                top_accumulative = prepared['top_accumulative']

                #print(optimized)

                cp_optimized = copy.deepcopy(optimized)
                # create cursors
                for l in cp_optimized:
                    if l[0] is None:
                        l[0] = db._db.get_children(obj._id)
                    else:
                        # replace any given parameters
                        try:
                            for indexed_lookup in l[0]:
                                index_value = indexed_lookup[1]
                                if isinstance(index_value, (bytes, str)) \
                                        and index_value[0] == '$':
                                    # equality cursor
                                    indexed_lookup[1] = \
                                        variables[index_value[1:]]
                                elif isinstance(index_value, tuple):
                                    # range cursor
                                    for limit in index_value:
                                        if isinstance(limit, list) \
                                                and isinstance(limit[0], str) \
                                                and limit[0][0] == '$':
                                            limit[0] = variables[limit[0][1:]]
                        except KeyError as e:
                            raise NameError(
                                'Undefined variable "%s"' % e.args[0])

                        l[0] = db._db.query(l[0])
                        l[0].set_scope(obj._id)

                r = select(obj._id,
                           deep,
                           cp_optimized,
                           all_fields,
                           variables,
                           top=select_top,
                           top_accumulative=top_accumulative)

                # close cursors
                cp_optimized.reverse()
                [l[0].close() for l in cp_optimized]
                results |= r

                if select_top is not None and top_accumulative:
                    if len(results) >= select_top:
                        break

    results = results.to_list()

    if results:
        if group_by:
            if select_fields:
                #construct groups
                group_dict = {}
                igrpstart = len(select_fields) + len(order_by)
                igrpend = igrpstart + len(group_by)
                for rec in results:
                    group_value = tuple(rec[igrpstart:igrpend])
                    group_dict[group_value] = \
                        group_dict.setdefault(group_value, [])
                    group_dict[group_value].append(rec)
                groups = [tuple(g) for g in group_dict.values()]
            else:
                raise TypeError(
                    'GROUP BY clause is incompatible with SELECT *')
        else:
            groups = [results]

        results = []

        if any(aggregates) or group_by:
            for ind, group in enumerate(groups):
                group_sum = []
                for aggr_index, aggr_type in enumerate(aggregates):
                    if aggr_type is not None:
                        # aggregates exclude None values
                        group_sum.append(compute_aggregate(
                            aggr_type,
                            [x[aggr_index]
                             for x in group
                             if x[aggr_index] is not None]))
                groups[ind] = (tuple(group_sum),)

        for group in groups:
            results.extend(group)

        if order_by:
            # extract sort values
            istart = 1
            if select_fields:
                istart = len(select_fields)
            sortlist = tuple([x[istart:istart + len(order_by)]
                              for x in results])
            results = sort_list(sortlist, results)
            # if it is descending reverse the result list
            if not sort_order:
                results.reverse()

    # remove aliases
    for alias in aliases:
        del variables[alias]

    if select_fields:
        schema = field_names
        # truncate to keep only select fields
        iend = len(select_fields)
        results = tuple([x[:iend] for x in results])
    else:
        schema = None
        results = tuple([x[:1][0] for x in results])

    #print(len(results))

    if select_range:
        results = results[slice(select_range[0] - 1, select_range[1])]

    results = ObjectSet(results)
    results.schema = schema
    return results
 def _get_no_access_ids(attr, trans):
     ids = [id for id in attr.value
            if db.get_item(id, trans) == None]
     return ids
Exemplo n.º 31
0
 def get_items(self):
     items = [db.get_item(id) for id in self.value]
     return ObjectSet([item for item in items
                       if item is not None and
                          self.relAttr in item.__props__])
Exemplo n.º 32
0
 def get_items(self):
     items = [db.get_item(id) for id in self.value]
     return ObjectSet([
         item for item in items
         if item is not None and self.relAttr in item.__props__
     ])