Advertisement
naimul64

StudentDataMigration

Jul 23rd, 2017
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.87 KB | None | 0 0
  1. __author__ = 'insan'
  2. EMPTY_STRING = ''
  3. CURRENT_SESSION = 1
  4.  
  5. import MySQLdb
  6. import configparser
  7. import datetime
  8. import traceback
  9. import re
  10. import logging
  11.  
  12.  
  13. logFormatter = logging.Formatter("%(asctime)s [%(levelname)-5.5s]  %(message)s")
  14. logger = logging.getLogger()
  15. logger.setLevel(logging.INFO)
  16.  
  17. fileHandler = logging.FileHandler("student_migration.log")
  18. fileHandler.setFormatter(logFormatter)
  19.  
  20. logger.addHandler(fileHandler)
  21.  
  22. # consoleHandler = logging.StreamHandler()
  23. # consoleHandler.setFormatter(logFormatter)
  24. # logger.addHandler(consoleHandler)
  25.  
  26.  
  27. def validate_amount(amount, no_of_student):
  28.     amount = re.sub("[^0-9]", "", str(amount))
  29.     if str(amount) == '':
  30.         return 0
  31.  
  32.     try:
  33.         amount = int(str(amount))
  34.     except Exception:
  35.         #traceback.print_exc()
  36.         amount = 0
  37.     if amount < 0:
  38.         return 0
  39.     if amount % 25 != 0:
  40.         amount = amount - (amount%25)
  41.     if amount < 50:
  42.         amount = 0
  43.     if amount > 1350:
  44.         amount = 1350
  45.     if no_of_student == 1 and amount > 375:
  46.         amount = 375
  47.     if no_of_student == 2 and amount > 750:
  48.         amount = 750
  49.     if no_of_student == 3 and amount > 1050:
  50.         amount = 1050
  51.     if no_of_student == 4 and amount > 1350:
  52.         amount = 1350
  53.  
  54.     return amount
  55.  
  56.  
  57. def validate_std_cnt(no_of_student, amount):
  58.     try:
  59.         no_of_student = int(str(no_of_student))
  60.     except Exception as e:
  61.         #print e
  62.         no_of_student = 0
  63.     try:
  64.         amount = int(amount)
  65.     except Exception as e:
  66.         #print e
  67.         amount = 0
  68.  
  69.     if no_of_student == '' or no_of_student == None:
  70.         no_of_student = 0
  71.  
  72.     if amount == 0:
  73.         no_of_student = 1
  74.     if amount > 375:
  75.         no_of_student = 2
  76.     if amount > 750:
  77.         no_of_student = 3
  78.     if amount > 1050:
  79.         no_of_student = 4
  80.     if no_of_student > 4:
  81.         no_of_student = 4
  82.  
  83.     return no_of_student
  84.  
  85.  
  86. def get_data_from_source(src_db_con, school_code_list_string):
  87.     cursor = src_db_con.cursor()
  88.     query = """SELECT
  89.        dsrd.id parent_id, dsrd.amount, ifnull(dsrd.no_of_student, 1), dsrd.school_code school_code
  90.    FROM
  91.        q2_disbursement_sheet_raw_data_report_prime dsrd
  92.        WHERE dsrd.school_code IN (""" + school_code_list_string + """)
  93.    """
  94.  
  95.     cursor.execute(query)
  96.     result = cursor.fetchall()
  97.  
  98.     return result
  99.  
  100.  
  101. def get_parent_dsSheet_map(dest_db_con, dsSheet_id_list):
  102.     map = {}
  103.     cursor = dest_db_con.cursor()
  104.     # cursor.execute("SET SESSION range_optimizer_max_mem_size = 16688608")
  105.     cursor.execute("""
  106.      SELECT dsSheet_id, parent_id from dsSheet_parent_map
  107.      WHERE dsSheet_id in (%s)
  108.      """ % dsSheet_id_list
  109.     )
  110.     result = cursor.fetchall()
  111.     for row in result:
  112.         map[str(row[0])] = str(row[1])
  113.  
  114.     return map
  115.  
  116.  
  117. def get_dsSheetId_list_from_schoolCode(src_db_con, school_code_list_string):
  118.     cursor = src_db_con.cursor()
  119.     # cursor.execute("SET SESSION group_concat_max_len = 1000000")
  120.     cursor.execute("""
  121.        SELECT
  122.            id
  123.        FROM
  124.            q2_disbursement_sheet_raw_data_report_prime
  125.        WHERE
  126.            school_code IN (""" + school_code_list_string + """)
  127.    """)
  128.  
  129.     result = cursor.fetchall()
  130.     id_list = []
  131.  
  132.     for row in result:
  133.         id_list.append(str(row[0]))
  134.  
  135.     if len(id_list) > 0:
  136.         return ",".join(id_list)
  137.     else:
  138.         return None
  139.  
  140.  
  141. def get_studentwise_amount_list(no_of_student, amount):
  142.     studentwise_amount_list = []
  143.     if no_of_student == 1 or no_of_student == 0:
  144.         studentwise_amount_list.append(amount)
  145.         return studentwise_amount_list
  146.  
  147.     if amount == 0:
  148.         studentwise_amount_list = get_studentwise_amount_list(no_of_student - 1, amount)
  149.         studentwise_amount_list.append(0)
  150.     elif amount <= no_of_student * 375 and no_of_student * 300 < amount:
  151.         studentwise_amount_list = get_studentwise_amount_list(no_of_student - 1, amount - 375)
  152.         studentwise_amount_list.append(375)
  153.     elif amount <= no_of_student * 300 and no_of_student * 150 < amount:
  154.         studentwise_amount_list = get_studentwise_amount_list(no_of_student - 1, amount - 300)
  155.         studentwise_amount_list.append(300)
  156.     elif amount <= no_of_student * 150 and amount > no_of_student * 100:
  157.         studentwise_amount_list = get_studentwise_amount_list(no_of_student - 1, amount - 150)
  158.         studentwise_amount_list.append(150)
  159.     else:
  160.         studentwise_amount_list = get_studentwise_amount_list(no_of_student - 1, amount - 25)
  161.         studentwise_amount_list.append(50)
  162.  
  163.     for num in studentwise_amount_list:
  164.         if num < 0:
  165.             pass
  166.     return studentwise_amount_list
  167.  
  168.  
  169. def get_school_id_by_code(school_code, dest_db_con):
  170.     cursor = dest_db_con.cursor()
  171.     cursor.execute("SELECT id FROM school WHERE code=%s" % school_code)
  172.     result = cursor.fetchone()
  173.     if result is not None:
  174.         return result[0]
  175.     else:
  176.         return None
  177.  
  178.  
  179. def insert_student_data(src_db_con, dest_db_con, school_code_list_string):
  180.     dest_cursor = dest_db_con.cursor()
  181.     #next_student_id = get_next_student_id(dest_cursor)
  182.     dsSheetId_stdCnt_schoolId_list = get_data_from_source(src_db_con, school_code_list_string)
  183.     dsSheet_id_list = get_dsSheetId_list_from_schoolCode(src_db_con, school_code_list_string)
  184.  
  185.     print "DsSheet entry in this thana " + str(len(dsSheetId_stdCnt_schoolId_list))
  186.  
  187.     if dsSheet_id_list is None:
  188.         return
  189.  
  190.     parent_dsSheet_map = get_parent_dsSheet_map(dest_db_con, dsSheet_id_list)
  191.  
  192.     for tupol in dsSheetId_stdCnt_schoolId_list:
  193.         dsShhet_id = str(tupol[0])
  194.         no_of_student = validate_std_cnt(no_of_student=tupol[2], amount=tupol[1])
  195.         amount = validate_amount(amount=tupol[1], no_of_student=no_of_student)
  196.  
  197.         student_wise_amount_list = get_studentwise_amount_list(no_of_student, amount)
  198.  
  199.         school_id = get_school_id_by_code(tupol[3], dest_db_con)
  200.  
  201.         if school_id is not None:
  202.             for i in range(no_of_student):
  203.                 student_insert_query = ''
  204.                 student_stipend_query = ''
  205.                 if dsShhet_id in parent_dsSheet_map:
  206.                     student_insert_query = """
  207.                        INSERT INTO student (name, parent_id, school_id)
  208.                        VALUES ('%s', %s, %s)
  209.                        """ % (EMPTY_STRING, parent_dsSheet_map[dsShhet_id], school_id)
  210.                     dest_cursor.execute(student_insert_query)
  211.  
  212.                     student_id = get_next_student_id(dest_cursor)
  213.                     student_stipend_query = """
  214.                        INSERT INTO student_stipend (amount, session_id, student_id)
  215.                        VALUES (%s, %s,%s)
  216.                    """ % (student_wise_amount_list[i], CURRENT_SESSION, student_id)
  217.                     dest_cursor.execute(student_stipend_query)
  218.  
  219.                 else:
  220.                     logger.error("No map found for ds id %s" % dsShhet_id)
  221.         else:
  222.             logger.error("No school found for sc: %s in dest db" % tupol[3])
  223.  
  224.     dest_db_con.commit()
  225.  
  226.  
  227. def get_next_student_id(cursor):
  228.     # cursor.execute("""
  229.     # select id from student
  230.     #     order by id desc
  231.     #     limit 1
  232.     # """)
  233.     # next_id = cursor.fetchall()
  234.     # if len(next_id) == 0 or len(next_id[0]) == 0:
  235.     #     next_id = 1
  236.     # else:
  237.     #     next_id = next_id[0][0] + 1
  238.     #
  239.     # return next_id
  240.     return cursor.lastrowid
  241.  
  242.  
  243. # def get_next_student_stipend_id(cursor):
  244. #     cursor.execute("""
  245. #     select id from student_stipend
  246. #         order by id desc
  247. #         limit 1
  248. #     """)
  249. #     next_id = cursor.fetchall()
  250. #     if len(next_id) == 0 or len(next_id[0]) == 0:
  251. #         next_id = 1
  252. #     else:
  253. #         next_id = next_id[0][0] + 1
  254. #
  255. #     return next_id
  256.  
  257.  
  258. # def get_thana_list(live_db_conn):
  259. #     cursor = live_db_conn.cursor()
  260. #     cursor.execute("""
  261. #         SELECT id from thana
  262. #          WHERE 1
  263. #          AND id > 0
  264. #          AND id <= 600
  265. #         ORDER BY id
  266. #     """)
  267. #     thana_id_list = []
  268. #     result = cursor.fetchall()
  269. #     for row in result:
  270. #         thana_id_list.append(row[0])
  271. #
  272. #     return thana_id_list
  273.  
  274.  
  275. def get_school_code_list_string(thana_id, live_db_con):
  276.     cursor = live_db_con.cursor()
  277.     cursor.execute("""
  278.    SELECT
  279.        school_code
  280.    FROM
  281.        school
  282.    WHERE
  283.        thana_id = """ + str(thana_id) + """ AND school_code REGEXP '^[0-9]+$'
  284.    """)
  285.     result = cursor.fetchall()
  286.  
  287.     sc_list = []
  288.     for row in result:
  289.         sc_list.append(row[0])
  290.  
  291.     try:
  292.         return "'"+"','".join(sc_list)+"'"
  293.     except Exception as e:
  294.         traceback.print_stack()
  295.         return None
  296.  
  297.  
  298. def get_reader():
  299.     config = configparser.ConfigParser()
  300.     config.sections()
  301.     config.read('config.ini')
  302.  
  303.     return config
  304.  
  305.  
  306. def get_src_connection():
  307.     config = get_reader()
  308.     section = config.default_section
  309.  
  310.     return MySQLdb.connect(config.get(section, 'src_ip'),
  311.                            config.get(section, 'src_uname'),
  312.                            config.get(section, 'src_pword'),
  313.                            config.get(section, 'src_db'))
  314.  
  315.  
  316. def get_dest_connection():
  317.     config = get_reader()
  318.     section = config.default_section
  319.  
  320.     return MySQLdb.connect(config.get(section, 'dest_ip'),
  321.                            config.get(section, 'dest_uname'),
  322.                            config.get(section, 'dest_pword'),
  323.                            config.get(section, 'dest_db'))
  324.  
  325.  
  326. def get_live_db_connection():
  327.     config = get_reader()
  328.     section = config.default_section
  329.  
  330.     return MySQLdb.connect(config.get(section, 'live_ip'),
  331.                            config.get(section, 'live_uname'),
  332.                            config.get(section, 'live_pword'),
  333.                            config.get(section, 'live_db'))
  334.  
  335.  
  336. def run():
  337.     # configure source database connection
  338.     src_db_con = get_src_connection()
  339.     # configure destination database connection
  340.     dest_db_con = get_dest_connection()
  341.     # live db configure
  342.     live_db_con = get_live_db_connection()
  343.  
  344.     thana_id_list = [x for x in range(401, 510)]
  345.     count = 1
  346.  
  347.     # total = len(thana_id_list)
  348.     for thana_id in thana_id_list:
  349.         logger.info("Processing thana: %d" % thana_id)
  350.         start_time = datetime.datetime.now()
  351.         school_code_list_string = get_school_code_list_string(thana_id, live_db_con)
  352.         # school_code_list_string = get_school_code_list_string(thana_id, live_db_con)
  353.         if school_code_list_string is not None:
  354.             insert_student_data(src_db_con, dest_db_con, school_code_list_string)
  355.         end_time = datetime.datetime.now()
  356.         logger.info("Processing done for thana: %d" % thana_id)
  357.         print "Processing done for thana: %d" % thana_id
  358.         print "Time taken: " + str(end_time - start_time)
  359.         count += 1
  360.  
  361. run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement