def build_subquery_table(env, stats_table, cross_db_group_by, group_by, filters=None): """ Build a subquery for group_by fields that require groupings in mozsplice_campaigns """ # Note: we only support one cross-db group-by at the moment if (len(cross_db_group_by) > 1): raise InvalidRequestError(CROSS_DB_ERROR % ' and '.join(cross_db_group_by)) group_by_field = cross_db_group_by[0] grouped_tiles = get_tile_ids_by_group(group_by=group_by_field, filters=filters) if not grouped_tiles: return None # flatten grouped_tiles all_tiles = sum([group['tile_ids'] for group in grouped_tiles], []) case_table = case( map((lambda item: (stats_table.c.tile_id.in_(item['tile_ids']), item[ group_by_field])), grouped_tiles)) subquery = (env.db.session.query( case_table.label(group_by_field), *stats_table.c).filter( stats_table.c.tile_id.in_(all_tiles))).subquery() return subquery
def __getattr__(self, item): try: return self.__getitem__(item) except KeyError: raise InvalidRequestError( f" [EngineRegistryUsage] SQLAlchemy Bind does not exist: '{item}'" )
def recieve_message_init(target, args, kwargs): author, chat = kwargs['author'], kwargs['chat'] author = User.query.get(author.id) chat = Chat.query.get(chat.id) if author in chat.users: return kwargs else: raise InvalidRequestError("author must be in a chat")
def get_select_precolumns(self, select, **kwargs): # This logic was copied from the ``sqlalchemy-access`` dialect. s = 'DISTINCT ' if select._distinct else '' if select._limit: s += 'TOP {0} '.format(select._limit) if select._offset: raise InvalidRequestError( "Pervasive PSQL does not support limit with an offset") return s
def __init__(self, clsname, bases, attrs): for cls_ in bases: if cls_.__name__ == 'MaterializedView' and not hasattr( self, '__view__'): raise InvalidRequestError( "Class '{}' must specify a '__view__' attribute".format( self)) try: self.__table__, self._view_dependencies = getattr(self, '__view__') attrs['__table__'] = self.__table__ except AttributeError: pass except (TypeError, ValueError): raise InvalidRequestError( "__view__ is invalid, use 'create_materialized_view' helper function" ) super(_MaterializedViewMeta, self).__init__(clsname, bases, attrs) self._view_dependencies_handler = None self._track_dependencies()
def insert_adgroup(session, record): if not adgroup_exists(session, record["name"], record["type"], record["campaign_id"]): record = record.copy() categories = record.pop('categories', []) if record['type'] == "suggested" and not categories: raise InvalidRequestError( "Each suggested adgroup must have at least one category.") cats = [AdgroupCategory(category=category) for category in categories] adgroup = Adgroup(categories=cats, **record) session.add(adgroup) session.flush() new = row_to_dict(adgroup) # row_to_dict can't handle nested objects new['categories'] = categories return new else: raise InvalidRequestError("Adgroup already exists")
def insert_tile(session, record): if not tile_exists(session, record["title"], record["target_url"], record["image_uri"], record["enhanced_image_uri"], record["type"], record["adgroup_id"]): tile = Tile(**record) session.add(tile) session.flush() return row_to_dict(tile) else: raise InvalidRequestError("Tile already exists")
def recieve_chat_init(target, args, kwargs): chat_name = kwargs.get('name') chat = Chat.query.filter_by(name=chat_name).first() if chat: raise InvalidRequestError("Chat name must be an unique") users = kwargs['users'] for user in users: user = User.query.get(user.id) if not user: raise ArgumentError("User not found") return kwargs
def update_adgroup(session, adgroup_id, record): adgroup = session.query(Adgroup).get(adgroup_id) if adgroup is None: raise NoResultFound("No result found") if "paused" in record: adgroup.paused = record["paused"] is_unique_key_changed = False if "name" in record and adgroup.name != record["name"]: is_unique_key_changed = True adgroup.name = record["name"] if "type" in record and adgroup.type != record["type"]: is_unique_key_changed = True adgroup.type = record["type"] if is_unique_key_changed and adgroup_exists( session, adgroup.name, adgroup.type, adgroup.campaign_id): raise InvalidRequestError("Adgroup already exists") if "frequencey_cap_daily" in record: adgroup.frequency_cap_daily = record["frequency_cap_daily"] if "frequencey_cap_total" in record: adgroup.frequency_cap_total = record["frequency_cap_total"] session.flush() new = row_to_dict(adgroup) if "categories" in record: if adgroup.type == "suggested" and not record['categories']: raise InvalidRequestError( "Each suggested adgroup must have at least one category") for category in adgroup.categories: session.delete(category) for category in record['categories']: adgroup.categories.append(AdgroupCategory(category=category)) new['categories'] = record['categories'] return new
def test_dashboard_error(app, client, mocker): app.config['container'].repositories[ 'ExperimentRepository'].all.side_effect = InvalidRequestError() response = client.get('/') # Error assert 'href="/experiments/run/' not in response.data.decode( 'utf-8', errors='ignore') assert 'There seems to be an error with your database.' in response.data.decode( 'utf-8', errors='ignore') assert 'Please try to refresh your migrations and restart the webgui to resolve this problem.' in response.data.decode( 'utf-8', errors='ignore')
def find_user_by(self, **kwargs) -> User: """ Method Find user, takes in arbitrary keyword arguments, Returns the first row found in the users table as filtered by the method’s input arguments """ session = self._session try: find_user = session.query(User).filter_by(**kwargs).first() except TypeError: raise InvalidRequestError() if not find_user: raise NoResultFound() return find_user
def __get__(s, instance, owner): try: mapper = class_mapper(owner) if mapper: if not self._registry.has() or not self._registry( )._depth: raise InvalidRequestError( 'Cannot access %s.query outside transaction, use with session: ...' % owner.__name__) if query_cls: # custom query class return query_cls(mapper, session=self._registry()) else: # session's configured query class return self._registry().query(mapper) except UnmappedClassError: return None
def update_user(self, pk: int, attrs_and_fields: Dict, **kwargs) -> UserModel: with self.db_connect as db: try: user: UserModel = db.query(UserModel).filter_by(id=pk).first() for attr, value in attrs_and_fields.items(): setattr(user, attr, value) db.commit() except Exception: db.rollback() raise InvalidRequestError("Transaction was not complete") db.refresh(user) return user
def _guess_relationship(child, parent): """Given two mapped classes, return a wild guess at a relationship that leads from the child to the parent. The logic is the same as that used in Query.with_parent, albeit backwards. """ child_mapper = class_mapper(child) parent_mapper = class_mapper(parent) for prop in child_mapper.iterate_properties: if isinstance(prop, RelationshipProperty) and prop.mapper is parent_mapper: # Be sure to turn it back into an attribute return getattr(child, prop.key) raise InvalidRequestError( "Can't find a relationship from {0} to {1}".format( child.__name__, parent.__name__))
def test_patch_user_profile( # pylint: disable=too-many-arguments self, api, user1, user2, authenticated_user, mocker): # Given response = StartResponseMock() request = Request(create_environ(headers={'AUTHORIZATION': 'XXXX'})) # When result = api.patch_user_profile(user1.user_id, "newname", "newpassword", request, response, authenticated_user) # Then assert result == { "user_id": user1.user_id, "name": "newname", "email": "*****@*****.**" } # When result = api.patch_user_profile(-1, "newname", "newpassword", request, response, authenticated_user) # Then assert response.status == HTTP_404 assert result is None # When result = api.patch_user_profile(user2.user_id, "newname", "newpassword", request, response, authenticated_user) # Then assert response.status == HTTP_401 assert result == ("Authenticated user isn't allowed to update the" " profile for requested user") # When mocker.patch.object(api.session, 'commit') api.session.commit.side_effect = InvalidRequestError() result = api.patch_user_profile(user1.user_id, "newname", "newpassword", request, response, authenticated_user) # Then assert result == 'User profile not updated'
def where_kv_with_expansion(self, conditions): # conditions is a dict active_queries = [] for query in self.queries: try: table = query['table'] for key, val in conditions.items(): if key not in table.c: raise InvalidRequestError('key not present') if val == "" or val[0] != '@': query['rows'] = query['rows'].filter( table.c[key] == val) else: file_filter = val[1:] with open(file_filter, 'r') as fin: data = json.load(fin) vals = recursive_find(data, key) query['rows'] = query['rows'].filter( table.c[key].in_(vals)) active_queries.append(query) except InvalidRequestError: continue self.queries = active_queries return self
def map_to(self, attrname, tablename=None, selectable=None, schema=None, base=None, mapper_args=util.immutabledict()): """Configure a mapping to the given attrname. This is the "master" method that can be used to create any configuration. .. versionadded:: 0.6.6 :param attrname: String attribute name which will be established as an attribute on this :class:.`.SqlSoup` instance. :param base: a Python class which will be used as the base for the mapped class. If ``None``, the "base" argument specified by this :class:`.SqlSoup` instance's constructor will be used, which defaults to ``object``. :param mapper_args: Dictionary of arguments which will be passed directly to :func:`.orm.mapper`. :param tablename: String name of a :class:`.Table` to be reflected. If a :class:`.Table` is already available, use the ``selectable`` argument. This argument is mutually exclusive versus the ``selectable`` argument. :param selectable: a :class:`.Table`, :class:`.Join`, or :class:`.Select` object which will be mapped. This argument is mutually exclusive versus the ``tablename`` argument. :param schema: String schema name to use if the ``tablename`` argument is present. """ if attrname in self._cache: raise InvalidRequestError( "Attribute '%s' is already mapped to '%s'" % ( attrname, class_mapper(self._cache[attrname]).mapped_table )) if tablename is not None: if not isinstance(tablename, basestring): raise ArgumentError("'tablename' argument must be a string." ) if selectable is not None: raise ArgumentError("'tablename' and 'selectable' " "arguments are mutually exclusive") selectable = Table(tablename, self._metadata, autoload=True, autoload_with=self.bind, schema=schema or self.schema) elif schema: raise ArgumentError("'tablename' argument is required when " "using 'schema'.") elif selectable is not None: if not isinstance(selectable, expression.FromClause): raise ArgumentError("'selectable' argument must be a " "table, select, join, or other " "selectable construct.") else: raise ArgumentError("'tablename' or 'selectable' argument is " "required.") if not selectable.primary_key.columns: if tablename: raise PKNotFoundError( "table '%s' does not have a primary " "key defined" % tablename) else: raise PKNotFoundError( "selectable '%s' does not have a primary " "key defined" % selectable) mapped_cls = _class_for_table( self.session, self.engine, selectable, base or self.base, mapper_args ) self._cache[attrname] = mapped_cls return mapped_cls
def _ddl_error(cls): msg = 'SQLSoup can only modify mapped Tables (found: %s)' \ % cls._table.__class__.__name__ raise InvalidRequestError(msg)
def recieve_user_init(target, args, kwargs): username = kwargs.get('username') user = User.query.filter_by(username=username).first() if user: raise InvalidRequestError("Username must be an unique") return kwargs
def __getattr__(self, name): """Proxy all attribute access to current session.""" if not self._registry.has(): raise InvalidRequestError( 'No transaction is active, use "with session: ..."') return getattr(self._registry(), name)