1# Copyright (c) 2017-2018 Cedric Bellegarde <cedric.bellegarde@adishatz.org> 2# Copyright (c) 2015 Jean-Philippe Braun <eon@patapon.info> 3# This program is free software: you can redistribute it and/or modify 4# it under the terms of the GNU General Public License as published by 5# the Free Software Foundation, either version 3 of the License, or 6# (at your option) any later version. 7# This program is distributed in the hope that it will be useful, 8# but WITHOUT ANY WARRANTY; without even the implied warranty of 9# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10# GNU General Public License for more details. 11# You should have received a copy of the GNU General Public License 12# along with this program. If not, see <http://www.gnu.org/licenses/>. 13 14from threading import current_thread 15 16from eolie.define import App 17 18 19class SqlCursor: 20 """ 21 Context manager to get the SQL cursor 22 """ 23 def add(obj): 24 """ 25 Add cursor to thread list 26 """ 27 name = current_thread().getName() + obj.__class__.__name__ 28 App().cursors[name] = obj.get_cursor() 29 30 def remove(obj): 31 """ 32 Remove cursor from thread list and commit 33 """ 34 name = current_thread().getName() + obj.__class__.__name__ 35 if name in App().cursors.keys(): 36 obj.thread_lock.acquire() 37 App().cursors[name].commit() 38 obj.thread_lock.release() 39 App().cursors[name].close() 40 del App().cursors[name] 41 42 def commit(obj): 43 """ 44 Commit current obj 45 """ 46 name = current_thread().getName() + obj.__class__.__name__ 47 if name in App().cursors.keys(): 48 obj.thread_lock.acquire() 49 App().cursors[name].commit() 50 obj.thread_lock.release() 51 52 def __init__(self, obj, commit=False): 53 """ 54 Init object 55 @param obj as Database/Playlists/Radios 56 @param commit as bool 57 """ 58 self.__obj = obj 59 self.__commit = commit 60 self.__cursor = None 61 62 def __enter__(self): 63 """ 64 Get thread cursor or a new one 65 """ 66 name = current_thread().getName() + self.__obj.__class__.__name__ 67 if name in App().cursors.keys(): 68 cursor = App().cursors[name] 69 return cursor 70 else: 71 self.__cursor = self.__obj.get_cursor() 72 return self.__cursor 73 74 def __exit__(self, type, value, traceback): 75 """ 76 Close cursor if not thread cursor 77 """ 78 if self.__cursor is not None: 79 if self.__commit: 80 self.__obj.thread_lock.acquire() 81 self.__cursor.commit() 82 self.__obj.thread_lock.release() 83 self.__cursor.close() 84 self.__cursor = None 85