diff --git a/sickbeard/db.py b/sickbeard/db.py index d379d5d8..fc9a9637 100644 --- a/sickbeard/db.py +++ b/sickbeard/db.py @@ -47,6 +47,29 @@ def dbFilename(filename='sickbeard.db', suffix=None): return ek.ek(os.path.join, sickbeard.DATA_DIR, filename) +def mass_upsert_sql(tableName, valueDict, keyDict): + + """ + use with cl.extend(mass_upsert_sql(tableName, valueDict, keyDict)) + + :param tableName: table name + :param valueDict: dict of values to be set {'table_fieldname': value} + :param keyDict: dict of restrains for update {'table_fieldname': value} + :return: list of 2 sql command + """ + cl = [] + + genParams = lambda myDict: [x + ' = ?' for x in myDict.keys()] + + cl.append(['UPDATE [%s] SET %s WHERE %s' % ( + tableName, ', '.join(genParams(valueDict)), ' AND '.join(genParams(keyDict))), valueDict.values() + keyDict.values()]) + + + cl.append(['INSERT INTO [' + tableName + '] (' + ', '.join(["'%s'" % ('%s' % v).replace("'", "''") for v in valueDict.keys() + keyDict.keys()]) + ')' + + ' SELECT ' + ', '.join(["'%s'" % ('%s' % v).replace("'", "''") for v in valueDict.values() + keyDict.values()]) + ' WHERE changes() = 0']) + return cl + + class DBConnection(object): def __init__(self, filename='sickbeard.db', suffix=None, row_type=None):