Search code examples
python-3.xsqlalchemy

how to clone table by SQL alchemy


I have a table with no model in SQLAlchemy, for example, names in my database and I want to clone it with a new name names_clone. How can this be achieved in SQLAlchemy without using SQLAlchemy Models?

db_url = "some DB URL engine"
engine = create_engine(db_url)
meta = MetaData(bind=engine)
inspector = inspect(engine)
table = Table("names", meta, autoload=True)
# I want do some thing like blow
new_table = table.copy

Solution

  • I code like this and

    columns = []
    for column in table.columns:
        columns.append(Column(column.name, column.type, primary_key=column.primary_key,
                                  autoincrement=column.autoincrement))
    new_table = Table(
        new_name, meta
        , *columns
    )
    result = meta.create_all(engine, tables=[new_table])
    
    query = new_table \
        .insert() \
        .from_select(names=[column.name for column in new_table.columns],
                     # array of column names that your query returns
                     select=select([table]))
    
    result = connection.execute(query)