def QueryMySql(query):
	# Create object for internal database methods (mySQL)
	mysqlDb = MySqlTask(config.mysql_username, config.mysql_password, config.mysql_host, config.mysql_database)
	mysqlDb.connect()

	results = mysqlDb.select_query(query)

	mysqlDb.close()

	return results
    if not offset.find("+"):
        minuteOffset = float(offset[1:]) * .6
        return str(timeToConvert - timedelta(minutes=minuteOffset))
    else:
        minuteOffset = float(offset[1:]) * .6
        return str(timeToConvert + timedelta(minutes=minuteOffset))

if __name__ == "__main__":
    logging.info("Running incremental Zendesk export...")

    # Create object for Zendesk queries
    zd = ZendeskTask(config.zenURL, config.zenAgent, config.zenPass, config.zenToken)
    
    # Create object for internal database methods (mySQL)
    zendeskDb = MySqlTask(config.zendeskMySql['username'],
                          config.zendeskMySql['password'],
                          config.zendeskMySql['host'],
                          config.zendeskMySql['database'])
    zendeskDb.connect()

    # Grab the last time Accounts were successfully updated
    start_time = zendeskDb.pull_job_timestamp("INCREMENTAL_EXPORT")

    logging.info("INCREMENTAL_EXPORT: start_time={0}".format(start_time))
    try:
        tickets = zd.get_tickets(start_time)

    except Exception, err:
        logging.exception(err)
    #print tickets

    dbQuery = ("INSERT INTO tickets "
import sys
import logging
import config
import re
from env import MySqlTask
from env import SalesforceTask
from env import ZendeskTask

if config.logLevel == "info":
	logging.basicConfig(format='%(asctime)s | %(levelname)s | %(filename)s | %(message)s', level=logging.INFO, filename=config.logFile)
else:
	logging.basicConfig(format='%(asctime)s | %(levelname)s | %(filename)s | %(message)s', level=logging.DEBUG, filename=config.logFile)

if __name__ == "__main__":
	# Create object for internal database methods (mySQL)
	mysqlDb = MySqlTask(config.mysql_username, config.mysql_password, config.mysql_host, config.mysql_database)

	# Create object for Salesforce methods
	sfdc = SalesforceTask(config.sfUser, config.sfPass, config.sfApiToken)

	# Create object for Zendesk methods
	zd = ZendeskTask(config.zenURL, config.zenAgent, config.zenPass, config.zenToken)

	### Pull SFDC Contact Info to Zendesk ###
	try:
		sfdcLastModified = sfdc.sfdc_timestamp()
		logging.info("Current Salesforce Timestamp: {0}".format(sfdcLastModified))
	except Exception, err:
		logging.error(err)
		sys.exit()
import time
import calendar
from datetime import datetime
from env import MySqlTask

if config.logLevel == "info":
	logging.basicConfig(format='%(asctime)s | %(levelname)s | %(filename)s | %(message)s', level=logging.INFO, filename=config.logFile)
else:
	logging.basicConfig(format='%(asctime)s | %(levelname)s | %(filename)s | %(message)s', level=logging.DEBUG, filename=config.logFile)


if __name__ == "__main__":
	_table_name = 'usage_reporting'

	# Create object for internal database methods (mySQL)
	mysql = MySqlTask(config.mysql_username, config.mysql_password, config.mysql_host, config.mysql_database)

	retry = 3
	while retry:
		try:
			logging.info("Getting valid columns from MySQL.")
			valid_sources = mysql.return_columns(_table_name)
			valid_sources = [ col for col in valid_sources if col not in ('intID', 'username', 'start', 'end', 'stream_type', 'stream_hash', 'seconds') ]
			logging.debug("Columns found: {0}".format(valid_sources))
			retry = 0
		except Exception, err:
			#print err #2013: Lost connection to MySQL server during query
			logging.error(err)
			retry -= 1
			logging.warning("Retries left: {0}".format(retry))
			time.sleep(2) # Sleep 2 seconds before retrying
# -*- coding: utf-8 -*-

from env import SalesforceTask
from env import MySqlTask
import config
import re
import logging
import sys

if config.logLevel == "info":
	logging.basicConfig(format='%(asctime)s | %(levelname)s | %(filename)s | %(message)s', level=logging.INFO, filename=config.logFile)
else:
	logging.basicConfig(format='%(asctime)s | %(levelname)s | %(filename)s | %(message)s', level=logging.DEBUG, filename=config.logFile)

sfdc = SalesforceTask(config.sfUser, config.sfPass, config.sfApiToken)
mysqlDb = MySqlTask(config.mysql_username, config.mysql_password, config.mysql_host, config.mysql_database)

sfdc_update = {}

# Get the last modified timestamp from internal database
startTime = mysqlDb.pull_job_timestamp('SFDC_DATASIFT_USER_ID')
logging.info("Pulling SFDC_DATASIFT_USER_ID; start time of {0}".format(startTime))

# Pull from SFDC
query = "Select Id, DataSift_UserID__c, Name FROM Account WHERE Account_Status__c = 'Customer' and DataSift_UserID__c != '' and LastModifiedDate > {0}".format(startTime)

results = sfdc.sfdc_query(query)

if results['count'] > 0:
	for account in results['results']:
		if account['Id'] not in sfdc_update:
	# Load config files
	try:
		filename = sys.argv[1]
		logging.info("Trying to open configuration file {0}.".format(filename))
		f = open(filename)
		config = yaml.safe_load(f)

		logging.info("Sucessfully opened configuration file.")

		f.close()
	except Exception, err:
		logging.exception(err)
		sys.exit(1)

	# Create object for internal database methods (mySQL)
	mysqlDb = MySqlTask(config['mysql_username'], config['mysql_password'], config['mysql_host'], config['mysql_database'])

	# Create object for Salesforce methods
	sfdc = SalesforceTask(config['sfUser'], config['sfPass'], config['sfApiToken'])

	# Create object for Zendesk methods
	zd = ZendeskTask(config['zenURL'], config['zenAgent'], config['zenPass'], config['zenToken'])

	### Pull SFDC Account Info to Zendesk Organizations ###
	try:
		sfdcLastModified = sfdc.sfdc_timestamp()
		logging.info("Current Salesforce Timestamp: {0}".format(sfdcLastModified))
	except Exception, err:
		logging.exception(err)
		sys.exit()

def processQueryResults(fieldName, data):
    users = {}
    for user in data:
        if user["Owner"]["Name"] != user[fieldName]:
            users[user["Id"]] = user["Owner"]["Name"]

    return users


if __name__ == "__main__":

    try:
        # Create object for internal database methods (mySQL)
        mysqlDb = MySqlTask(config.mysql_username, config.mysql_password, config.mysql_host, config.mysql_database)

        # Create object for Salesforce methods
        sfdc = SalesforceTask(config.sfUser, config.sfPass, config.sfApiToken)

        logging.info("Logging into SFDC...")

        ######################## SFDC Accounts ########################
        # Get the last modified timestamp
        sfdcLastModified = sfdc.sfdc_timestamp()

        # Grab the last time Accounts were successfully updated
        scriptLastRun = mysqlDb.pull_job_timestamp("SFDC_ACCOUNT_OWNERS_LM")

        query = "SELECT Id, Name, OwnerId, Owner.Name, Account_Owner_Name__c FROM Account WHERE LastModifiedDate > {0}".format(
            scriptLastRun