def migrate(conn, tables):
    import os
    from systools import sys_log_debug
    updateTablesPriority = [
        "Orders", "OrderCustomProperties", "OrderItemCustomProperties", "OrderStateHistory",
        "OrderItem", "OrderTax", "OrderDiscount", "OrderVoidHistory", "OrderTender", "OrderComment",
        "POS", "CurrentOrderItem", "BackupOrders", "BackupCurrentOrderItem", "OrderPrice", "OrderProduct"
    ]
    sys_log_debug("[migrate] start")
    for table in updateTablesPriority:
        if tables[table]["fields_OldDB"]:
            sys_log_debug("[migrate] table {}".format(table))
            strCommonFields = ", ".join(tables[table]["fields_Common"])
            sys_log_debug("[migrate] copying data for table {}".format(table))
            stmt = "INSERT OR REPLACE INTO %s (%s) SELECT %s FROM old.%s;" % (table, strCommonFields, strCommonFields, table)
            conn.query(stmt)
            sys_log_debug("[migrate] finished query for table {}".format(table))
    # Updates new OrderPrice table
    if not tables["OrderPrice"]["fields_OldDB"]:
        db_path = '{}/databases/product.db'.format(os.environ['HVDATADIR'])
        sys_log_debug("[migrate] attaching database {}".format(db_path))
        conn.query("ATTACH DATABASE '{}' as 'productdb';".format(db_path))
        sys_log_debug("[migrate] copying actual OrderItem pricekeys to new OrderPrice table ...")
        conn.query("""
            INSERT INTO OrderPrice(OrderId,PriceKey,DefaultUnitPrice,AddedUnitPrice,SubtractedUnitPrice,Computed,IncludedQty,ValidFrom,ValidThru)
            SELECT T.OrderId,T.PriceKey,P.DefaultUnitPrice,P.AddedUnitPrice,P.SubtractedUnitPrice,P.Computed,P.IncludedQty,P.ValidFrom,P.ValidThru
            FROM (SELECT DISTINCT OrderId, PriceKey FROM OrderItem) T
            JOIN productdb.Price P WHERE P.PriceKey=T.PriceKey;
        """)
    sys_log_debug("[migrate] finished iterating")
