def copy_table(tableInstance, new_table_name, debug=None, overwrite=False): debug_level = get_table_debug_level(tableInstance, debug) engine = tableInstance.session.bind.engine tableObj = tableInstance.model.__table__ metadata = MetaData(bind=engine) table_name = tableInstance.model.__tablename__ table_rows = tableInstance.rowCount() physical_table = Table(table_name, metadata, autoload=True) physical_table.__tablename__ = table_name columns = [c.copy() for c in physical_table.columns] #temp_schema={} # PHYSICAL_TABLE_TABLE = db_table_class(physical_table, temp_schema, engine, tableInstance.session, debug_level - 1) # query_rows1 = PHYSICAL_TABLE_TABLE.rowCount() query_rows1 = engine.execute(f"select count(*) from {table_name}").scalar() # m = MetaData() # m.reflect(engine) # for table in m.tables.values(): # print(table.name) # # for column in table.c: # # print(column.name) if not overwrite: tables_list = get_tables_directory(engine) xnew_table_name = new_table_name ix = 0 while ix <= 99: ix = ix + 1 if xnew_table_name in tables_list: xnew_table_name = new_table_name + '_' + str(ix) else: break new_table_name = xnew_table_name new_table = Table(new_table_name, metadata, *columns) new_table.drop(engine, checkfirst=True) new_table.create(engine, checkfirst=True) new_table = Table(new_table_name, metadata, autoload=True) columns = [c.copy() for c in new_table.columns] # temp_schema={} # NEW_TABLE_TABLE = db_table_class(new_table, temp_schema, engine, tableInstance.session, debug_level - 1) columns_str = '' for column in columns: if columns_str: columns_str = columns_str + ' , ' + column.name else: columns_str = column.name from_table = tableInstance.model.__tablename__ to_table = new_table.name ddl_string = f"INSERT INTO {to_table} ({columns_str}) select {columns_str} from {from_table}" if int(debug_level) > 0: msg = f"table [[{tableInstance.model.__tablename__}]] copy records to [[{to_table}]] DDL: [[[{ddl_string}]]]" log_message(msg) try: engine.execute(ddl_string) except Exception as e: print(e) return False # query_rows2= NEW_TABLE_TABLE.rowCount() query_rows2 = engine.execute(f"select count(*) from {to_table}").scalar() #garbage kill del new_table del physical_table # del PHYSICAL_TABLE_TABLE # del NEW_TABLE_TABLE msg = f"table [[{from_table}]] [copied to ] [[{to_table}]] with [[[{query_rows2}/{query_rows1} rows]]]." if int(debug_level) > 0: log_message(msg) if query_rows1 == query_rows2: return to_table else: return None