PyBitmessage/src/helper_sql.py

122 lines
3.6 KiB
Python
Raw Normal View History

"""
SQL-related functions defined here are really pass the queries (or other SQL
commands) to :class:`.threads.sqlThread` through `sqlSubmitQueue` queue and check
or return the result got from `sqlReturnQueue`.
This is done that way because :mod:`sqlite3` is so thread-unsafe that they
won't even let you call it from different threads using your own locks.
SQLite objects can only be used from one thread.
.. note:: This actually only applies for certain deployments, and/or
really old version of sqlite. I haven't actually seen it anywhere.
Current versions do have support for threading and multiprocessing.
I don't see an urgent reason to refactor this, but it should be noted
in the comment that the problem is mostly not valid. Sadly, last time
I checked, there is no reliable way to check whether the library is
or isn't thread-safe.
"""
2018-04-07 07:29:09 +00:00
import threading
import Queue
sqlSubmitQueue = Queue.Queue()
"""the queue for SQL"""
sqlReturnQueue = Queue.Queue()
"""the queue for results"""
sqlLock = threading.Lock()
2013-08-27 00:00:30 +00:00
2018-04-07 07:29:09 +00:00
2013-08-27 00:00:30 +00:00
def sqlQuery(sqlStatement, *args):
"""
Query sqlite and return results
:param str sqlStatement: SQL statement string
:param list args: SQL query parameters
:rtype: list
"""
sqlLock.acquire()
sqlSubmitQueue.put(sqlStatement)
2013-08-27 00:00:30 +00:00
if args == ():
sqlSubmitQueue.put('')
2018-04-07 07:29:09 +00:00
elif isinstance(args[0], (list, tuple)):
2015-11-26 23:37:44 +00:00
sqlSubmitQueue.put(args[0])
2013-08-27 00:00:30 +00:00
else:
sqlSubmitQueue.put(args)
2018-04-07 07:29:09 +00:00
queryreturn, _ = sqlReturnQueue.get()
sqlLock.release()
2013-08-27 00:00:30 +00:00
return queryreturn
def sqlExecuteChunked(sqlStatement, idCount, *args):
2019-10-07 08:08:26 +00:00
"""Execute chunked SQL statement to avoid argument limit"""
# SQLITE_MAX_VARIABLE_NUMBER,
# unfortunately getting/setting isn't exposed to python
sqlExecuteChunked.chunkSize = 999
if idCount == 0 or idCount > len(args):
return 0
totalRowCount = 0
with sqlLock:
for i in range(
len(args) - idCount, len(args),
sqlExecuteChunked.chunkSize - (len(args) - idCount)
):
chunk_slice = args[
2018-04-07 07:29:09 +00:00
i:i + sqlExecuteChunked.chunkSize - (len(args) - idCount)
]
sqlSubmitQueue.put(
sqlStatement.format(','.join('?' * len(chunk_slice)))
)
# first static args, and then iterative chunk
sqlSubmitQueue.put(
2018-04-07 07:29:09 +00:00
args[0:len(args) - idCount] + chunk_slice
)
retVal = sqlReturnQueue.get()
totalRowCount += retVal[1]
sqlSubmitQueue.put('commit')
return totalRowCount
2013-08-27 00:00:30 +00:00
def sqlExecute(sqlStatement, *args):
2019-10-05 09:52:28 +00:00
"""Execute SQL statement (optionally with arguments)"""
sqlLock.acquire()
sqlSubmitQueue.put(sqlStatement)
2013-08-27 00:00:30 +00:00
if args == ():
sqlSubmitQueue.put('')
2013-08-27 00:00:30 +00:00
else:
sqlSubmitQueue.put(args)
_, rowcount = sqlReturnQueue.get()
sqlSubmitQueue.put('commit')
sqlLock.release()
return rowcount
2013-08-27 00:00:30 +00:00
def sqlStoredProcedure(procName):
sqlLock.acquire()
sqlSubmitQueue.put(procName)
sqlLock.release()
2018-04-07 07:29:09 +00:00
class SqlBulkExecute:
"""This is used when you have to execute the same statement in a cycle."""
def __enter__(self):
sqlLock.acquire()
return self
2018-04-07 07:29:09 +00:00
def __exit__(self, exc_type, value, traceback):
sqlSubmitQueue.put('commit')
sqlLock.release()
2018-04-07 07:29:09 +00:00
@staticmethod
def execute(sqlStatement, *args):
"""Used for statements that do not return results."""
sqlSubmitQueue.put(sqlStatement)
if args == ():
sqlSubmitQueue.put('')
else:
sqlSubmitQueue.put(args)
sqlReturnQueue.get()