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)
This commit is contained in:
Prinz23 2017-11-14 21:48:01 +01:00 committed by JackDandy
parent b4ca844f60
commit 0216658231

View file

@ -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):