Guest User

Untitled

a guest
Dec 10th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.25 KB | None | 0 0
  1. """
  2. Early tracking date pre-dating March 1st of 2008 is unreliable and
  3. needs to be deleted. This module safely deletes these records in a way
  4. which does not lock tblRequestLog.
  5. """
  6.  
  7. import pymssql, time
  8. from datetime import datetime, timedelta
  9.  
  10. queries = {
  11.     'minDate': 'SELECT MIN(dtTimeStamp) FROM dbo.tblRequestLog WITH (NOLOCK);',
  12.  
  13.     # @@rowcount is selected because of a bug in pymssql that causes
  14.     # row.rowcount to always be 0
  15.     'deleteRange': """DELETE FROM dbo.tblRequestLog WHERE dtTimeStamp
  16.    >= '%s' AND dtTimeStamp <= '%s'; SELECT @@rowcount;"""
  17. }
  18.  
  19. def openDB():
  20.     """ Returns an open connection to the database """
  21.     conn = pymssql.connect(host="****.****.****.****",
  22.                           user="******",
  23.                           password="****",
  24.                           database="*****")
  25.     return conn
  26.  
  27. def formatDate(dt, maxMs=True):
  28.     """ Formats datetime objects such that MSSQL doesn't percieve them
  29.    to be syntax errors. """
  30.     if maxMs:
  31.         return datetime.strftime(dt, "%Y-%m-%d %H:%M:%S.999")
  32.     else:
  33.         return datetime.strftime(dt, "%Y-%m-%d %H:%M:%S.000")
  34.  
  35. def getStartDate():
  36.     """ Retrieves earliest record we have in tblRequestLog """
  37.     conn = openDB()
  38.     cur = conn.cursor()
  39.     cur.execute(queries["minDate"]);
  40.     result = cur.fetchone()[0]
  41.     conn.close()
  42.     return result
  43.  
  44. # This is the day the data becomes reliable
  45. endDate = datetime(2009, 2, 28, 23, 59, 59, 999999)
  46. startDate = getStartDate()
  47. currentDate = startDate
  48.  
  49. # currentDate will move forward 1 minute per iteration of the loop
  50. timeIncrement = timedelta(minutes=1)
  51. currentDate = startDate + timeIncrement
  52.  
  53. conn = openDB()
  54. cur = conn.cursor()
  55.  
  56. try:
  57.     while currentDate <= endDate:
  58.         print(str(datetime.now()) + " ::: Deleting between " +
  59.               formatDate(startDate, False) + " and " +
  60.               formatDate(currentDate, True) + ".")
  61.  
  62.         cur.execute(queries["deleteRange"] % (formatDate(startDate, False), formatDate(currentDate, True)));
  63.  
  64.         print(str(datetime.now()) +
  65.               " ::: Deleted " + str(cur.fetchone()[0]) + " records.")
  66.  
  67.         currentDate += timeIncrement
  68.         time.sleep(5)
  69. except Exception as ex:
  70.     print(str(ex))
  71.  
  72. conn.close()
Add Comment
Please, Sign In to add comment