from sqlalchemy.ext.compiler import compiles
import sqlalchemy.sql.expression as expr
class Upsert(expr.Insert): pass
@compiles(Upsert, "mysql")
def compile_upsert(insert_stmt, compiler, **kwargs):
if insert_stmt._has_multi_parameters:
keys = insert_stmt.parameters[0].keys()
else:
keys = insert_stmt.parameters.keys()
pk = insert_stmt.table.primary_key
auto = None
if (len(pk.columns) == 1 and
isinstance(pk.columns.values()[0].type, sa.Integer) and
pk.columns.values()[0].autoincrement):
auto = pk.columns.keys()[0]
if auto in keys:
keys.remove(auto)
insert = compiler.visit_insert(insert_stmt, **kwargs)
ondup = 'ON DUPLICATE KEY UPDATE'
updates = ', '.join(
'%s = VALUES(%s)' % (c.name, c.name)
for c in insert_stmt.table.columns
if c.name in keys
)
if auto is not None:
last_id = '%s = LAST_INSERT_ID(%s)' % (auto, auto)
if updates:
updates = ', '.join((last_id, updates))
else:
updates = last_id
upsert = ' '.join((insert, ondup, updates))
return upsert
try:
###INSERT OR UPDATe
db.session.execute(Upsert( BIUserStatistic,rows))
except:
print('process_bi_user_statistic_records transaction.rollback()')
db.session.rollback()
raise
else:
print('process_bi_user_statistic_records transaction.commit()')
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.