use new DatabaseCon context class

This commit is contained in:
shaun 2016-11-05 13:19:57 +11:00
parent a58b644062
commit 881b3f8e70
4 changed files with 183 additions and 209 deletions

View file

@ -6,6 +6,7 @@ import logging
import sqlite3 import sqlite3
from contextlib import closing from contextlib import closing
import sys import sys
import traceback
import xbmc import xbmc
import xbmcaddon import xbmcaddon
@ -97,7 +98,8 @@ class DatabaseConn(object):
def __enter__(self): def __enter__(self):
# Open the connection # Open the connection
self.path = self._SQL(self.db_file) self.path = self._SQL(self.db_file)
log.info("opening database: %s", self.path) log.info("opening: %s", self.path)
#traceback.print_stack()
if settings('dblock') == "true": if settings('dblock') == "true":
self.conn = sqlite3.connect(self.path, isolation_level=None, timeout=self.timeout) self.conn = sqlite3.connect(self.path, isolation_level=None, timeout=self.timeout)
@ -131,7 +133,7 @@ class DatabaseConn(object):
self.conn.commit() self.conn.commit()
log.info("commit: %s", self.path) log.info("commit: %s", self.path)
log.info("close: %s", self.path) log.info("closing: %s", self.path)
self.conn.close() self.conn.close()

View file

@ -28,6 +28,8 @@ import playbackutils as pbutils
import playutils import playutils
import api import api
from utils import window, settings, dialog, language as lang from utils import window, settings, dialog, language as lang
from database import DatabaseConn
from contextlib import closing
################################################################################################# #################################################################################################
@ -234,11 +236,10 @@ def deleteItem():
log.info("Unknown type, unable to proceed.") log.info("Unknown type, unable to proceed.")
return return
embyconn = utils.kodiSQL('emby') with DatabaseConn('emby') as conn:
embycursor = embyconn.cursor() with closing(conn.cursor()) as cursor:
emby_db = embydb.Embydb_Functions(embycursor) emby_db = embydb.Embydb_Functions(cursor)
item = emby_db.getItem_byKodiId(dbId, itemType) item = emby_db.getItem_byKodiId(dbId, itemType)
embycursor.close()
try: try:
itemId = item[0] itemId = item[0]
@ -422,11 +423,10 @@ def getThemeMedia():
return return
# Get every user view Id # Get every user view Id
embyconn = utils.kodiSQL('emby') with DatabaseConn('emby') as conn:
embycursor = embyconn.cursor() with closing(conn.cursor()) as cursor:
emby_db = embydb.Embydb_Functions(embycursor) emby_db = embydb.Embydb_Functions(cursor)
viewids = emby_db.getViews() viewids = emby_db.getViews()
embycursor.close()
# Get Ids with Theme Videos # Get Ids with Theme Videos
itemIds = {} itemIds = {}

View file

@ -13,6 +13,8 @@ import embydb_functions as embydb
import playbackutils as pbutils import playbackutils as pbutils
from utils import window, settings, kodiSQL from utils import window, settings, kodiSQL
from ga_client import log_error from ga_client import log_error
from database import DatabaseConn
from contextlib import closing
################################################################################################# #################################################################################################
@ -165,11 +167,10 @@ class KodiMonitor(xbmc.Monitor):
item_id = None item_id = None
conn = kodiSQL('emby') with DatabaseConn('emby') as conn:
cursor = conn.cursor() with closing(conn.cursor()) as cursor:
emby_db = embydb.Embydb_Functions(cursor) emby_db = embydb.Embydb_Functions(cursor)
db_item = emby_db.getItem_byKodiId(kodi_id, item_type) db_item = emby_db.getItem_byKodiId(kodi_id, item_type)
cursor.close()
try: try:
item_id = db_item[0] item_id = db_item[0]

View file

@ -12,7 +12,6 @@ import xbmcgui
import xbmcvfs import xbmcvfs
import api import api
import database
import utils import utils
import clientinfo import clientinfo
import downloadutils import downloadutils
@ -25,6 +24,7 @@ import videonodes
from objects import Movies, MusicVideos, TVShows, Music from objects import Movies, MusicVideos, TVShows, Music
from utils import window, settings, language as lang, should_stop from utils import window, settings, language as lang, should_stop
from ga_client import GoogleAnalytics from ga_client import GoogleAnalytics
from database import DatabaseConn
from contextlib import closing from contextlib import closing
################################################################################################## ##################################################################################################
@ -57,7 +57,6 @@ class LibrarySync(threading.Thread):
self.monitor = xbmc.Monitor() self.monitor = xbmc.Monitor()
self.clientInfo = clientinfo.ClientInfo() self.clientInfo = clientinfo.ClientInfo()
self.database = database.DatabaseConn
self.doUtils = downloadutils.DownloadUtils().downloadUrl self.doUtils = downloadutils.DownloadUtils().downloadUrl
self.user = userclient.UserClient() self.user = userclient.UserClient()
self.emby = embyserver.Read_EmbyServer() self.emby = embyserver.Read_EmbyServer()
@ -235,11 +234,10 @@ class LibrarySync(threading.Thread):
# Add sources # Add sources
utils.sourcesXML() utils.sourcesXML()
embyconn = utils.kodiSQL('emby') # use emby and video DBs
embycursor = embyconn.cursor() with DatabaseConn('emby') as conn_emby, DatabaseConn('video') as conn_video:
with closing(conn_emby.cursor()) as cursor_emby, closing(conn_video.cursor()) as cursor_video:
# content sync: movies, tvshows, musicvideos, music # content sync: movies, tvshows, musicvideos, music
kodiconn = utils.kodiSQL('video')
kodicursor = kodiconn.cursor()
if manualrun: if manualrun:
message = "Manual sync" message = "Manual sync"
@ -278,8 +276,7 @@ class LibrarySync(threading.Thread):
starttotal = datetime.now() starttotal = datetime.now()
# Set views # Set views
self.maintainViews(embycursor, kodicursor) self.maintainViews(cursor_emby, cursor_video)
embyconn.commit()
# Sync video library # Sync video library
process = { process = {
@ -294,7 +291,7 @@ class LibrarySync(threading.Thread):
continue continue
startTime = datetime.now() startTime = datetime.now()
completed = process[itemtype](embycursor, kodicursor, pDialog) completed = process[itemtype](cursor_emby, kodicursor, pDialog)
if not completed: if not completed:
xbmc.executebuiltin('InhibitIdleShutdown(false)') xbmc.executebuiltin('InhibitIdleShutdown(false)')
utils.setScreensaver(value=screensaver) utils.setScreensaver(value=screensaver)
@ -302,30 +299,23 @@ class LibrarySync(threading.Thread):
if pDialog: if pDialog:
pDialog.close() pDialog.close()
embycursor.close()
kodicursor.close()
return False return False
else: else:
self.dbCommit(kodiconn)
embyconn.commit()
elapsedTime = datetime.now() - startTime elapsedTime = datetime.now() - startTime
log.info("SyncDatabase (finished %s in: %s)" log.info("SyncDatabase (finished %s in: %s)"
% (itemtype, str(elapsedTime).split('.')[0])) % (itemtype, str(elapsedTime).split('.')[0]))
else:
# Close the Kodi cursor
kodicursor.close()
# sync music # sync music
# use emby and music
if music_enabled: if music_enabled:
if repair and 'music' not in repair_list: if repair and 'music' not in repair_list:
pass pass
else: else:
musicconn = utils.kodiSQL('music') with DatabaseConn('emby') as conn_emby, DatabaseConn('music') as conn_music:
musiccursor = musicconn.cursor() with closing(conn_emby.cursor()) as cursor_emby, closing(conn_music.cursor()) as cursor_music:
startTime = datetime.now() startTime = datetime.now()
completed = self.music(embycursor, musiccursor, pDialog) completed = self.music(cursor_emby, cursor_music, pDialog)
if not completed: if not completed:
xbmc.executebuiltin('InhibitIdleShutdown(false)') xbmc.executebuiltin('InhibitIdleShutdown(false)')
utils.setScreensaver(value=screensaver) utils.setScreensaver(value=screensaver)
@ -333,25 +323,21 @@ class LibrarySync(threading.Thread):
if pDialog: if pDialog:
pDialog.close() pDialog.close()
embycursor.close()
musiccursor.close()
return False return False
else: else:
musicconn.commit()
embyconn.commit()
elapsedTime = datetime.now() - startTime elapsedTime = datetime.now() - startTime
log.info("SyncDatabase (finished music in: %s)" log.info("SyncDatabase (finished music in: %s)"
% (str(elapsedTime).split('.')[0])) % (str(elapsedTime).split('.')[0]))
musiccursor.close()
if pDialog: if pDialog:
pDialog.close() pDialog.close()
emby_db = embydb.Embydb_Functions(embycursor) with DatabaseConn('emby') as conn_emby:
with closing(conn_emby.cursor()) as cursor_emby:
emby_db = embydb.Embydb_Functions(cursor_emby)
current_version = emby_db.get_version(self.clientInfo.get_version()) current_version = emby_db.get_version(self.clientInfo.get_version())
window('emby_version', current_version) window('emby_version', current_version)
embyconn.commit()
embycursor.close()
settings('SyncInstallRunDone', value="true") settings('SyncInstallRunDone', value="true")
@ -376,19 +362,11 @@ class LibrarySync(threading.Thread):
def refreshViews(self): def refreshViews(self):
embyconn = utils.kodiSQL('emby') with DatabaseConn('emby') as conn_emby, DatabaseConn('video') as conn_video:
embycursor = embyconn.cursor() with closing(conn_emby.cursor()) as cursor_emby, closing(conn_video.cursor()) as cursor_video:
kodiconn = utils.kodiSQL('video')
kodicursor = kodiconn.cursor()
# Compare views, assign correct tags to items # Compare views, assign correct tags to items
self.maintainViews(embycursor, kodicursor) self.maintainViews(cursor_emby, cursor_video)
self.dbCommit(kodiconn)
kodicursor.close()
embyconn.commit()
embycursor.close()
def maintainViews(self, embycursor, kodicursor): def maintainViews(self, embycursor, kodicursor):
@ -737,19 +715,17 @@ class LibrarySync(threading.Thread):
def incrementalSync(self): def incrementalSync(self):
embyconn = utils.kodiSQL('emby') with DatabaseConn('emby') as conn_emby, DatabaseConn('video') as conn_video:
embycursor = embyconn.cursor() with closing(conn_emby.cursor()) as cursor_emby, closing(conn_video.cursor()) as cursor_video:
kodiconn = utils.kodiSQL('video')
kodicursor = kodiconn.cursor() emby_db = embydb.Embydb_Functions(cursor_emby)
emby_db = embydb.Embydb_Functions(embycursor)
pDialog = None pDialog = None
update_embydb = False update_embydb = False
if self.refresh_views: if self.refresh_views:
# Received userconfig update # Received userconfig update
self.refresh_views = False self.refresh_views = False
self.maintainViews(embycursor, kodicursor) self.maintainViews(cursor_emby, cursor_video)
embycursor.commit()
self.forceLibraryUpdate = True self.forceLibraryUpdate = True
update_embydb = True update_embydb = True
@ -775,7 +751,7 @@ class LibrarySync(threading.Thread):
listItems = list(process[process_type]) listItems = list(process[process_type])
del process[process_type][:] # Reset class list del process[process_type][:] # Reset class list
items_process = itemtypes.Items(embycursor, kodicursor) items_process = itemtypes.Items(cursor_emby, cursor_video)
update = False update = False
# Prepare items according to process process_type # Prepare items according to process process_type
@ -809,13 +785,11 @@ class LibrarySync(threading.Thread):
if update_embydb: if update_embydb:
update_embydb = False update_embydb = False
log.info("Updating emby database.") log.info("Updating emby database.")
embyconn.commit()
self.saveLastSync() self.saveLastSync()
if self.forceLibraryUpdate: if self.forceLibraryUpdate:
# Force update the Kodi library # Force update the Kodi library
self.forceLibraryUpdate = False self.forceLibraryUpdate = False
self.dbCommit(kodiconn)
log.info("Updating video library.") log.info("Updating video library.")
window('emby_kodiScan', value="true") window('emby_kodiScan', value="true")
@ -824,9 +798,6 @@ class LibrarySync(threading.Thread):
if pDialog: if pDialog:
pDialog.close() pDialog.close()
kodicursor.close()
embycursor.close()
def compareDBVersion(self, current, minimum): def compareDBVersion(self, current, minimum):
# It returns True is database is up to date. False otherwise. # It returns True is database is up to date. False otherwise.
@ -849,7 +820,7 @@ class LibrarySync(threading.Thread):
def _verify_emby_database(self): def _verify_emby_database(self):
# Create the tables for the emby database # Create the tables for the emby database
with self.database('emby') as conn: with DatabaseConn('emby') as conn:
with closing(conn.cursor()) as cursor: with closing(conn.cursor()) as cursor:
# emby, view, version # emby, view, version
cursor.execute( cursor.execute(
@ -907,18 +878,18 @@ class LibrarySync(threading.Thread):
if (window('emby_dbCheck') != "true" and settings('SyncInstallRunDone') == "true"): if (window('emby_dbCheck') != "true" and settings('SyncInstallRunDone') == "true"):
# Verify the validity of the database # Verify the validity of the database
log.info("Doing DB Version Check")
with DatabaseConn('emby') as conn:
with closing(conn.cursor()) as cursor:
embyconn = utils.kodiSQL('emby') emby_db = embydb.Embydb_Functions(cursor)
embycursor = embyconn.cursor()
emby_db = embydb.Embydb_Functions(embycursor)
currentVersion = emby_db.get_version() currentVersion = emby_db.get_version()
###$ Begin migration $### ###$ Begin migration $###
if not currentVersion: if not currentVersion:
currentVersion = emby_db.get_version(settings('dbCreatedWithVersion') or self.clientInfo.get_version()) currentVersion = emby_db.get_version(settings('dbCreatedWithVersion') or self.clientInfo.get_version())
embyconn.commit()
log.info("Migration of database version completed") log.info("Migration of database version completed")
###$ End migration $### ###$ End migration $###
embycursor.close()
window('emby_version', value=currentVersion) window('emby_version', value=currentVersion)
minVersion = window('emby_minDBVersion') minVersion = window('emby_minDBVersion')