From 021665823126dcc2889d8b425bf1985516e710d5 Mon Sep 17 00:00:00 2001 From: Prinz23 Date: Tue, 14 Nov 2017 21:48:01 +0100 Subject: [PATCH] Add db.mass_upsert_sql Example usage: my_db = db.DBConnection() cl = [] for i in list: cl.extend(db.mass_upsert_sql( 'tablename', {'fieldname': 'some value'}, {'where clause field(s)': 'value'})) if cl: my_db.mass_action(cl) --- sickbeard/db.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) 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):