### Configure Flask-Alembic with Plain SQLAlchemy Engine and Metadata Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/databases.md This example demonstrates initializing Flask-Alembic with a manually created SQLAlchemy engine and metadata, useful when not using Flask extensions or for explicit control. ```python from flask_alembic import Alembic from sqlalchemy import create_engine from sqlalchemy.orm import DeclarativeBase engine = create_engine("sqlite:///default.sqlite") class Model(DeclarativeBase): pass alembic = Alembic(metadatas=Model.metadata, engines=engine) ``` -------------------------------- ### Flask CLI Commands for Database Migrations Source: https://github.com/pallets-eco/flask-alembic/blob/main/README.md Shows example commands for using Flask-Alembic via the Flask CLI. These commands facilitate common migration tasks such as generating new revisions, displaying help, and upgrading the database schema. ```shell $ flask db --help $ flask db revision "making changes" $ flask db upgrade ``` -------------------------------- ### Configure Flask-Alembic with Multiple Metadatas for a Single Database Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/databases.md This example shows how to initialize Flask-Alembic when a single database's models are split across multiple metadata objects, by passing a list of metadatas. ```python from flask_alembic import Alembic from sqlalchemy.orm import DeclarativeBase class DefaultBase(DeclarativeBase): pass class AuthBase(DeclarativeBase): pass alembic = Alembic(metadatas=[DefaultBase.metadata, AuthBase.metadata]) ``` -------------------------------- ### Describe Migration Operations with compare_metadata() Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/api.md The compare_metadata() function describes the operations that would be included in a new database revision. It is designed for single-database setups. For multi-database environments, a loop iterating through alembic.produce_migrations().upgrade_ops_list should be used to process each operation. ```python import alembic # For single database # revision_description = compare_metadata() # For multiple databases for ops in alembic.produce_migrations().upgrade_ops_list: name = ops.upgrade_token.removesuffix("_upgrades") diff = ops.as_diffs() print(f"Operations for {name}: {diff}") ``` -------------------------------- ### Access Alembic Internals Programmatically Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/use.md Provides examples of accessing lower-level Alembic functionalities from Python, such as retrieving revision information, comparing metadata, and applying operations directly. ```python # locate a revision by name alembic.script.get_revision("head") # could compare this to the "head" revision above to see if upgrades are needed alembic.context.get_current_revision() # probably don't want to do this outside a revision, but it'll work alembic.op.drop_column("my_table", "my_column") # see that the column you just dropped will be added back next revision alembic.compare_metadata() ``` -------------------------------- ### Configure Post-Processing Hooks in Flask-Alembic Source: https://context7.com/pallets-eco/flask-alembic/llms.txt Configures automatic code formatting and git integration for generated migration files using Alembic's post_write_hooks. This example integrates the 'ruff' formatter and 'git add' command to automatically stage newly created migration scripts, streamlining the development workflow. ```python from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_alembic import Alembic app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db' app.config['ALEMBIC'] = { 'script_location': 'migrations', 'post_write_hooks': { 'hooks': 'ruff, git', 'ruff.type': 'console_scripts', 'ruff.entrypoint': 'ruff', 'ruff.options': 'format REVISION_SCRIPT_FILENAME', 'git.type': 'exec', 'git.executable': 'git', 'git.options': 'add REVISION_SCRIPT_FILENAME' } } app.config['ALEMBIC_CONTEXT'] = { 'compare_type': True, 'compare_server_default': True, 'include_schemas': True } db = SQLAlchemy(app) alembic = Alembic(app) with app.app_context(): alembic.revision('add indexes') ``` -------------------------------- ### Configure Pre-commit Hook in Flask-Alembic Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/config.md This example demonstrates setting up 'pre-commit' as a post-write hook to automatically run configured pre-commit hooks on generated migration files. It specifies the type, entry point, and options to execute pre-commit on the revision file. ```python ALEMBIC = { "post_write_hooks": { "hooks": "pre-commit", "pre-commit.type": "console_scripts", "pre-commit.entrypoint": "pre-commit", "pre-commit.options": "run --files REVISION_SCRIPT_FILENAME", } } ``` -------------------------------- ### Plain SQLAlchemy Integration with Flask-Alembic Source: https://context7.com/pallets-eco/flask-alembic/llms.txt Integrate Flask-Alembic with plain SQLAlchemy, bypassing Flask-SQLAlchemy. This approach allows explicit definition of metadata and engines, providing flexibility for complex database setups or when not using Flask-SQLAlchemy. ```python from flask import Flask from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, Text from flask_alembic import Alembic app = Flask(__name__) # Create SQLAlchemy metadata and define schema metadata = MetaData() blog_posts = Table('blog_posts', metadata, Column('id', Integer, primary_key=True), Column('title', String(200), nullable=False), Column('body', Text), Column('author', String(100)) ) comments = Table('comments', metadata, Column('id', Integer, primary_key=True), Column('post_id', Integer, nullable=False), Column('text', Text), Column('author', String(100)) ) # Create engine engine = create_engine('postgresql://user:pass@localhost/mydb') # Initialize Flask-Alembic with explicit metadata and engine alembic = Alembic(app, metadatas=metadata, engines=engine) with app.app_context(): # All standard operations work the same alembic.revision('initial blog schema') alembic.upgrade() if alembic.needs_upgrade(): alembic.upgrade() ``` -------------------------------- ### Configure Version Locations for Separate Migration Paths Source: https://context7.com/pallets-eco/flask-alembic/llms.txt Configures distinct migration paths for different parts of the application, such as 'users' and 'products', allowing for independent management of their respective database schemas. This setup uses the 'ALEMBIC' configuration dictionary to specify multiple version locations. ```python from flask import Flask from flask_alembic import Alembic app = Flask(__name__) app.config['ALEMBIC'] = { 'version_locations': [ ('users', 'migrations/users'), ('products', 'migrations/products') ] } alembic = Alembic(app) with app.app_context(): alembic.revision('update schemas') alembic.upgrade() ``` -------------------------------- ### Log Revisions API Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/api.md Retrieves a list of revisions that will be applied in a specific order, optionally filtered by start and end revisions. ```APIDOC ## GET /log ### Description Get the list of revisions in the order they will run. ### Method GET ### Endpoint /log ### Parameters #### Query Parameters - **start** (string | Script | list[string] | list[Script] | tuple[string, ...] | tuple[Script, ...]) - Optional - Only get entries since this revision. - **end** (string | Script | list[string] | list[Script] | tuple[string, ...] | tuple[Script, ...]) - Optional - Only get entries until this revision. ### Response #### Success Response (200) - **revisions** (list[Script]) - A list of Script objects representing the revisions. #### Response Example { "revisions": [ { "revision": "abcdef123456", "down_revision": "fedcba654321", "message": "Initial migration" }, { "revision": "123456abcdef", "down_revision": "abcdef123456", "message": "Add user table" } ] } ``` -------------------------------- ### Check for Database Model Changes with needs_revision() Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/api.md The needs_revision() function checks if there are any detected changes between the database schema and the defined models. It returns a boolean value indicating whether changes are found. This function is available starting from version 3.2. ```python from flask_alembic import needs_revision if needs_revision(): print("Database changes detected.") else: print("Database is up to date.") ``` -------------------------------- ### Initialize Flask-Alembic with Flask-SQLAlchemy Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/use.md Demonstrates initializing Flask-Alembic with a Flask application and Flask-SQLAlchemy. It shows the common pattern of passing the app to Alembic either directly or via init_app(). ```python from flask_alembic import Alembic alembic = Alembic() alembic.init_app(app) # call in the app factory if you're using that pattern ``` -------------------------------- ### Initialize Flask-Alembic Extension Source: https://github.com/pallets-eco/flask-alembic/blob/main/README.md Demonstrates the basic initialization of the Flask-Alembic extension within a Flask application. This involves importing the Alembic class, creating an instance, and initializing it with the Flask app object. ```python from flask_alembic import Alembic # Intialize the extension alembic = Alembic() alembic.init_app(app) ``` -------------------------------- ### Manage Flask-Alembic Migrations via CLI Source: https://context7.com/pallets-eco/flask-alembic/llms.txt Demonstrates the command-line interface for Flask-Alembic, providing commands to manage database migrations. These commands are accessible under the 'flask db' namespace and include revision creation, status checks, history viewing, and applying upgrades/downgrades. ```bash # View available commands flask db --help # Create initial migration with auto-detection flask db revision "initial schema" # Check current database revision flask db current # View migration history flask db log # Check if database needs upgrade flask db current --check-heads # Exit code 0 if up-to-date, 1 if upgrade needed # Upgrade to latest revision flask db upgrade # Upgrade by relative count flask db upgrade +2 # Downgrade one revision flask db downgrade # Downgrade to specific revision flask db downgrade abc123 # View all head revisions flask db heads # Check if model changes exist flask db check # Output: "No changes detected." or "Changes detected." with exit code 1 ``` -------------------------------- ### Migration Execution Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/api.md Configure and run database migrations using a provided function. ```APIDOC ## run_migrations(fn, **kwargs) ### Description Configure an Alembic `MigrationContext` to run migrations for the given function. This takes the place of Alembic’s `env.py` file, specifically the `run_migrations_online` function. ### Parameters #### Parameters * **fn** (Callable[[list[str] | tuple[str, ...], MigrationContext, list[MigrationStep]], None]) - Use this function to control what migrations are run. * **kwargs** (Any) - Extra arguments passed to `upgrade` or `downgrade` in each revision. ### Return Type None ``` -------------------------------- ### Initialize Flask-Alembic Extension with Flask-SQLAlchemy Source: https://context7.com/pallets-eco/flask-alembic/llms.txt Basic initialization of the Flask-Alembic extension, demonstrating integration with Flask-SQLAlchemy. The extension automatically detects SQLAlchemy metadata and engines. Requires Flask and Flask-SQLAlchemy. ```python from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_alembic import Alembic # Create Flask app and database app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db' db = SQLAlchemy(app) # Define models class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) # Initialize Flask-Alembic alembic = Alembic(app) # Extension is now ready - migrations directory created automatically # CLI commands available: flask db --help ``` -------------------------------- ### Use Alembic Commands with Flask CLI Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/use.md Illustrates how to interact with Flask-Alembic using the Flask command-line interface. It covers basic commands like generating new revisions and applying upgrades. ```text $ flask db --help $ flask db revision "made changes" $ flask db upgrade ``` -------------------------------- ### Script Directory Management Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/api.md Utilities for creating and managing Alembic script directories. ```APIDOC ## mkdir() ### Description Create the script directory and template. Alembic’s `generic` template is used if a single database is configured. The `multidb` template if multiple databases are configured. ### Return Type None ``` -------------------------------- ### Programmatic Database Migration Operations in Python Source: https://github.com/pallets-eco/flask-alembic/blob/main/README.md Illustrates how to access and utilize Flask-Alembic's migration functionality directly within Python code, using the application context. This allows for automated migration tasks and access to Alembic's internal environment. ```python with app.app_context(): # Auto-generate a migration alembic.revision('making changes') # Upgrade the database alembic.upgrade() # Access the internals environment_context = alembic.env ``` -------------------------------- ### Configure Flask-Alembic for Multiple Databases Source: https://context7.com/pallets-eco/flask-alembic/llms.txt Demonstrates how to configure Flask-Alembic to manage migrations for multiple databases simultaneously. This is achieved by providing separate SQLAlchemy MetaData objects and engines for each database, utilizing Alembic's multidb template capabilities. Requires Flask, SQLAlchemy, and Flask-Alembic. ```python from flask import Flask from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String from flask_alembic import Alembic app = Flask(__name__) # Create separate metadata for each database users_metadata = MetaData() products_metadata = MetaData() # Define tables users_table = Table('users', users_metadata, Column('id', Integer, primary_key=True), Column('name', String(50)) ) products_table = Table('products', products_metadata, Column('id', Integer, primary_key=True), Column('name', String(100)) ) # Create engines users_engine = create_engine('sqlite:///users.db') products_engine = create_engine('sqlite:///products.db') # Initialize with multiple databases alembic = Alembic( app, metadatas={'users': users_metadata, 'products': products_metadata}, engines={'users': users_engine, 'products': products_engine} ) ``` -------------------------------- ### Programmatically Apply Alembic Upgrades Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/use.md Shows how to apply all available database migrations using the `alembic.upgrade()` method in Python. This function mirrors the behavior of the `flask db upgrade` command. ```python # run all available upgrades # same as `flask db upgrade` alembic.upgrade() ``` -------------------------------- ### Flask-Alembic Alembic Class Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/api.md Documentation for the main Alembic class provided by Flask-Alembic, including its constructor and key methods/properties. ```APIDOC ## Class flask_alembic.Alembic ### Description Provides an Alembic environment and migration API. Can be instantiated with an app instance or initialized later using `init_app()`. ### Parameters #### Constructor Parameters - **app** (Flask | None) - The Flask app instance to register the extension with. If None, `init_app()` must be called later. - **run_mkdir** (bool) - Whether to run `mkdir()` during `init_app`. (Deprecated in v3.2) - **command_name** (str) - The name to register the Click command with during `init_app`. Defaults to 'db'. (Deprecated in v3.2) - **metadatas** (sa.MetaData | list[sa.MetaData] | dict[str, sa.MetaData | list[sa.MetaData]] | None) - Metadata objects to inspect for migrations. Can be a single object, a list, or a dictionary mapping keys to metadata objects. - **engines** (sa.Engine | dict[str, sa.Engine] | None) - Database engines to perform migrations on. Must correspond to keys in `metadatas`. Can be a single engine or a dictionary mapping keys to engines. ### Methods #### init_app(app) ##### Description Registers the Flask-Alembic extension with a Flask application instance. ##### Parameters - **app** (Flask) - The Flask application instance. ##### Return Type None #### rev_id() ##### Description Generates a unique ID for a revision. By default, uses the current UTC timestamp. Can be overridden. ##### Return Type str ### Properties #### config ##### Description Returns the Alembic `Config` object for the current app. ##### Return Type Config #### script_directory ##### Description Returns the Alembic `ScriptDirectory` object for the current app. ##### Return Type ScriptDirectory #### environment_context ##### Description Returns the Alembic `EnvironmentContext` object for the current app. ##### Return Type EnvironmentContext #### migration_contexts ##### Description Returns a dictionary mapping database keys to their respective Alembic `MigrationContext` objects. Connections are closed when the app context ends. ##### Return Type dict[str, MigrationContext] #### migration_context ##### Description Returns the Alembic `MigrationContext` for the default database key. If multiple databases are configured, this is the context for the "default" key. The connection is closed when the app context ends. ##### Return Type MigrationContext ``` -------------------------------- ### Configure Flask-Alembic with SQLAlchemy Metadata Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/databases.md This snippet shows how to initialize Flask-Alembic when using Flask-SQLAlchemy-Lite, passing the metadata from a DeclarativeBase model. ```python from flask_alembic import Alembic from sqlalchemy.orm import DeclarativeBase class Model(DeclarativeBase): pass alembic = Alembic(metadatas=Model.metadata) ``` -------------------------------- ### Configure Flask-Alembic for Multiple Databases Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/databases.md This snippet illustrates setting up Flask-Alembic to manage migrations across multiple databases by providing dictionaries for metadatas and configuring SQLALCHEMY_ENGINES. It uses the 'multidb' template. ```python from flask import Flask from flask_alembic import Alembic from flask_sqlalchemy_lite import SQLAlchemy from sqlalchemy.orm import DeclarativeBase class DefaultBase(DeclarativeBase): pass class AuthBase(DeclarativeBase): pass db = SQLAlchemy() alembic = Alembic( metadatas={ "default": DefaultBase.metadata, "auth": AuthBase.metadata, }, ) app = Flask(__name__) app.config["SQLALCHEMY_ENGINES"] = { "default": "sqlite:///default.sqlite", "auth": "postgresql:///app-auth", } db.init_app(app) alembic.init_app(app) ``` -------------------------------- ### Execute Alembic Commands within App Context Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/use.md Illustrates the necessity of an application context when running Flask-Alembic commands programmatically outside of a request context. It shows how to manually establish an app context. ```python with app.app_context(): alembic.upgrade() ``` -------------------------------- ### Manage Independent Migration Branches with Flask-Alembic Source: https://context7.com/pallets-eco/flask-alembic/llms.txt Demonstrates managing independent migration branches for parallel development using Flask-Alembic. This allows for separate migration paths, like 'feature_auth' and 'feature_reporting', enabling independent versioning and controlled merging of changes. It covers creating revisions on specific branches, viewing branches, and merging them. ```python from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_alembic import Alembic app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db' app.config['ALEMBIC'] = { 'version_locations': [ ('feature_auth', 'migrations/feature_auth'), ('feature_reporting', 'migrations/feature_reporting') ] } db = SQLAlchemy(app) alembic = Alembic(app) with app.app_context(): alembic.revision( 'add user authentication', branch='feature_auth', parent='feature_auth@base' ) alembic.revision( 'add password reset', branch='feature_auth', parent='feature_auth@head' ) alembic.revision( 'add analytics tables', branch='feature_reporting', parent='feature_reporting@base' ) branches = alembic.branches() for branch in branches: print(f"Branch point: {branch.revision}") alembic.merge( revisions='heads', message='merge feature branches', label='merged' ) ``` -------------------------------- ### Create Empty Migrations with Flask-Alembic Source: https://context7.com/pallets-eco/flask-alembic/llms.txt Manually create empty migration files using Flask-Alembic, ideal for data migrations or custom operations without auto-detection. This method supports specifying revision messages, parent revisions, dependencies, and labels for better organization and tracking. ```python from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_alembic import Alembic app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db' db = SQLAlchemy(app) alembic = Alembic(app) with app.app_context(): # Create empty migration for manual editing revisions = alembic.revision( 'populate default categories', empty=True ) print(f"Created empty migration: {revisions[0].module_path}") print("Edit the file to add custom upgrade/downgrade logic") # Create migration with specific parent alembic.revision( 'fix data inconsistencies', empty=True, parent='abc123', # specific revision ID splice=True # allow non-head parent ) # Create migration with dependencies alembic.revision( 'add computed columns', empty=True, depend='def456', # depends on another revision label='data_migration' # add label for tracking ) ``` -------------------------------- ### Upgrade Database API Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/api.md Applies database migrations to upgrade the database to a specified target revision. ```APIDOC ## POST /upgrade ### Description Run migrations to upgrade database. ### Method POST ### Endpoint /upgrade ### Parameters #### Request Body - **target** (integer | string | Script) - Required - Revision to go up to. ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example { "message": "Database upgraded successfully." } ``` -------------------------------- ### Configure Git Add Hook in Flask-Alembic Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/config.md This configuration adds a 'git add' command as a post-write hook, ensuring that generated migration files are staged after other hooks complete. It defines the hook type as 'exec', the executable as 'git', and the options to add the revision file to staging. ```python ALEMBIC = { "post_write_hooks": { "hooks": "pre-commit, git", "pre-commit.type": "console_scripts", "pre-commit.entrypoint": "pre-commit", "pre-commit.options": "run --files REVISION_SCRIPT_FILENAME", "git.type": "exec", "git.executable": "git", "git.options": "add REVISION_SCRIPT_FILENAME", } } ``` -------------------------------- ### Configure Black Formatter Hook in Flask-Alembic Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/config.md This snippet shows how to configure the 'black' formatter as a post-write hook for Alembic migration files. It specifies the hook type as 'console_scripts' and the entry point for executing black. ```python ALEMBIC = { "post_write_hooks": { "hooks": "black", "black.type": "console_scripts", "black.entrypoint": "black", } } ``` -------------------------------- ### Alembic Operations Context Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/api.md Access to the Alembic Operations context for configured databases. ```APIDOC ## Properties ### ops * **Type**: `dict[str, Operations]` * **Description**: Get the Alembic `Operations` context for each configured database key for the current app. ### op * **Type**: `Operations` * **Description**: Get the Alembic `Operations` context for the current app. If multiple databases are configured, this is the context for the `"default"` key. ``` -------------------------------- ### Downgrade Database API Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/api.md Applies database migrations to downgrade the database to a specified target revision. ```APIDOC ## POST /downgrade ### Description Run migrations to downgrade database. ### Method POST ### Endpoint /downgrade ### Parameters #### Request Body - **target** (integer | string | Script) - Required - Revision to go down to. Defaults to -1 (previous revision). ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example { "message": "Database downgraded successfully." } ``` -------------------------------- ### Revision Information Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/api.md Retrieve information about current and available database revisions. ```APIDOC ## current() ### Description Get the list of current revisions. ### Return Type tuple[Script, ...] ## needs_upgrade() ### Description Check whether the current revisions are the head revisions. ### Returns `True` if the database is not at all head revisions, `False` otherwise. ### Return Type bool ## heads(resolve_dependencies=False) ### Description Get the list of revisions that have no child revisions. ### Parameters #### Path Parameters * **resolve_dependencies** (bool) - Optional - Treat dependencies as down revisions. ### Return Type tuple[Script, ...] ## branches() ### Description Get the list of revisions that have more than one next revision. ### Return Type list[Script] ``` -------------------------------- ### Access Alembic Internals with Flask-Alembic Source: https://context7.com/pallets-eco/flask-alembic/llms.txt Directly access underlying Alembic objects like configuration, script directory, environment context, migration context, and operations for advanced use cases. This allows for custom migration logic and direct schema manipulation within Flask applications. ```python from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_alembic import Alembic app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db' db = SQLAlchemy(app) alembic = Alembic(app) with app.app_context(): # Access Alembic config config = alembic.config script_location = config.get_main_option('script_location') # Access script directory script_dir = alembic.script_directory revision_map = script_dir.revision_map # Access environment context env = alembic.environment_context # Access migration context migration_ctx = alembic.migration_context current_rev = migration_ctx.get_current_revision() # Access operations object for direct schema operations with alembic.migration_context.begin_transaction(): op = alembic.op op.create_table( 'temp_table', db.Column('id', db.Integer, primary_key=True) ) op.add_column('users', db.Column('active', db.Boolean)) ``` -------------------------------- ### Produce Migrations API Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/api.md This endpoint generates the MigrationScript object that would be used to create a new revision, without actually creating the revision itself. ```APIDOC ## POST /produce_migrations ### Description Generate the `MigrationScript` object that would generate a new revision. ### Method POST ### Endpoint /produce_migrations ### Parameters No parameters required for this endpoint. ### Response #### Success Response (200) - **migration_script** (MigrationScript) - The generated MigrationScript object. #### Response Example ```json { "migration_script": { "script": "path/to/migration/script.py" } } ``` ``` -------------------------------- ### Metadata Comparison Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/api.md Describes the operations that would be present in a new database revision. This function is intended for single database comparisons. ```APIDOC ## compare_metadata() ### Description Describe the operations that would be present in a new revision. This only supports a single database. ### Method N/A (This is a function, not an HTTP endpoint) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response - **list** - A list containing tuples, where each tuple describes migration operations. The structure is list[tuple[Any, ...]]. #### Response Example ```json { "operations": [ ["create_table", {"name": "users", "columns": [["id", "Integer", {"primary_key": true}], ["name", "String"]]}], ["add_column", "users", "email", "String", {}] ] } ``` ``` -------------------------------- ### Configure Ruff Formatter Hook in Flask-Alembic Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/config.md This configuration enables the 'ruff' formatter as a post-write hook for Alembic revisions. It defines Ruff's type, entry point, and the command-line options to format the generated revision script. ```python ALEMBIC = { "post_write_hooks": { "hooks": "ruff", "ruff.type": "console_scripts", "ruff.entrypoint": "ruff", "ruff.options": "format REVISION_SCRIPT_FILENAME", } } ``` -------------------------------- ### Generate Alembic Revisions with Named Branches (Shell) Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/branches.md These shell commands demonstrate how to use Flask-Alembic's simplified 'revision' command to create new database migration scripts within named branches. It shows the Flask-Alembic command and its equivalent, more verbose Alembic commands for both new and existing branches. The '--branch' option automatically handles the base revision, label, and path. ```shell $ flask db revision --branch users "create user model" # equivalent to (if branch is new) $ alembic revision --autogenerate --head base --branch-label users --version-path users/migrations -m "create user model" # or (if branch exists) $ alembic revision --autogenerate --head users@head -m "create user model" ``` -------------------------------- ### Programmatically Generate Alembic Revision Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/use.md Demonstrates how to generate a new Alembic revision using the `alembic.revision()` method within Python code. This is equivalent to the `flask db revision` command. ```python # generate a new revision # same as `flask db revision "made changes"` alembic.revision("made changes") ``` -------------------------------- ### Create Revision API Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/api.md This endpoint is used to create new database revisions. It can auto-generate operations by comparing models and the database, or be configured to create empty revisions. ```APIDOC ## POST /revision ### Description Create a new revision. By default, auto-generate operations by comparing models and database. ### Method POST ### Endpoint /revision ### Parameters #### Request Body - **message** (string) - Required - Description of revision. - **empty** (boolean) - Optional - Don't auto-generate operations. Defaults to False. - **branch** (string) - Optional - Use this independent branch name. Defaults to 'default'. - **parent** (string | list[string] | tuple[string, ...]) - Optional - Parent revision(s) of this revision. Defaults to 'head'. - **splice** (boolean) - Optional - Allow non-head parent revision. Defaults to False. - **depend** (string | list[string] | tuple[string, ...]) - Optional - Revision(s) this revision depends on. - **label** (string | list[string]) - Optional - Label(s) to apply to this revision. - **path** (string) - Optional - Where to store this revision. ### Response #### Success Response (200) - **revisions** (list[Script]) - A list of new revision objects created. #### Response Example ```json { "revisions": [ { "id": "a1b2c3d4e5f6", "message": "Initial migration" } ] } ``` ``` -------------------------------- ### Detect Model Changes Programmatically with Flask-Alembic Source: https://context7.com/pallets-eco/flask-alembic/llms.txt Enables programmatic detection of schema changes without automatically creating migration files, useful for CI/CD pipelines and pre-commit hooks. It checks if a migration is needed using `needs_revision()`, provides a detailed diff of changes using `compare_metadata()`, and can generate migration script objects using `produce_migrations()`. ```python from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_alembic import Alembic app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db db = SQLAlchemy(app) alembic = Alembic(app) class Product(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100)) price = db.Column(db.Numeric(10, 2)) with app.app_context(): if alembic.needs_revision(): print("Model changes detected - migration required") diff = alembic.compare_metadata() for item in diff: print(f"Change type: {item[0]}") print(f"Details: {item}") script = alembic.produce_migrations() print(f"Upgrade operations: {script.upgrade_ops}") print(f"Downgrade operations: {script.downgrade_ops}") else: print("No changes detected - database is synchronized") ``` -------------------------------- ### Configure Alembic Version Locations for Named Branches (Python) Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/branches.md This Python code configures Alembic's version locations to support independent named branches. It allows specifying directories for migration scripts, including tuple pairs for branch-specific locations. This configuration simplifies the management of migrations across different parts of an application or extensions. ```python ALEMBIC = { "version_locations": [ # not a branch, just another search location "other_migrations", # posts branch migrations will be placed here ("posts", "/path/to/posts_extension/migrations"), # relative paths are relative to the application root ("users", "users/migrations"), ], } ``` -------------------------------- ### Database Revision Check Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/api.md Checks if there are any detected changes between the database schema and the defined models. ```APIDOC ## needs_revision() ### Description Checks if any changes between the database and models are detected. ### Method N/A (This is a function, not an HTTP endpoint) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response - **bool** - True if changes are detected, False otherwise. #### Response Example ```json { "result": true } ``` ``` -------------------------------- ### Stamp Revision API Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/api.md Sets the current database revision without executing any migration scripts. ```APIDOC ## POST /stamp ### Description Set the current database revision without running migrations. ### Method POST ### Endpoint /stamp ### Parameters #### Request Body - **target** (string | Script | list[string] | list[Script] | tuple[string, ...] | tuple[Script, ...]) - Required - Revision to set to. ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example { "message": "Database revision stamped successfully." } ``` -------------------------------- ### Merge Revisions API Source: https://github.com/pallets-eco/flask-alembic/blob/main/docs/api.md This endpoint allows for the creation of merge revisions, combining specified revision histories into a new, unified revision. ```APIDOC ## POST /merge ### Description Create a merge revision. ### Method POST ### Endpoint /merge ### Parameters #### Request Body - **revisions** (string | list[string] | tuple[string, ...]) - Required - Revisions to merge. Defaults to 'heads'. - **message** (string) - Optional - Description of merge, will default to the revisions parameter. - **label** (string | list[string]) - Optional - Label(s) to apply to this revision. ### Response #### Success Response (200) - **revision** (Script) - The newly created merge revision object. #### Response Example ```json { "revision": { "id": "f6e5d4c3b2a1", "message": "Merge branch 'feature' into main" } } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.