地块面积迁移脚本


import json

import psycopg2

USER = "postgres"
PASSWORD = "Mz9A85vmP5wSxxeNbGBrjv86L9bJoX"
PORT = 5432
HOST = "10.0.0.17"
DATABASE = "unittest"


def call_postgresql(sql, flag=1):
    # "flag = 1表示获取多条数据 0表示获取单条数据"

    conn = psycopg2.connect(database=DATABASE, port=PORT,
                            host=HOST, user=USER, password=PASSWORD)
    cursor = conn.cursor()
    cursor.execute(sql)
    if flag:
        results = cursor.fetchall()
    else:
        results = None
    conn.commit()
    conn.close()
    return results

def get_area():
    # if "bigdata" in testcase_id:
        # testcase_id = "testcase_bigdata_{}".format(testcase_id[-5:])
    # elif "multi_product" in testcase_id:
        # testcase_id = 'testcase_{:05d}'.format(int(block_type.split("_")[-1]))
    # else:
        # testcase_id = testcase_id[:14]    
    sql = "select testcase_id,area from testcase_area"
    rows = call_postgresql(sql)
    r_dict = {}
    for row in rows:
        r_dict[row[0]] = row[1]
    return r_dict

def get_area_from_testcase_id(testcase_id,block_type,kwargs:dict):
    if "bigdata" in testcase_id:
        testcase_id = "testcase_bigdata_{}".format(testcase_id[-5:])
    elif "multi_product" in testcase_id:
        testcase_id = 'testcase_{:05d}'.format(int(block_type.split("_")[-1]))
    else:
        testcase_id = testcase_id[:14]
    return kwargs[testcase_id]

def migrate():
    sql = "select id,testcase_id,type FROM baseline_new_algorithm_result"
    return_list = []
    result = call_postgresql(sql)
    sql_list = []
    all_dict = get_area()
    for row in result:
        area = get_area_from_testcase_id(row[1],row[2],all_dict)
        sql_list.append("UPDATE baseline_new_algorithm_result SET area_list_string='{:.2f}' where id={}".format(area,row[0]))
    return sql_list

if __name__ == "__main__":
    sql_list = migrate()
    conn = psycopg2.connect(database=DATABASE, port=PORT,
                            host=HOST, user=USER, password=PASSWORD)
    cursor = conn.cursor()
    for sql in sql_list:
        cursor.execute(sql)
        conn.commit()
    conn.close()