Skip to main content

SQLAlchemy and Alembic

 

SQLAlchemy and Alembic: Explained with Example

SQLAlchemy:

  • A powerful Python library for interacting with relational databases.
  • Provides an object-relational mapper (ORM) that lets you define your data model as Python classes and map them to tables in a database.
  • Simplifies writing SQL queries and manipulating data through its object-oriented interface.

Alembic:

  • A migration tool built on top of SQLAlchemy.
  • Allows you to track changes to your database schema over time and manage upgrades and downgrades.
  • Generates migration scripts as your data model evolves, providing version control for your database schema.

Example:

Let's consider a model that defines a User table with two attributes: id (primary key) and username.

Python code (SQLAlchemy):

Python
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

classUser(Base):
    __tablename__ = "users"id = Column(Integer, primary_key=True)
    username = Column(String(50), nullable=False)

engine = create_engine("sqlite:///database.db")
Base.metadata.create_all(engine)

# Creating new User objects and writing to the database
user1 = User(username="alice")
user2 = User(username="bob")

session = Session(engine)
session.add_all([user1, user2])
session.commit()

# Reading users from the database
users = session.query(User).all()
print(users)

Creating a Migration with Alembic:

  1. Initialize Alembic:
alembic init
  1. Generate a migration script for the initial schema:
alembic revision --autogenerate

This creates a migration script containing the necessary SQL statements to create the users table.

  1. Upgrade the database schema:
alembic upgrade

This executes the migration script and creates the users table in the database.

Adding a new attribute to the model:

We can add a new attribute email to the User model:

Python
class User(Base):
    # ... existing code
    email = Column(String(100))

Base.metadata.alter(engine)

This will alter the existing users table in the database and add the email column.

  1. Generate a new migration script:
alembic revision --autogenerate
  1. Upgrade the database schema:
alembic upgrade

Benefits of using SQLAlchemy and Alembic:

  • Code readability: Focuses on the data model structure rather than writing raw SQL queries.
  • Maintainability: Easier to evolve the database schema and track changes.
  • Version control: Migration scripts act as version control for the database schema.
  • Portability: Code can be ported to different databases with minimal changes.

Remember: This is a simplified example. For real-world scenarios, you can define much more complex models with relationships, constraints, and other features.

You can find more example in internet also can check my github repo here https://github.com/dhirajpatra

Comments

Popular posts from this blog

Financial Engineering

Financial Engineering: Key Concepts Financial engineering is a multidisciplinary field that combines financial theory, mathematics, and computer science to design and develop innovative financial products and solutions. Here's an in-depth look at the key concepts you mentioned: 1. Statistical Analysis Statistical analysis is a crucial component of financial engineering. It involves using statistical techniques to analyze and interpret financial data, such as: Hypothesis testing : to validate assumptions about financial data Regression analysis : to model relationships between variables Time series analysis : to forecast future values based on historical data Probability distributions : to model and analyze risk Statistical analysis helps financial engineers to identify trends, patterns, and correlations in financial data, which informs decision-making and risk management. 2. Machine Learning Machine learning is a subset of artificial intelligence that involves training algorithms t...

Wholesale Customer Solution with Magento Commerce

The client want to have a shop where regular customers to be able to see products with their retail price, while Wholesale partners to see the prices with ? discount. The extra condition: retail and wholesale prices hasn’t mathematical dependency. So, a product could be $100 for retail and $50 for whole sale and another one could be $60 retail and $50 wholesale. And of course retail users should not be able to see wholesale prices at all. Basically, I will explain what I did step-by-step, but in order to understand what I mean, you should be familiar with the basics of Magento. 1. Creating two magento websites, stores and views (Magento meaning of website of course) It’s done from from System->Manage Stores. The result is: Website | Store | View ———————————————— Retail->Retail->Default Wholesale->Wholesale->Default Both sites using the same category/product tree 2. Setting the price scope in System->Configuration->Catalog->Catalog->Price set drop-down to...

How to Prepare for AI Driven Career

  Introduction We are all living in our "ChatGPT moment" now. It happened when I asked ChatGPT to plan a 10-day holiday in rural India. Within seconds, I had a detailed list of activities and places to explore. The speed and usefulness of the response left me stunned, and I realized instantly that life would never be the same again. ChatGPT felt like a bombshell—years of hype about Artificial Intelligence had finally materialized into something tangible and accessible. Suddenly, AI wasn’t just theoretical; it was writing limericks, crafting decent marketing content, and even generating code. The world is still adjusting to this rapid shift. We’re in the middle of a technological revolution—one so fast and transformative that it’s hard to fully comprehend. This revolution brings both exciting opportunities and inevitable challenges. On the one hand, AI is enabling remarkable breakthroughs. It can detect anomalies in MRI scans that even seasoned doctors might miss. It can trans...