[PYTHON] How to Alter with SQLAlchemy?

I found out how to do ** Alter ** with ** SQLAlchemy **, so I'd like to write it as a reminder.

But unfortunately SQLAlchemy doesn't seem to support any special features for running Alter.

In general, change the schema using migration tools such as Alembic and SQLAlchemy-Migrate. To do.

Also, if you really want to change the schema dynamically, Connection.execute () or Use DDL.

Official Documents> Altering Schemas through Migrations http://docs.sqlalchemy.org/en/latest/core/metadata.html#altering-schemas-through-migrations

Operating environment

Sample code

Sample code to add a new column "kana" to the table.

sqlalchemy_alter.py


# -*- coding:utf-8 -*-
import sqlalchemy
import sqlalchemy.ext.declarative

Base = sqlalchemy.ext.declarative.declarative_base()

class Student(Base):
    __tablename__ = 'students'
    id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
    name = sqlalchemy.Column(sqlalchemy.String(20))

    @staticmethod
    def add_column(engine, column):
        column_name = column.compile(dialect=engine.dialect)
        column_type = column.type.compile(engine.dialect)
        engine.execute('ALTER TABLE %s ADD COLUMN %s %s' % (Student.__tablename__, column_name, column_type))

def main():
    url = 'mysql+pymysql://root:@localhost/test_db?charset=utf8'

    engine = sqlalchemy.create_engine(url, echo=True)

    #Drop the table
    Base.metadata.drop_all(engine)

    #Create table
    Base.metadata.create_all(engine)

    #Add column to table
    column = sqlalchemy.Column('kana', sqlalchemy.String(40), primary_key=False)
    Student.add_column(engine, column)

if __name__ == '__main__':
    main()

Recommended Posts

How to Alter with SQLAlchemy?
How to update with SQLAlchemy?
How to Delete with SQLAlchemy?
How to INNER JOIN with SQLAlchemy
How to get parent id with sqlalchemy
How to use SQLAlchemy / Connect with aiomysql
Introduction to RDB with sqlalchemy Ⅰ
How to cast with Theano
How to separate strings with','
How to RDP with Fedora31
How to convert a class object to a dictionary with SQLAlchemy
How to get more than 1000 data with SQLAlchemy + MySQLdb
How to cancel RT with tweepy
How to handle session in SQLAlchemy
Python: How to use async with
Connect to multiple databases with SQLAlchemy
How to use virtualenv with PowerShell
How to deal with imbalanced data
How to install python-pip with ubuntu20.04LTS
How to deal with imbalanced data
Introduction to RDB with sqlalchemy II
How to get started with Python
How to deal with DistributionNotFound errors
How to get started with Django
How to Data Augmentation with PyTorch
How to calculate date with python
How to install mysql-connector with pip3
How to install Anaconda with pyenv
How to authenticate with Django Part 2
How to authenticate with Django Part 3
[Blender] How to set shape_key with script
How to title multiple figures with matplotlib
How to add a package with PyCharm
How to install DLIB with 2020 / CUDA enabled
How to use ManyToManyField with Django's Admin
How to use OpenVPN with Ubuntu 18.04.3 LTS
How to use Cmder with PyCharm (Windows)
How to prevent package updates with apt
How to work with BigQuery in Python
How to use Ass / Alembic with HtoA
How to deal with enum compatibility errors
How to do portmanteau test with python
How to search Google Drive with Google Colaboratory
How to download youtube videos with youtube-dl
How to use jupyter notebook with ABCI
How to power off Linux with Ultra96-V2
"How to pass PATH" to learn with homebrew
How to scrape websites created with SPA
How to use CUT command (with sample)
How to enter Japanese with Python curses
[Python] How to deal with module errors
How to install zsh (with .zshrc customization)
How to read problem data with paiza
How to get started with laravel (Linux)
How to group volumes together with LVM
How to install python3 with docker centos
How to use JDBC driver with Redash
How to selectively delete past tweets with Tweepy
How to upload with Heroku, Flask, Python, Git (4)
How to deal with memory leaks in matplotlib.pyplot
How to create sample CSV data with hypothesis