title: SqlAlchemy asyncio orm: How to query the database
body: <p>In SqlAlchemy async orm engine how do I query a table and get a value or all?</p>
  <p>I know from the non async methods that I can just do</p>
  <p><code>SESSION.query(TableClass).get(x)</code></p>
  <p>but trying this with the async methods it throws the next error:</p>
  <p><code>AttributeError: 'AsyncSession' object has no attribute 'query'.</code></p>
  <p>Here's my SESSION variable defined. The LOOP variable is just <code>asyncio.get_event_loop()</code> used to start async methods when my sql module is loaded and populate variables used as a cache to avoid caching the database every time I need somethin:</p>
  <pre><code>from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
  from sqlalchemy.ext.declarative import declarative_base
  from sqlalchemy.orm import sessionmaker, scoped_session
  
  from .. import CONFIG, LOOP
  
  def _build_async_db_uri(uri):
      if &quot;+asyncpg&quot; not in uri:
          return '+asyncpg:'.join(uri.split(&quot;:&quot;, 1))
      return uri
  
  async def start() -&gt; declarative_base:
      engine = create_async_engine(_build_async_db_uri(CONFIG.general.sqlalchemy_db_uri))
      async with engine.begin() as conn:
          BASE.metadata.bind = engine
          await conn.run_sync(BASE.metadata.create_all)
      return scoped_session(sessionmaker(bind=engine, autoflush=False, class_=AsyncSession))
  
  
  BASE = declarative_base()
  SESSION = LOOP.run_until_complete(start())
  </code></pre>
  <p>Here's an example of table and cache function:</p>
  <pre><code>class TableClass:
      __tablename__ = &quot;tableclass&quot;
      id = Column(Integer, primary_key = True)
      alias = Column(Integer)
  
  CACHE = {}
  async def _load_all():
      global CACHE
      try:
          curr = await SESSION.query(TableClass).all()
          CACHE = {i.id: i.alias for i in curr}
  
  LOOP.run_until_complete(_load_all())
  </code></pre>