Base query for a target.

        Args:
            session: database session to query in
163536
def _base_query(self, session):
        
        return session.query(ORMTargetMarker) \
            .filter(ORMTargetMarker.name == self.name) \
            .filter(ORMTargetMarker.params == self.params)
50608
def get_sessionmaker(sqlalchemy_url, engine=None):
    
    if engine is None:
        engine = create_engine(sqlalchemy_url)
    return sessionmaker(bind=engine)
1175677
def magic_session(db_session=None, url=None):
    

    if db_session is not None:
        yield db_session
    else:
        session = get_session(url, expire_on_commit=False)
        try:
            try:
                yield session
            finally:
                session.commit()
        finally:
            session.close()
1165900
def reflect(source, model, cache=None):
    ''''''
    if source is None:
        return None
    if cache and source in cache:
        return cache[source]
    db = object_session(source)
    ident = identity_key(instance=source)[1]
    assert ident is not None
    return db.query(model).get(ident)
293960
def search(session, query):
    
    flat_query = "".join(query.split())

    artists = session.query(Artist).filter(
            or_(Artist.name.ilike(f"%%{query}%%"),
                Artist.name.ilike(f"%%{flat_query}%%"))
               ).all()
    albums = session.query(Album).filter(
            Album.title.ilike(f"%%{query}%%")).all()
    tracks = session.query(Track).filter(
            Track.title.ilike(f"%%{query}%%")).all()

    return dict(artists=artists,
                albums=albums,
                tracks=tracks)
970532
def execute_query(cmd, client, application, analytics_query, start_time=None, end_time=None, offset='1h', resource_group_name=None):
    """"""
    from .vendored_sdks.applicationinsights.models import QueryBody
    targets = get_query_targets(cmd.cli_ctx, application, resource_group_name)
    return client.query.execute(targets[0], QueryBody(query=analytics_query, timespan=get_timespan(cmd.cli_ctx, start_time, end_time, offset), applications=targets[1:]))
569802
def QueryDatabases(self, query, options=None):
        
        if options is None:
            options = {}

        def fetch_fn(options):
            return self.__QueryFeed('/dbs',
                                    'dbs',
                                    '',
                                    lambda r: r['Databases'],
                                    lambda _, b: b,
                                    query,
                                    options), self.last_response_headers
        return query_iterable.QueryIterable(self, query, options, fetch_fn)
263487
def where(self, key, operator, value):
        
        self.__store_query({"key": key, "operator": operator, "value": value})
        return self
310798
def _query_db(self, mapping):
        
        model = self.models[mapping.get("table")]

        # Use primary key instead of the field mapped to SF Id
        fields = mapping.get("fields", {}).copy()
        if mapping["oid_as_pk"]:
            del fields["Id"]
        id_column = model.__table__.primary_key.columns.keys()[0]
        columns = [getattr(model, id_column)]

        for f in fields.values():
            columns.append(model.__table__.columns[f])
        lookups = mapping.get("lookups", {}).copy()
        for lookup in lookups.values():
            lookup["aliased_table"] = aliased(
                self.metadata.tables["{}_sf_ids".format(lookup["table"])]
            )
            columns.append(lookup["aliased_table"].columns.sf_id)

        query = self.session.query(*columns)
        if "record_type" in mapping and hasattr(model, "record_type"):
            query = query.filter(model.record_type == mapping["record_type"])
        if "filters" in mapping:
            filter_args = []
            for f in mapping["filters"]:
                filter_args.append(text(f))
            query = query.filter(*filter_args)
        for sf_field, lookup in lookups.items():
            # Outer join with lookup ids table:
            # returns main obj even if lookup is null
            key_field = get_lookup_key_field(lookup, sf_field)
            value_column = getattr(model, key_field)
            query = query.outerjoin(
                lookup["aliased_table"],
                lookup["aliased_table"].columns.id == value_column,
            )
            # Order by foreign key to minimize lock contention
            # by trying to keep lookup targets in the same batch
            lookup_column = getattr(model, key_field)
            query = query.order_by(lookup_column)
        self.logger.info(str(query))
        return query
1222351
def query(self, query_str, *query_args, **query_options):
        
        with self.connection(**query_options) as connection:
            query_options['connection'] = connection
            return self._query(query_str, query_args, **query_options)
1336054
def get_for_update(self, connection_name='DEFAULT', **kwargs):

        
        if not kwargs:
            raise InvalidQueryError(
                "Can not execute a query without parameters")

        obj = self.pool.connections[connection_name].session.query(
            self._model).with_for_update(
                nowait=True, of=self._model).filter_by(**kwargs).first()
        if not obj:
            raise NotFoundError('Object not found')
        return obj
763117
def get_session():
    
    if hasattr(g, 'session'):
        return g.session
    sess = create_session(bind=current_app.config['DATABASE_ENGINE'])
    try:
        g.session = sess
    except RuntimeError:
        pass
    return sess
889378
def create_database_session(engine):
    """"""

    try:
        Session = sessionmaker(bind=engine)
        return Session()
    except OperationalError as e:
        raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])
355926
def get_session(url):
    
    engine = create_engine(url)
    db_session = scoped_session(sessionmaker(engine))
    Base.metadata.create_all(engine)
    return db_session
894595
def query(cls, name=None, offset=None, limit=None, api=None):
        

        api = api or cls._API
        return super(Automation, cls)._query(
            url=cls._URL['query'],
            name=name,
            offset=offset,
            limit=limit,
            api=api,
        )
633009
def init_session(db_url=None, echo=False, engine=None, settings=None):
    
    if engine is None:
        engine = init_engine(db_url=db_url, echo=echo, settings=settings)
    return sessionmaker(bind=engine)
1164852
def dereference(self, session, ref, allow_none=False):
        
        ref = DBRef(id=ref, collection=self.type.type.get_collection_name(),
                    database=self.db)
        ref.type = self.type.type
        return session.dereference(ref, allow_none=allow_none)