Creating Random Person Table with Dagster and SQLAlchemy

  • Share this:

Code introduction


This function uses the Dagster library and SQLAlchemy to create an in-memory SQLite database and generates a random table of people with names and ages.


Technology Stack : Dagster, SQLAlchemy

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import random
from dagster import op
from sqlalchemy import create_engine, Table, Column, Integer, String
from sqlalchemy.orm import sessionmaker

def random_table_creation():
    # This function creates a random table in an SQLite database using SQLAlchemy
    engine = create_engine('sqlite:///:memory:')
    Table(
        'random_table',
        engine,
        Column('id', Integer, primary_key=True),
        Column('name', String),
        Column('age', Integer)
    ).create()
    Session = sessionmaker(bind=engine)
    session = Session()
    session.add_all([
        {'name': f'Person_{i}', 'age': random.randint(18, 70) for i in range(1, 11)}
    ])
    session.commit()
    session.close()