|
|
@ -6,6 +6,8 @@
|
|
|
|
# @Project : futool-db-lite
|
|
|
|
# @Project : futool-db-lite
|
|
|
|
# @Desc :
|
|
|
|
# @Desc :
|
|
|
|
import threading
|
|
|
|
import threading
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import sqlalchemy
|
|
|
|
from sqlalchemy import Engine
|
|
|
|
from sqlalchemy import Engine
|
|
|
|
from executor.sql_executor import SQLExecutor
|
|
|
|
from executor.sql_executor import SQLExecutor
|
|
|
|
from transaction.connect_transaction import TransactionFactory
|
|
|
|
from transaction.connect_transaction import TransactionFactory
|
|
|
@ -89,19 +91,38 @@ class Sqlsession(object):
|
|
|
|
return self.executor.query(sql).fetchall()
|
|
|
|
return self.executor.query(sql).fetchall()
|
|
|
|
|
|
|
|
|
|
|
|
def insert(self, sql):
|
|
|
|
def insert(self, sql):
|
|
|
|
return self.executor.execute_update(sql)
|
|
|
|
return self._execute_with_tx(sql)
|
|
|
|
|
|
|
|
|
|
|
|
def insert_batch(self, sql):
|
|
|
|
def insert_batch(self, sql_template, data, batch_size=1000):
|
|
|
|
"""
|
|
|
|
"""
|
|
|
|
todo implement
|
|
|
|
批量插入实现
|
|
|
|
|
|
|
|
:param data: [{"id":1, "value":"v1"}, {"id":2, "value":"v2"}] 或者 [(1,'v1'),(2,'v2')]
|
|
|
|
|
|
|
|
:param sql_template: "INSERT INTO table (id, value) VALUES (:id, :value)"
|
|
|
|
|
|
|
|
:param batch_size: 批量插入size
|
|
|
|
|
|
|
|
:return:
|
|
|
|
"""
|
|
|
|
"""
|
|
|
|
pass
|
|
|
|
if data and isinstance(data, list) and len(data) > 0:
|
|
|
|
|
|
|
|
# 特殊处理SQLAlchemy row对象
|
|
|
|
|
|
|
|
if isinstance(data[0], sqlalchemy.engine.row.Row):
|
|
|
|
|
|
|
|
# 转为元组
|
|
|
|
|
|
|
|
data = [tuple(x) for x in data]
|
|
|
|
|
|
|
|
return self.executor.execute_batch(sql_template, data, batch_size)
|
|
|
|
|
|
|
|
|
|
|
|
def update(self, sql):
|
|
|
|
def update(self, sql):
|
|
|
|
return self.executor.execute_update(sql)
|
|
|
|
return self._execute_with_tx(sql)
|
|
|
|
|
|
|
|
|
|
|
|
def delete(self, sql):
|
|
|
|
def delete(self, sql):
|
|
|
|
return self.executor.execute_update(sql)
|
|
|
|
return self._execute_with_tx(sql)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _execute_with_tx(self, sql):
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
|
|
|
self.begin_transaction()
|
|
|
|
|
|
|
|
rt = self.executor.execute_update(sql)
|
|
|
|
|
|
|
|
self.commit()
|
|
|
|
|
|
|
|
return rt
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
|
|
self.rollback()
|
|
|
|
|
|
|
|
print(e)
|
|
|
|
|
|
|
|
|
|
|
|
def begin_transaction(self):
|
|
|
|
def begin_transaction(self):
|
|
|
|
"""
|
|
|
|
"""
|
|
|
|