Convert Figma logo to code with AI

sqlalchemy logoalembic

A database migrations tool for SQLAlchemy.

2,714
238
2,714
120

Top Related Projects

79,643

The Web framework for perfectionists with deadlines.

38,831

Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB

29,432

Feature-rich ORM for modern Node.js and TypeScript, it supports PostgreSQL (with JSON and JSONB support), MySQL, MariaDB, SQLite, MS SQL Server, Snowflake, Oracle DB (v6), DB2 and DB2 for IBM i.

19,158

A query builder for PostgreSQL, MySQL, CockroachDB, SQL Server, SQLite3 and Oracle, designed to be flexible, portable, and fun to use.

34,121

ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.

Quick Overview

Alembic is a database migration tool for SQLAlchemy, a popular SQL toolkit and Object-Relational Mapping (ORM) library for Python. It provides a way to manage and apply incremental, reversible changes to database schemas, allowing developers to version control their database structures alongside their application code.

Pros

  • Seamless integration with SQLAlchemy, leveraging its powerful ORM capabilities
  • Supports automatic generation of migration scripts based on detected schema changes
  • Provides a flexible and extensible system for writing custom migration operations
  • Offers both programmatic and command-line interfaces for managing migrations

Cons

  • Learning curve can be steep for developers new to SQLAlchemy or database migrations
  • Auto-generated migrations may sometimes require manual adjustments for complex schema changes
  • Limited support for certain database-specific features or optimizations
  • Can be overkill for small projects with simple database structures

Code Examples

  1. Creating a new migration:
from alembic import op
import sqlalchemy as sa

def upgrade():
    op.create_table(
        'users',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('name', sa.String(50), nullable=False),
        sa.Column('email', sa.String(120), nullable=False),
        sa.PrimaryKeyConstraint('id')
    )

def downgrade():
    op.drop_table('users')
  1. Adding a column to an existing table:
from alembic import op
import sqlalchemy as sa

def upgrade():
    op.add_column('users', sa.Column('age', sa.Integer()))

def downgrade():
    op.drop_column('users', 'age')
  1. Creating an index:
from alembic import op

def upgrade():
    op.create_index('idx_user_email', 'users', ['email'], unique=True)

def downgrade():
    op.drop_index('idx_user_email', 'users')

Getting Started

  1. Install Alembic:
pip install alembic
  1. Initialize Alembic in your project:
alembic init alembic
  1. Edit alembic.ini to set your database URL:
sqlalchemy.url = postgresql://user:password@localhost/dbname
  1. Create a migration:
alembic revision -m "Create users table"
  1. Edit the generated migration file in the alembic/versions/ directory.

  2. Apply the migration:

alembic upgrade head

Competitor Comparisons

79,643

The Web framework for perfectionists with deadlines.

Pros of Django

  • Full-featured web framework with built-in ORM, admin interface, and authentication
  • Batteries-included approach, providing a complete ecosystem for web development
  • Large and active community with extensive documentation and third-party packages

Cons of Django

  • Less flexible for database migrations compared to Alembic's fine-grained control
  • Steeper learning curve for developers new to the framework's conventions
  • Tightly coupled components may be overkill for smaller projects

Code Comparison

Django migration:

from django.db import migrations, models

class Migration(migrations.Migration):
    dependencies = [('myapp', '0001_initial')]
    operations = [
        migrations.AddField('MyModel', 'new_field', models.CharField(max_length=100)),
    ]

Alembic migration:

from alembic import op
import sqlalchemy as sa

def upgrade():
    op.add_column('my_model', sa.Column('new_field', sa.String(length=100)))

def downgrade():
    op.drop_column('my_model', 'new_field')

Django focuses on a declarative approach within its ORM ecosystem, while Alembic offers more granular control over database operations, allowing for complex migrations and greater flexibility across different database systems.

38,831

Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB

Pros of Prisma

  • Provides a type-safe database client with auto-generated queries
  • Offers a powerful schema migration system with automatic SQL generation
  • Supports multiple databases with a unified API

Cons of Prisma

  • Less flexible for complex queries compared to raw SQL or ORM-based solutions
  • Steeper learning curve for developers familiar with traditional ORMs
  • Limited support for certain advanced database features

Code Comparison

Prisma schema definition:

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
}

Alembic model definition:

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True)
    email = Column(String, unique=True)
    name = Column(String, nullable=True)

Prisma focuses on a declarative schema approach, while Alembic uses Python classes for model definitions. Prisma generates a type-safe client for database operations, whereas Alembic works alongside SQLAlchemy to provide ORM functionality. Both tools offer migration capabilities, but Prisma's approach is more automated, while Alembic provides finer control over migration scripts.

29,432

Feature-rich ORM for modern Node.js and TypeScript, it supports PostgreSQL (with JSON and JSONB support), MySQL, MariaDB, SQLite, MS SQL Server, Snowflake, Oracle DB (v6), DB2 and DB2 for IBM i.

Pros of Sequelize

  • More intuitive API for JavaScript developers
  • Built-in support for multiple databases (MySQL, PostgreSQL, SQLite, etc.)
  • Active community with frequent updates and extensive documentation

Cons of Sequelize

  • Limited support for complex database operations compared to Alembic
  • Performance can be slower for large-scale applications
  • Steeper learning curve for developers new to ORM concepts

Code Comparison

Sequelize model definition:

const User = sequelize.define('User', {
  username: DataTypes.STRING,
  email: DataTypes.STRING
});

Alembic model definition:

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    username = Column(String)
    email = Column(String)

Both Alembic and Sequelize are popular database migration and ORM tools, but they cater to different ecosystems. Alembic, part of the SQLAlchemy project, is Python-based and offers more flexibility for complex database operations. Sequelize, on the other hand, is JavaScript-focused and provides a more accessible API for Node.js developers.

Alembic excels in handling intricate database schemas and migrations, while Sequelize shines in its ease of use and built-in support for multiple databases. The choice between the two often depends on the programming language and specific project requirements.

19,158

A query builder for PostgreSQL, MySQL, CockroachDB, SQL Server, SQLite3 and Oracle, designed to be flexible, portable, and fun to use.

Pros of Knex

  • Simpler API and easier learning curve for JavaScript developers
  • Supports a wider range of databases out-of-the-box
  • More flexible query building with chainable methods

Cons of Knex

  • Less powerful schema management capabilities
  • Lacks some advanced ORM features present in SQLAlchemy
  • Smaller ecosystem and community compared to Alembic/SQLAlchemy

Code Comparison

Knex migration:

exports.up = function(knex) {
  return knex.schema.createTable('users', function(table) {
    table.increments('id');
    table.string('name');
  });
};

Alembic migration:

def upgrade():
    op.create_table('users',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('name', sa.String(), nullable=True),
        sa.PrimaryKeyConstraint('id')
    )

Both Knex and Alembic are popular database migration tools, but they cater to different ecosystems. Knex is primarily used in JavaScript/Node.js projects, while Alembic is part of the SQLAlchemy ecosystem in Python. Knex offers a more straightforward approach to query building and migrations, making it attractive for developers familiar with JavaScript. However, Alembic, being part of the SQLAlchemy suite, provides more robust schema management and integrates seamlessly with SQLAlchemy's ORM capabilities. The choice between the two often depends on the project's primary programming language and specific database requirements.

34,121

ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.

Pros of TypeORM

  • Supports both Active Record and Data Mapper patterns, offering more flexibility in ORM design
  • Native TypeScript support, providing better type safety and integration with TypeScript projects
  • Broader database support, including MongoDB for NoSQL options

Cons of TypeORM

  • Less mature and battle-tested compared to Alembic, which may lead to more edge cases or bugs
  • Smaller community and ecosystem, potentially resulting in fewer resources and third-party integrations

Code Comparison

TypeORM migration:

export class CreateUserTable1234567890123 implements MigrationInterface {
    public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.createTable(new Table({
            name: "user",
            columns: [
                { name: "id", type: "int", isPrimary: true },
                { name: "name", type: "varchar" }
            ]
        }), true);
    }
}

Alembic migration:

def upgrade():
    op.create_table(
        'user',
        sa.Column('id', sa.Integer(), primary_key=True),
        sa.Column('name', sa.String())
    )

Both TypeORM and Alembic provide powerful database migration tools, but they cater to different ecosystems and programming languages. TypeORM is more suited for TypeScript and JavaScript projects, while Alembic is primarily used with SQLAlchemy in Python environments.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Alembic is a database migrations tool written by the author of SQLAlchemy <http://www.sqlalchemy.org>_. A migrations tool offers the following functionality:

  • Can emit ALTER statements to a database in order to change the structure of tables and other constructs
  • Provides a system whereby "migration scripts" may be constructed; each script indicates a particular series of steps that can "upgrade" a target database to a new version, and optionally a series of steps that can "downgrade" similarly, doing the same steps in reverse.
  • Allows the scripts to execute in some sequential manner.

The goals of Alembic are:

  • Very open ended and transparent configuration and operation. A new Alembic environment is generated from a set of templates which is selected among a set of options when setup first occurs. The templates then deposit a series of scripts that define fully how database connectivity is established and how migration scripts are invoked; the migration scripts themselves are generated from a template within that series of scripts. The scripts can then be further customized to define exactly how databases will be interacted with and what structure new migration files should take.
  • Full support for transactional DDL. The default scripts ensure that all migrations occur within a transaction - for those databases which support this (Postgresql, Microsoft SQL Server), migrations can be tested with no need to manually undo changes upon failure.
  • Minimalist script construction. Basic operations like renaming tables/columns, adding/removing columns, changing column attributes can be performed through one line commands like alter_column(), rename_table(), add_constraint(). There is no need to recreate full SQLAlchemy Table structures for simple operations like these - the functions themselves generate minimalist schema structures behind the scenes to achieve the given DDL sequence.
  • "auto generation" of migrations. While real world migrations are far more complex than what can be automatically determined, Alembic can still eliminate the initial grunt work in generating new migration directives from an altered schema. The --autogenerate feature will inspect the current status of a database using SQLAlchemy's schema inspection capabilities, compare it to the current state of the database model as specified in Python, and generate a series of "candidate" migrations, rendering them into a new migration script as Python directives. The developer then edits the new file, adding additional directives and data migrations as needed, to produce a finished migration. Table and column level changes can be detected, with constraints and indexes to follow as well.
  • Full support for migrations generated as SQL scripts. Those of us who work in corporate environments know that direct access to DDL commands on a production database is a rare privilege, and DBAs want textual SQL scripts. Alembic's usage model and commands are oriented towards being able to run a series of migrations into a textual output file as easily as it runs them directly to a database. Care must be taken in this mode to not invoke other operations that rely upon in-memory SELECTs of rows - Alembic tries to provide helper constructs like bulk_insert() to help with data-oriented operations that are compatible with script-based DDL.
  • Non-linear, dependency-graph versioning. Scripts are given UUID identifiers similarly to a DVCS, and the linkage of one script to the next is achieved via human-editable markers within the scripts themselves. The structure of a set of migration files is considered as a directed-acyclic graph, meaning any migration file can be dependent on any other arbitrary set of migration files, or none at all. Through this open-ended system, migration files can be organized into branches, multiple roots, and mergepoints, without restriction. Commands are provided to produce new branches, roots, and merges of branches automatically.
  • Provide a library of ALTER constructs that can be used by any SQLAlchemy application. The DDL constructs build upon SQLAlchemy's own DDLElement base and can be used standalone by any application or script.
  • At long last, bring SQLite and its inability to ALTER things into the fold, but in such a way that SQLite's very special workflow needs are accommodated in an explicit way that makes the most of a bad situation, through the concept of a "batch" migration, where multiple changes to a table can be batched together to form a series of instructions for a single, subsequent "move-and-copy" workflow. You can even use "move-and-copy" workflow for other databases, if you want to recreate a table in the background on a busy system.

Documentation and status of Alembic is at https://alembic.sqlalchemy.org/

The SQLAlchemy Project

Alembic is part of the SQLAlchemy Project <https://www.sqlalchemy.org>_ and adheres to the same standards and conventions as the core project.

Development / Bug reporting / Pull requests


Please refer to the SQLAlchemy Community Guide <https://www.sqlalchemy.org/develop.html>_ for guidelines on coding and participating in this project.

Code of Conduct


Above all, SQLAlchemy places great emphasis on polite, thoughtful, and constructive communication between users and developers. Please see our current Code of Conduct at Code of Conduct <https://www.sqlalchemy.org/codeofconduct.html>_.

License

Alembic is distributed under the MIT license <https://opensource.org/licenses/MIT>_.