#!/usr/bin/env python
#
# Copyright (c) 2016 Samsung Electronics.Co.Ltd.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; version 2 of the License
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
#!/usr/bin/python
import json
import sys
import os
import subprocess
import base64
import MySQLdb
import MySQLdb.cursors


def unicode_to_str(obj):
    """convert unicode object to str"""

    if isinstance(obj, list):
        return [unicode_to_str(element) for element in obj]
    elif isinstance(obj, dict):
        return {unicode_to_str(key) : unicode_to_str(value) for key, value \
                in obj.iteritems()}
    elif isinstance(obj, unicode):
        return obj.encode('utf-8')
    else:
        return obj

def mysql_excute_query(conn, cur, sql):
    print "==== mysql_excute_query ===="
    print "sql= '%s'" % sql
    result = None
    try:
        cur.execute( sql )
        conn.commit()
    except MySQLdb.IntegrityError:
        print "[mysql warning or error] query = ", sql
        cur.close()
        conn.close()
        sys.exit(1)


def main():

    TEST_DATA    = {}
    MYSQL  = { 'query'    : {},
               'fetchall' : {} }
    RESULT = {}

    print '[INFO] Jenkins TRBS_DATA loaded'
    print '=====[ file base receiving...]=====\n'


    CONFIG = {'MYSQL': {} }

#    if CONFIG['BASE']['location'] == 'internal':

    # load config data
    CONFIG['MYSQL']['host']     = os.getenv("BUILDMONITOR_IP")
    CONFIG['MYSQL']['user']     = os.getenv("BUILDMONITOR_USER")
    CONFIG['MYSQL']['password'] = os.getenv("BUILDMONITOR_PASS")
    CONFIG['MYSQL']['database'] = os.getenv("BUILDMONITOR_NAME")
    print '[CONFIG] mysql - load getenv.\n'

    print CONFIG


    test_data = os.getenv('file0')

    if test_data:
        f = open('file0', 'r')
        TEST_DATA = unicode_to_str(json.loads(f.read()))
        f.close()
    else:
        sys.exit( "[Error] TRBS_DATA is empty!\n" )

    print '[TEST_DATA] load TEST_DATA.\n'


    print '===========[ TEST DATA ]===========\n'
    print TEST_DATA

    # Connect MySQL
    MYSQL['connection'] = MySQLdb.connect( host  =CONFIG['MYSQL']['host'],
                                           user  =CONFIG['MYSQL']['user'],
                                           passwd=CONFIG['MYSQL']['password'],
                                           db    =CONFIG['MYSQL']['database'],
                                           cursorclass=MySQLdb.cursors.DictCursor)
    print '[INFO] connect MySQL'
    MYSQL['cursor'] = MYSQL['connection'].cursor()

    # load received data
    url = TEST_DATA['snapshot_name']
    snapshot_sp = url.split('/')
    snapshot_name = snapshot_sp[len(snapshot_sp) - 1]
    repository = TEST_DATA['repository']
    device_name = TEST_DATA['device_name']
    profile_name = TEST_DATA['profile_name']
    target_name = TEST_DATA['target_name']

    print("snapshot_name : " + snapshot_name)
    print("repository : " + repository)
    print("device_name : " + device_name)
    print("profile_name : " + profile_name)
    print("target_name : " + target_name)

#    sql = 'UNLOCK TABLES;';
#    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], sql)


    # insert build_snapshot
    MYSQL['query']['insert_build_snapshot'] = "INSERT INTO build_snapshot (build_project_id, snapshot_name, snapshot_url, snapshot_num, start_time, end_time, status) SELECT 1, '%s', '%s', 1, FROM_UNIXTIME(UNIX_TIMESTAMP()), FROM_UNIXTIME(UNIX_TIMESTAMP()), 'succeeded' FROM DUAL WHERE NOT EXISTS ( SELECT * FROM build_snapshot WHERE snapshot_name='%s' );" % (snapshot_name, url, snapshot_name)
    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['insert_build_snapshot'])

    # get build_snapshot_id
    MYSQL['query']['select_build_snapshot'] = "SELECT id FROM build_snapshot WHERE snapshot_name='%s'" % (snapshot_name)
    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['select_build_snapshot'])
    build_snapshot_id = MYSQL['cursor'].fetchone()['id']
    print "[Write] build_snapshot id =", build_snapshot_id


    # insert build_image
    MYSQL['query']['insert_build_image'] = "INSERT INTO build_image (build_snapshot_id, repository, device_name, start_time, end_time, status, image_size, image_url) SELECT '%s', '%s', '%s', FROM_UNIXTIME(UNIX_TIMESTAMP()), FROM_UNIXTIME(UNIX_TIMESTAMP()), 'succeeded', 300000000, '%s' FROM DUAL WHERE NOT EXISTS ( SELECT * FROM build_image WHERE  build_snapshot_id=%s );" % (build_snapshot_id, repository, device_name, snapshot_name, build_snapshot_id)
    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['insert_build_image'])

    # get build_image_id
    MYSQL['query']['select_build_image'] = "SELECT id FROM build_image \
        WHERE build_snapshot_id=%s AND repository='%s' AND device_name='%s'" \
        % (build_snapshot_id, repository, device_name)
    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['select_build_image'])
    build_image_id = MYSQL['cursor'].fetchone()['id']
    print "[Write] build_image id =", build_image_id

    # insert application_info
    app_list = TEST_DATA['application_info']
    for app_info in app_list:
        pkg_id = app_info['pkg_id']
        app_id = app_info['app_id']
        app_type = app_info['app_type']
        MYSQL['query']['insert_application_info'] = "INSERT INTO application_info \
            (name, app_id, pkg_id, app_type) SELECT '%s', '%s', '%s', '%s' FROM DUAL WHERE NOT EXISTS \
            ( SELECT * FROM application_info WHERE app_id='%s' AND pkg_id='%s' );" \
            % (pkg_id, app_id, pkg_id, app_type, app_id, pkg_id)
        mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['insert_application_info'])


    # insert launching_performance_profile_name
    MYSQL['query']['insert_launching_performance_profile_name'] = "INSERT INTO launching_performance_profile_name (build_image_id, profile_name) SELECT '%s', '%s' FROM DUAL WHERE NOT EXISTS ( SELECT * FROM launching_performance_profile_name WHERE profile_name='%s' );" % (build_image_id, profile_name, profile_name)
    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['insert_launching_performance_profile_name'])

    # get launching_performance_profile_name_id
    MYSQL['query']['select_launching_performance_profile_name'] = "SELECT id FROM launching_performance_profile_name WHERE profile_name='%s'" % (profile_name)
    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['select_launching_performance_profile_name'])
    launching_performance_profile_name_id = MYSQL['cursor'].fetchone()['id']
    print "[Write] launching_performance_profile_name id =", launching_performance_profile_name_id


    # insert launching_performance_target_name
    MYSQL['query']['insert_launching_performance_target_name'] = "INSERT INTO launching_performance_target_name (build_image_id, target_name) SELECT '%s', '%s' FROM DUAL WHERE NOT EXISTS ( SELECT * FROM launching_performance_target_name WHERE target_name='%s' );" % (build_image_id, target_name, target_name)
    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['insert_launching_performance_target_name'])

    # get launching_performance_target_name_id
    MYSQL['query']['select_launching_performance_target_name'] = "SELECT id FROM launching_performance_target_name WHERE target_name='%s'" % (target_name)
    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['select_launching_performance_target_name'])
    launching_performance_target_name_id = MYSQL['cursor'].fetchone()['id']
    print "[Write] launching_performance_target_name id =", launching_performance_target_name_id


    # get launching_performance_test_id
#    MYSQL['query']['select_launching_performance_test'] = "SELECT AUTO_INCREMENT FROM information_schema.tables WHERE table_name = 'launching_performance_test' AND table_schema = DATABASE( ) ;"
#    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['select_launching_performance_test'])
#    launching_performance_test_id = MYSQL['cursor'].fetchone()['AUTO_INCREMENT']
#    print "[Write] launching_performance_test id =", launching_performance_test_id

    # insert launching_performance_test
    average_time = TEST_DATA['performance_sum'] / TEST_DATA['application_count']
    tpk_dotnet_app_count = TEST_DATA['tpk_dotnet_app_count']
    installed_dotnet_app_count = TEST_DATA['installed_dotnet_app_count']
    launched_dotnet_app_count = TEST_DATA['launched_dotnet_app_count']
    MYSQL['query']['insert_launching_performance_test'] = "INSERT INTO launching_performance_test \
        (build_image_id, average_time, tpk_dotnet_app_count, installed_dotnet_app_count, launched_dotnet_app_count, test_date) \
        SELECT %s, %s, %s, %s, %s, FROM_UNIXTIME(UNIX_TIMESTAMP()) ON DUPLICATE KEY UPDATE build_image_id=%s;" \
        % (build_image_id, average_time, tpk_dotnet_app_count, installed_dotnet_app_count, launched_dotnet_app_count, build_image_id)
    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['insert_launching_performance_test'])

    # get launching_performance_test_id
    MYSQL['query']['select_launching_performance_test'] = "SELECT id FROM launching_performance_test WHERE build_image_id=%s AND average_time=%s;" \
        % (build_image_id, average_time)
    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['select_launching_performance_test'])
    launching_performance_test_id = MYSQL['cursor'].fetchone()['id']
    print "[Write] launching_performance_test id =", launching_performance_test_id

    # delete launching_performance data with the same build_image_id to prevent duplicate insertion.
    MYSQL['query']['delete_launching_performance_conditionally'] = "DELETE FROM \
        launching_performance WHERE build_image_id=%d;" % (build_image_id)
    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['delete_launching_performance_conditionally'])

    # delete launching_performance_test_tpk_app data with the same build_image_id to prevent duplicate insertion.
    MYSQL['query']['delete_launching_performance_test_tpk_app_conditionally'] = "DELETE FROM \
        launching_performance_test_tpk_app WHERE build_image_id=%d;" % (build_image_id)
    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['delete_launching_performance_test_tpk_app_conditionally'])

    # delete launching_performance_test_installed_app data with the same build_image_id to prevent duplicate insertion.
    MYSQL['query']['delete_launching_performance_test_installed_app_conditionally'] = "DELETE FROM \
        launching_performance_test_installed_app WHERE build_image_id=%d;" % (build_image_id)
    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['delete_launching_performance_test_installed_app_conditionally'])

    # delete launching_performance_test_launched_app data with the same build_image_id to prevent duplicate insertion.
    MYSQL['query']['delete_launching_performance_test_launched_app_conditionally'] = "DELETE FROM \
        launching_performance_test_launched_app WHERE build_image_id=%d;" % (build_image_id)
    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['delete_launching_performance_test_launched_app_conditionally'])

    # get application_info_id
    app_info_ids = {}
    MYSQL['query']['select_application_info'] = "SELECT id, app_id FROM application_info;"
    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['select_application_info'])

    row = MYSQL['cursor'].fetchone()
    while row is not None:
        app_info_ids[row['app_id']] = row['id']
        row = MYSQL['cursor'].fetchone()
    print 'app_info_ids: ', app_info_ids

    launching_performance_list = TEST_DATA['launching_performance']
    for launching_performance in launching_performance_list:
        launching_time = launching_performance['launching_time']
        app_id = launching_performance['app_id']
        pkg_id = launching_performance['pkg_id']
        application_info_id = app_info_ids[app_id]
#        MYSQL['query']['select_application_info'] = "SELECT id FROM application_info WHERE app_id='%s' AND pkg_id='%s'" % (app_id, pkg_id)
#        mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['select_application_info'])
#        application_info_id = MYSQL['cursor'].fetchone()['id']
#        print "[Write] application_info id =", application_info_id

#        MYSQL['query']['insert_launching_performance'] =  "INSERT INTO launching_performance (launching_performance_test_id, build_image_id, application_info_id, launching_time) VALUES (%s, %s, %s, %s);" % (launching_performance_test_id, build_image_id, application_info_id, launching_time)
        # insert launching_performance
        MYSQL['query']['insert_launching_performance'] = "INSERT INTO launching_performance \
            (launching_performance_test_id, build_image_id, application_info_id, launching_time) \
            SELECT %s, %s, %s, %s FROM DUAL WHERE NOT EXISTS \
            ( SELECT * FROM launching_performance WHERE launching_performance_test_id=%s AND application_info_id=%s );" \
            % (launching_performance_test_id, build_image_id, application_info_id, launching_time, launching_performance_test_id, application_info_id)
        mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['insert_launching_performance'])

        # insert launching_performance_test_launched_app
        MYSQL['query']['insert_launching_performance_test_launched_app'] = "INSERT INTO launching_performance_test_launched_app \
            (build_image_id, test_id, application_info_id) \
            SELECT %s, %s, %s FROM DUAL WHERE NOT EXISTS \
            ( SELECT * FROM launching_performance_test_launched_app WHERE test_id=%s AND application_info_id=%s );" \
            % (build_image_id, launching_performance_test_id, application_info_id, launching_performance_test_id, application_info_id)
        mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['insert_launching_performance_test_launched_app'])

    # insert launching_performance_test_installed_app
    installed_app_list = TEST_DATA['installed_app_list']
    for installed_app in installed_app_list:
        app_id = installed_app['app_id']
        pkg_id = installed_app['pkg_id']
        application_info_id = app_info_ids[app_id]
        MYSQL['query']['insert_launching_performance_test_installed_app'] = "INSERT INTO launching_performance_test_installed_app \
            (build_image_id, test_id, application_info_id) \
            SELECT %s, %s, %s FROM DUAL WHERE NOT EXISTS \
            ( SELECT * FROM launching_performance_test_installed_app WHERE test_id=%s AND application_info_id=%s );" \
            % (build_image_id, launching_performance_test_id, application_info_id, launching_performance_test_id, application_info_id)
        mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['insert_launching_performance_test_installed_app'])

    # insert launching_performance_test_tpk_app
    for app_info in app_list:
        app_id = app_info['app_id']
        application_info_id = app_info_ids[app_id]
        MYSQL['query']['insert_launching_performance_test_tpk_app'] = "INSERT INTO launching_performance_test_tpk_app \
            (build_image_id, test_id, application_info_id) \
            SELECT %s, %s, %s FROM DUAL WHERE NOT EXISTS \
            ( SELECT * FROM launching_performance_test_tpk_app WHERE test_id=%s AND application_info_id=%s );" \
            % (build_image_id, launching_performance_test_id, application_info_id, launching_performance_test_id, application_info_id)
        mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['insert_launching_performance_test_tpk_app'])

    ### insert memory usage data ###
    # get launching_memory_usage_test_id
#    MYSQL['query']['select_launching_memory_usage_test'] = "SELECT AUTO_INCREMENT FROM information_schema.tables WHERE table_name = 'launching_memory_usage_test' AND table_schema = DATABASE( ) ;"
#    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['select_launching_memory_usage_test'])
#    launching_memory_usage_test_id = MYSQL['cursor'].fetchone()['AUTO_INCREMENT']
#    print "[Write] launching_memory_usage_test id =", launching_memory_usage_test_id

    # insert launching_memory_usage_test
    memory_usage_sum = TEST_DATA['memory_sum']
    app_count = TEST_DATA['memory_count']
    average_memory_usage = memory_usage_sum / app_count
    MYSQL['query']['insert_launching_memory_usage_test'] = "INSERT INTO launching_memory_usage_test \
        (build_image_id, average_memory_usage, memory_usage_sum, app_count, test_date) \
        SELECT %s, %s, %s, %s, FROM_UNIXTIME(UNIX_TIMESTAMP()) ON DUPLICATE KEY UPDATE build_image_id=%s;" \
        % (build_image_id, average_memory_usage, memory_usage_sum, app_count, build_image_id)
    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['insert_launching_memory_usage_test'])

    # get launching_memory_usage_test_id
    MYSQL['query']['select_launching_memory_usage_test'] = "SELECT id FROM launching_memory_usage_test \
        WHERE build_image_id=%s AND average_memory_usage=%s;" % (build_image_id, average_memory_usage)
    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['select_launching_memory_usage_test'])
    launching_memory_usage_test_id = MYSQL['cursor'].fetchone()['id']
    print "[Write] launching_memory_usage_test id =", launching_memory_usage_test_id

    # delete launching_memory_usage and launching_memory_object data with the same build_image_id to prevent duplicate insertion.
    MYSQL['query']['delete_launching_memory_object_conditionally'] = "DELETE FROM launching_memory_object WHERE build_image_id=%d;" \
        % (build_image_id)
    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['delete_launching_memory_object_conditionally'])

    MYSQL['query']['delete_launching_memory_usage_conditionally'] = "DELETE FROM launching_memory_usage WHERE build_image_id=%d;" \
        % (build_image_id)
    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['delete_launching_memory_usage_conditionally'])

    # insert launching memory usage and insert launching memory object
    launching_memory_list = TEST_DATA['memory_performance']
    for launching_memory in launching_memory_list:
        usage = launching_memory['usage']
        pss = launching_memory['pss']
        memory_3d = launching_memory['3d']
        gem = launching_memory['gem']
        app_id = launching_memory['app_id']
        pkg_id = launching_memory['pkg_id']
        application_info_id = app_info_ids[app_id]

        MYSQL['query']['select_launching_memory_usage'] = "SELECT AUTO_INCREMENT FROM information_schema.tables \
            WHERE table_name = 'launching_memory_usage' AND table_schema = DATABASE( ) ;"
        mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['select_launching_memory_usage'])
        launching_memory_usage_id = MYSQL['cursor'].fetchone()['AUTO_INCREMENT']

        MYSQL['query']['insert_launching_memory_usage'] = "INSERT INTO launching_memory_usage \
            (launching_memory_usage_test_id, build_image_id, application_info_id, memory_usage, pss, 3d, gem) \
            SELECT %s, %s, %s, %s, %s, %s, %s FROM DUAL WHERE NOT EXISTS \
            ( SELECT * FROM launching_memory_usage WHERE launching_memory_usage_test_id=%s AND application_info_id=%s );" \
            % (launching_memory_usage_test_id, build_image_id, application_info_id, usage, pss, memory_3d, gem, \
            launching_memory_usage_test_id, application_info_id)
#        MYSQL['query']['insert_launching_memory_usage'] = "INSERT INTO launching_memory_usage (launching_memory_usage_test_id, build_image_id, application_info_id, memory_usage, pss, 3d, gem) VALUES (%s, %s, %s, %s, %s, %s, %s);" % (launching_memory_usage_test_id, build_image_id, application_info_id, usage, pss, memory_3d, gem)
        mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['insert_launching_memory_usage'])

        object_memory_list = launching_memory['app_memory_list']
        for object_memory in object_memory_list:
            object_name = object_memory['object_name']
            pcode_pdata = object_memory['pcode_pdata']

            MYSQL['query']['insert_launching_memory_object'] =  "INSERT INTO launching_memory_object \
                (launching_memory_usage_test_id, launching_memory_usage_id, build_image_id, application_info_id, object_name, pcode_pdata) \
                VALUES (%s, %s, %s, %s, '%s', %s);" \
                % (launching_memory_usage_test_id, launching_memory_usage_id, build_image_id, application_info_id, object_name, pcode_pdata)
            mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['insert_launching_memory_object'])

    BINARY_DATA = TEST_DATA['dotnet_binary']
    # insert dotnet_binary_count
    all_binary_count = BINARY_DATA['binary_count']['all_binary_count']
    selective_aot_dll_count = BINARY_DATA['binary_count']['selective_aot_dll_count']
    full_aot_dll_count = BINARY_DATA['binary_count']['full_aot_dll_count']
    MYSQL['query']['insert_dotnet_binary_count'] = "INSERT INTO dotnet_binary_count \
        (build_image_id, all_binary_count, selective_aot_dll_count, full_aot_dll_count) \
        SELECT %s, %s, %s, %s FROM DUAL WHERE NOT EXISTS ( SELECT * FROM dotnet_binary_count WHERE build_image_id=%s );" \
        % (build_image_id, all_binary_count, selective_aot_dll_count, full_aot_dll_count, build_image_id)
    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['insert_dotnet_binary_count'])

    # insert dotnet_binary_summary
    binary_summary_list = BINARY_DATA['binary_summary']
    for binary_summary in binary_summary_list:
        category = binary_summary['category']
        original_size = binary_summary['original_size']
        selective_aot_size = binary_summary['selective_aot_size']
        full_aot_size = binary_summary['full_aot_size']
        MYSQL['query']['insert_dotnet_binary_summary'] = "INSERT INTO dotnet_binary_summary \
            (build_image_id, category, original_size, selective_aot_size, full_aot_size) \
            SELECT %s, '%s', %s, %s, %s FROM DUAL WHERE NOT EXISTS ( SELECT * FROM dotnet_binary_summary WHERE build_image_id=%s );" \
            % (build_image_id, category, original_size, selective_aot_size, full_aot_size, build_image_id)
        mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['insert_dotnet_binary_summary'])

    # insert dotnet_binary_info
    binary_info_list = BINARY_DATA['binary_info']
    for binary_info in binary_info_list:
        binary_name = binary_info['binary_name']
        category = binary_info['category']
        binary_dir = binary_info['binary_dir']
        binary_type = binary_info['binary_type']
        MYSQL['query']['insert_dotnet_binary_info'] = "INSERT INTO dotnet_binary_info \
            (binary_name, category, binary_dir, binary_type) SELECT '%s', '%s', '%s', '%s' FROM DUAL WHERE NOT EXISTS \
            ( SELECT * FROM dotnet_binary_info WHERE binary_name='%s' AND category='%s' );" \
            % (binary_name, category, binary_dir, binary_type, binary_name, category)
        mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['insert_dotnet_binary_info'])

    # get dotnet_binary_info
    binary_info_ids = {}
    MYSQL['query']['select_dotnet_binary_info'] = "SELECT id, category, binary_name FROM dotnet_binary_info;"
    mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['select_dotnet_binary_info'])

    row = MYSQL['cursor'].fetchone()
    while row is not None:
        if row['category'] not in binary_info_ids:
            binary_info_ids[row['category']] = {}
        binary_info_ids[row['category']][row['binary_name']] = row['id']
        row = MYSQL['cursor'].fetchone()
    print 'binary_info_ids: ', binary_info_ids

    # insert dotnet_binary_size
    binary_size_list = BINARY_DATA['binary_size']
    for binary_size_info in binary_size_list:
        binary_name = binary_size_info['binary_name']
        category = binary_size_info['category']
        binary_size = binary_size_info['binary_size']
        dotnet_binary_info_id = binary_info_ids[category][binary_name]
        MYSQL['query']['insert_dotnet_binary_size'] = "INSERT INTO dotnet_binary_size (dotnet_binary_info_id, build_image_id, binary_size)" \
            "SELECT %s, %s, %s FROM DUAL WHERE NOT EXISTS ( SELECT * FROM dotnet_binary_size WHERE build_image_id=%s AND dotnet_binary_info_id=%s );" \
            % (dotnet_binary_info_id, build_image_id, binary_size, build_image_id, dotnet_binary_info_id)
        mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['insert_dotnet_binary_size'])

    # insert dotnet_binary_aot_dll
    binary_aot_dll_list = BINARY_DATA['binary_aot_dll']
    for binary_aot_dll in binary_aot_dll_list:
        binary_name = binary_aot_dll['binary_name']
        aot_dll_name = binary_aot_dll['aot_dll_name']
        category = binary_aot_dll['category']
        original_binary_size = binary_aot_dll['original_binary_size']
        aot_binary_size = binary_aot_dll['aot_binary_size']
        is_selective_aot = binary_aot_dll['is_selective_aot']
        size_comparative_percentage = binary_aot_dll['size_comparative_percentage']
        dotnet_binary_info_id = binary_info_ids[category][binary_name]
        MYSQL['query']['insert_dotnet_binary_aot_dll'] = "INSERT INTO dotnet_binary_aot_dll \
            (dotnet_binary_info_id, build_image_id, aot_dll_name, is_selective_aot, original_binary_size, aot_binary_size, size_comparative_percentage) \
            SELECT %s, %s, '%s', %s, %s, %s, %s FROM DUAL WHERE NOT EXISTS \
            ( SELECT * FROM dotnet_binary_aot_dll WHERE build_image_id=%s AND dotnet_binary_info_id=%s );" \
            % (dotnet_binary_info_id, build_image_id, aot_dll_name, is_selective_aot, original_binary_size, aot_binary_size, size_comparative_percentage, \
            build_image_id, dotnet_binary_info_id)
        mysql_excute_query(MYSQL['connection'], MYSQL['cursor'], MYSQL['query']['insert_dotnet_binary_aot_dll'])

    MYSQL['cursor'].close()
    MYSQL['connection'].close()

if __name__ == '__main__':
    main()
    sys.exit(0)
