# -*- coding:utf-8 -*-
import json
from optparse import OptionParser
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import pymssql
# data = {
#     "pbAPPUpgradeReleaseHistory": [
#         {"app_code": "Tool", "app_version": "master", "project_branch": "master", "project_url": "http://baidu.com",
#          "project_name": "tools", "operator_email": "huangtianba@huansi.net"}
#     ]
# }
#
# print(json.dumps(data, separators=(',', ':')))
# LINUX上  ./db_manage -c mssql+pymssql:// --data '{"pbAPPUpgradeReleaseHistory":[{"project_name":"tools","project_branch":"master","app_code":"Tool","project_url":"http://baidu.com","operator_email":"huangtianba@huansi.net","app_version":"master"}]}'
if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option('-c', '--connection', help='db connection string')
    parser.add_option('-d', '--data', help='data', metavar="FILE")

    options, args = parser.parse_args()

    con_str = options.connection
    data_dict_str = options.data

    print(data_dict_str)
    data_dict_str = data_dict_str.replace("'", '"')
    data_dict = json.loads(data_dict_str)

    sql_list = []
    for table, table_data_list in data_dict.items():
        for table_data in table_data_list:
            sql_list.append('''INSERT INTO {}
({})
VALUES
({})'''.format(table, ','.join(table_data.keys()),
               ','.join(["'" + str(item) + "'" for item in table_data.values()])))

    sql_str = '\n'.join(sql_list)
    print(sql_str)

    engine = create_engine(con_str)

    DBSession = sessionmaker(bind=engine)

    session = DBSession()
    try:
        result = session.execute(sql_str)

        session.commit()
    except Exception as e:
        session.rollback()

        orig = getattr(e, 'orig')
        args = getattr(orig, 'args', ((),))
        if isinstance(args[0], tuple):
            args = args[0]

        error_message = ''
        for e_item in args:
            if isinstance(e_item, bytes):
                try:
                    e_item = e_item.decode()
                except:
                    e_item = str(e_item)
            error_message += str(e_item)

        if not error_message:
            error_message = str(e)
        print('exec sql error:{}'.format(error_message))
    finally:
        session.close()
