Random Query Execution with SQLAlchemy on In-Memory Database

  • Share this:

Code introduction


The function uses SQLAlchemy to create a simple database model and executes a query with a randomly selected attribute and value. It first creates an in-memory SQLite database and a users table, then performs a query with a randomly selected attribute and value.


Technology Stack : SQLAlchemy, Python

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import random

def random_select_query():
    Base = declarative_base()
    
    class User(Base):
        __tablename__ = 'users'
        id = Column(Integer, primary_key=True)
        name = Column(String)
        age = Column(Integer)
    
    engine = create_engine('sqlite:///:memory:')
    Base.metadata.create_all(engine)
    
    Session = sessionmaker(bind=engine)
    session = Session()
    
    # Randomly select an attribute and a value to query
    attribute = random.choice(['name', 'age'])
    value = random.choice([20, 30, 40])
    
    # Perform the query
    query = session.query(User).filter(getattr(User, attribute) == value)
    
    results = query.all()
    
    # Close the session
    session.close()
    
    return results