From e92b0173480852c2e3e374eafdf8c2b8de1cd525 Mon Sep 17 00:00:00 2001 From: Jon Tibble Date: Tue, 15 Jun 2010 03:08:22 +0100 Subject: [PATCH] RFC PT4: The other DB plugins --- openlp/core/lib/db.py | 14 ++- openlp/plugins/custom/customplugin.py | 9 +- openlp/plugins/custom/forms/editcustomform.py | 6 +- openlp/plugins/custom/lib/__init__.py | 1 - .../plugins/custom/lib/{classes.py => db.py} | 31 ++++- openlp/plugins/custom/lib/manager.py | 117 ------------------ openlp/plugins/custom/lib/mediaitem.py | 10 +- openlp/plugins/custom/lib/meta.py | 38 ------ openlp/plugins/custom/lib/models.py | 39 ------ openlp/plugins/custom/lib/tables.py | 37 ------ openlp/plugins/songs/lib/manager.py | 3 - openlp/plugins/songs/songsplugin.py | 4 +- .../songusage/forms/songusagedetailform.py | 17 ++- openlp/plugins/songusage/lib/classes.py | 32 ----- .../songusage/lib/{models.py => db.py} | 44 +++++-- openlp/plugins/songusage/lib/manager.py | 100 +++------------ openlp/plugins/songusage/lib/meta.py | 38 ------ openlp/plugins/songusage/lib/tables.py | 39 ------ openlp/plugins/songusage/songusageplugin.py | 6 +- 19 files changed, 120 insertions(+), 465 deletions(-) rename openlp/plugins/custom/lib/{classes.py => db.py} (68%) delete mode 100644 openlp/plugins/custom/lib/manager.py delete mode 100644 openlp/plugins/custom/lib/meta.py delete mode 100644 openlp/plugins/custom/lib/models.py delete mode 100644 openlp/plugins/custom/lib/tables.py delete mode 100644 openlp/plugins/songusage/lib/classes.py rename openlp/plugins/songusage/lib/{models.py => db.py} (63%) delete mode 100644 openlp/plugins/songusage/lib/meta.py delete mode 100644 openlp/plugins/songusage/lib/tables.py diff --git a/openlp/core/lib/db.py b/openlp/core/lib/db.py index 7517998f0..4c7b1ca23 100644 --- a/openlp/core/lib/db.py +++ b/openlp/core/lib/db.py @@ -171,7 +171,7 @@ class Manager(object): Returns all the objects from the database ``object_class`` - The type of object to return + The type of objects to return ``order_by_ref`` Any parameters to order the returned objects by. Defaults to None. @@ -180,6 +180,18 @@ class Manager(object): return self.session.query(object_class).order_by(order_by_ref).all() return self.session.query(object_class).all() + def get_all_objects_filtered(self, object_class, filter_string): + """ + Returns a selection of objects from the database + + ``object_class`` + The type of objects to return + + ``filter_string`` + The filter governing selection of objects to return + """ + return self.session.query(object_class).filter(filter_string).all() + def delete_object(self, object_class, id): """ Delete an object from the database diff --git a/openlp/plugins/custom/customplugin.py b/openlp/plugins/custom/customplugin.py index 9ae208a28..92bfdadfc 100644 --- a/openlp/plugins/custom/customplugin.py +++ b/openlp/plugins/custom/customplugin.py @@ -27,7 +27,9 @@ import logging from forms import EditCustomForm from openlp.core.lib import Plugin, build_icon, PluginStatus, translate -from openlp.plugins.custom.lib import CustomManager, CustomMediaItem, CustomTab +from openlp.core.lib.db import Manager +from openlp.plugins.custom.lib import CustomMediaItem, CustomTab +from openlp.plugins.custom.lib.db import CustomSlide, init_schema log = logging.getLogger(__name__) @@ -45,7 +47,7 @@ class CustomPlugin(Plugin): def __init__(self, plugin_helpers): Plugin.__init__(self, u'Custom', u'1.9.1', plugin_helpers) self.weight = -5 - self.custommanager = CustomManager() + self.custommanager = Manager(u'custom', init_schema) self.edit_custom_form = EditCustomForm(self.custommanager) self.icon = build_icon(u':/media/media_custom.png') self.status = PluginStatus.Active @@ -75,6 +77,7 @@ class CustomPlugin(Plugin): return about_text def can_delete_theme(self, theme): - if len(self.custommanager.get_customs_for_theme(theme)) == 0: + filter = u'theme_name=%s' % theme + if not self.custommanager.get_all_objects_filtered(CustomSlide, filter): return True return False diff --git a/openlp/plugins/custom/forms/editcustomform.py b/openlp/plugins/custom/forms/editcustomform.py index 4e8b5957a..2b8a5bc03 100644 --- a/openlp/plugins/custom/forms/editcustomform.py +++ b/openlp/plugins/custom/forms/editcustomform.py @@ -29,7 +29,7 @@ from PyQt4 import QtCore, QtGui from editcustomdialog import Ui_customEditDialog from openlp.core.lib import SongXMLBuilder, SongXMLParser, Receiver, translate -from openlp.plugins.custom.lib.models import CustomSlide +from openlp.plugins.custom.lib.db import CustomSlide log = logging.getLogger(__name__) @@ -117,7 +117,7 @@ class EditCustomForm(QtGui.QDialog, Ui_customEditDialog): self.customSlide = CustomSlide() self.initialise() if id != 0: - self.customSlide = self.custommanager.get_custom(id) + self.customSlide = self.custommanager.get_object(CustomSlide, id) self.TitleEdit.setText(self.customSlide.title) self.CreditEdit.setText(self.customSlide.credits) songXML = SongXMLParser(self.customSlide.text) @@ -167,7 +167,7 @@ class EditCustomForm(QtGui.QDialog, Ui_customEditDialog): u'utf-8') self.customSlide.theme_name = unicode(self.ThemeComboBox.currentText(), u'utf-8') - self.custommanager.save_slide(self.customSlide) + self.custommanager.insert_object(self.customSlide) return True def onUpButtonPressed(self): diff --git a/openlp/plugins/custom/lib/__init__.py b/openlp/plugins/custom/lib/__init__.py index e62669ad3..0d9de3173 100644 --- a/openlp/plugins/custom/lib/__init__.py +++ b/openlp/plugins/custom/lib/__init__.py @@ -23,6 +23,5 @@ # Temple Place, Suite 330, Boston, MA 02111-1307 USA # ############################################################################### -from manager import CustomManager from mediaitem import CustomMediaItem from customtab import CustomTab diff --git a/openlp/plugins/custom/lib/classes.py b/openlp/plugins/custom/lib/db.py similarity index 68% rename from openlp/plugins/custom/lib/classes.py rename to openlp/plugins/custom/lib/db.py index 6d8c623d1..277f3a7e8 100644 --- a/openlp/plugins/custom/lib/classes.py +++ b/openlp/plugins/custom/lib/db.py @@ -22,11 +22,40 @@ # with this program; if not, write to the Free Software Foundation, Inc., 59 # # Temple Place, Suite 330, Boston, MA 02111-1307 USA # ############################################################################### +""" +The :mod:`db` module provides the database and schema that is the backend for +the Custom plugin +""" -from openlp.core.lib.db import BaseModel +from sqlalchemy import Column, Table, types +from sqlalchemy.orm import mapper + +from openlp.core.lib.db import BaseModel, init_db class CustomSlide(BaseModel): """ Custom Slide model """ pass + +def init_schema(url): + """ + Setup the custom database connection and initialise the database schema + + ``url`` + The database to setup + """ + session, metadata = init_db(url) + + custom_slide_table = Table(u'custom_slide', metadata, + Column(u'id', types.Integer(), primary_key=True), + Column(u'title', types.Unicode(255), nullable=False), + Column(u'text', types.UnicodeText, nullable=False), + Column(u'credits', types.UnicodeText), + Column(u'theme_name', types.Unicode(128)) + ) + + mapper(CustomSlide, custom_slide_table) + + metadata.create_all(checkfirst=True) + return session diff --git a/openlp/plugins/custom/lib/manager.py b/openlp/plugins/custom/lib/manager.py deleted file mode 100644 index 793cd8699..000000000 --- a/openlp/plugins/custom/lib/manager.py +++ /dev/null @@ -1,117 +0,0 @@ -# -*- coding: utf-8 -*- -# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4 - -############################################################################### -# OpenLP - Open Source Lyrics Projection # -# --------------------------------------------------------------------------- # -# Copyright (c) 2008-2010 Raoul Snyman # -# Portions copyright (c) 2008-2010 Tim Bentley, Jonathan Corwin, Michael # -# Gorven, Scott Guerrieri, Christian Richter, Maikel Stuivenberg, Martin # -# Thompson, Jon Tibble, Carsten Tinggaard # -# --------------------------------------------------------------------------- # -# This program is free software; you can redistribute it and/or modify it # -# under the terms of the GNU General Public License as published by the Free # -# Software Foundation; version 2 of the License. # -# # -# This program is distributed in the hope that it will be useful, but WITHOUT # -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # -# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # -# more details. # -# # -# You should have received a copy of the GNU General Public License along # -# with this program; if not, write to the Free Software Foundation, Inc., 59 # -# Temple Place, Suite 330, Boston, MA 02111-1307 USA # -############################################################################### - -import logging - -from PyQt4 import QtCore -from sqlalchemy.exceptions import InvalidRequestError - -from openlp.core.utils import AppLocation -from openlp.plugins.custom.lib.models import init_models, metadata, CustomSlide - -log = logging.getLogger(__name__) - -class CustomManager(object): - """ - The Song Manager provides a central location for all database code. This - class takes care of connecting to the database and running all the queries. - """ - log.info(u'Custom manager loaded') - - def __init__(self): - """ - Creates the connection to the database, and creates the tables if they - don't exist. - """ - log.debug(u'Custom Initialising') - settings = QtCore.QSettings() - settings.beginGroup(u'custom') - self.db_url = u'' - db_type = unicode( - settings.value(u'db type', QtCore.QVariant(u'sqlite')).toString()) - if db_type == u'sqlite': - self.db_url = u'sqlite:///%s/custom.sqlite' % \ - AppLocation.get_section_data_path(u'custom') - else: - self.db_url = u'%s://%s:%s@%s/%s' % (db_type, - unicode(settings.value(u'db username').toString()), - unicode(settings.value(u'db password').toString()), - unicode(settings.value(u'db hostname').toString()), - unicode(settings.value(u'db database').toString())) - self.session = init_models(self.db_url) - metadata.create_all(checkfirst=True) - settings.endGroup() - log.debug(u'Custom Initialised') - - def get_all_slides(self): - """ - Returns the details of a Custom Slide Show - """ - return self.session.query(CustomSlide).order_by(CustomSlide.title).all() - - def save_slide(self, customslide): - """ - Saves a Custom slide show to the database - """ - log.debug(u'Custom Slide added') - try: - self.session.add(customslide) - self.session.commit() - log.debug(u'Custom Slide saved') - return True - except InvalidRequestError: - self.session.rollback() - log.exception(u'Custom Slide save failed') - return False - - def get_custom(self, id=None): - """ - Returns the details of a Custom Slide - """ - if id is None: - return CustomSlide() - else: - return self.session.query(CustomSlide).get(id) - - def delete_custom(self, id): - """ - Delete a Custom slide show - """ - if id != 0: - customslide = self.get_custom(id) - try: - self.session.delete(customslide) - self.session.commit() - return True - except InvalidRequestError: - self.session.rollback() - log.exception(u'Custom Slide deleton failed') - return False - else: - return True - - def get_customs_for_theme(self, theme): - return self.session.query( - CustomSlide).filter(CustomSlide.theme_name == theme).all() diff --git a/openlp/plugins/custom/lib/mediaitem.py b/openlp/plugins/custom/lib/mediaitem.py index 581334410..18f681489 100644 --- a/openlp/plugins/custom/lib/mediaitem.py +++ b/openlp/plugins/custom/lib/mediaitem.py @@ -29,6 +29,7 @@ from PyQt4 import QtCore, QtGui from openlp.core.lib import MediaManagerItem, SongXMLParser, BaseListWithDnD, \ Receiver, ItemCapabilities, translate +from openlp.plugins.custom.lib.db import CustomSlide log = logging.getLogger(__name__) @@ -72,7 +73,8 @@ class CustomMediaItem(MediaManagerItem): MediaManagerItem.requiredIcons(self) def initialise(self): - self.loadCustomListView(self.parent.custommanager.get_all_slides()) + self.loadCustomListView(self.parent.custommanager.get_all_objects( + CustomSlide, CustomSlide.title)) #Called to redisplay the song list screen edith from a search #or from the exit of the Song edit dialog. If remote editing is active #Trigger it and clean up so it will not update again. @@ -106,7 +108,7 @@ class CustomMediaItem(MediaManagerItem): type of display is required. """ fields = customid.split(u':') - valid = self.parent.custommanager.get_custom(fields[1]) + valid = self.parent.custommanager.get_object(CustomSlide, fields[1]) if valid: self.remoteCustom = fields[1] self.remoteTriggered = fields[0] @@ -126,7 +128,7 @@ class CustomMediaItem(MediaManagerItem): item = self.ListView.currentItem() if item: item_id = (item.data(QtCore.Qt.UserRole)).toInt()[0] - self.parent.custommanager.delete_custom(item_id) + self.parent.custommanager.delete_object(CustomSlide, item_id) row = self.ListView.row(item) self.ListView.takeItem(row) @@ -148,7 +150,7 @@ class CustomMediaItem(MediaManagerItem): service_item.add_capability(ItemCapabilities.AllowsEdit) service_item.add_capability(ItemCapabilities.AllowsPreview) service_item.add_capability(ItemCapabilities.AllowsLoop) - customSlide = self.parent.custommanager.get_custom(item_id) + customSlide = self.parent.custommanager.get_object(CustomSlide, item_id) title = customSlide.title credit = customSlide.credits service_item.editId = item_id diff --git a/openlp/plugins/custom/lib/meta.py b/openlp/plugins/custom/lib/meta.py deleted file mode 100644 index affa31969..000000000 --- a/openlp/plugins/custom/lib/meta.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4 - -############################################################################### -# OpenLP - Open Source Lyrics Projection # -# --------------------------------------------------------------------------- # -# Copyright (c) 2008-2010 Raoul Snyman # -# Portions copyright (c) 2008-2010 Tim Bentley, Jonathan Corwin, Michael # -# Gorven, Scott Guerrieri, Christian Richter, Maikel Stuivenberg, Martin # -# Thompson, Jon Tibble, Carsten Tinggaard # -# --------------------------------------------------------------------------- # -# This program is free software; you can redistribute it and/or modify it # -# under the terms of the GNU General Public License as published by the Free # -# Software Foundation; version 2 of the License. # -# # -# This program is distributed in the hope that it will be useful, but WITHOUT # -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # -# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # -# more details. # -# # -# You should have received a copy of the GNU General Public License along # -# with this program; if not, write to the Free Software Foundation, Inc., 59 # -# Temple Place, Suite 330, Boston, MA 02111-1307 USA # -############################################################################### - -from sqlalchemy import MetaData - -__all__ = ['session', 'metadata', 'engine'] - -# SQLAlchemy database engine. Updated by model.init_model() -engine = None - -# SQLAlchemy session manager. Updated by model.init_model() -session = None - -# Global metadata. If you have multiple databases with overlapping table -# names, you'll need a metadata for each database -metadata = MetaData() diff --git a/openlp/plugins/custom/lib/models.py b/openlp/plugins/custom/lib/models.py deleted file mode 100644 index 3bd2886bd..000000000 --- a/openlp/plugins/custom/lib/models.py +++ /dev/null @@ -1,39 +0,0 @@ -# -*- coding: utf-8 -*- -# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4 - -############################################################################### -# OpenLP - Open Source Lyrics Projection # -# --------------------------------------------------------------------------- # -# Copyright (c) 2008-2010 Raoul Snyman # -# Portions copyright (c) 2008-2010 Tim Bentley, Jonathan Corwin, Michael # -# Gorven, Scott Guerrieri, Christian Richter, Maikel Stuivenberg, Martin # -# Thompson, Jon Tibble, Carsten Tinggaard # -# --------------------------------------------------------------------------- # -# This program is free software; you can redistribute it and/or modify it # -# under the terms of the GNU General Public License as published by the Free # -# Software Foundation; version 2 of the License. # -# # -# This program is distributed in the hope that it will be useful, but WITHOUT # -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # -# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # -# more details. # -# # -# You should have received a copy of the GNU General Public License along # -# with this program; if not, write to the Free Software Foundation, Inc., 59 # -# Temple Place, Suite 330, Boston, MA 02111-1307 USA # -############################################################################### - -from sqlalchemy import create_engine -from sqlalchemy.orm import scoped_session, sessionmaker, mapper - -from openlp.plugins.custom.lib.meta import metadata -from openlp.plugins.custom.lib.tables import * -from openlp.plugins.custom.lib.classes import * - -def init_models(url): - engine = create_engine(url) - metadata.bind = engine - session = scoped_session(sessionmaker(autoflush=True, autocommit=False, - bind=engine)) - mapper(CustomSlide, custom_slide_table) - return session diff --git a/openlp/plugins/custom/lib/tables.py b/openlp/plugins/custom/lib/tables.py deleted file mode 100644 index bb86d9d6d..000000000 --- a/openlp/plugins/custom/lib/tables.py +++ /dev/null @@ -1,37 +0,0 @@ -# -*- coding: utf-8 -*- -# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4 - -############################################################################### -# OpenLP - Open Source Lyrics Projection # -# --------------------------------------------------------------------------- # -# Copyright (c) 2008-2010 Raoul Snyman # -# Portions copyright (c) 2008-2010 Tim Bentley, Jonathan Corwin, Michael # -# Gorven, Scott Guerrieri, Christian Richter, Maikel Stuivenberg, Martin # -# Thompson, Jon Tibble, Carsten Tinggaard # -# --------------------------------------------------------------------------- # -# This program is free software; you can redistribute it and/or modify it # -# under the terms of the GNU General Public License as published by the Free # -# Software Foundation; version 2 of the License. # -# # -# This program is distributed in the hope that it will be useful, but WITHOUT # -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # -# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # -# more details. # -# # -# You should have received a copy of the GNU General Public License along # -# with this program; if not, write to the Free Software Foundation, Inc., 59 # -# Temple Place, Suite 330, Boston, MA 02111-1307 USA # -############################################################################### - -from sqlalchemy import Column, Table, types - -from openlp.plugins.custom.lib.meta import metadata - -# Definition of the "custom slide" table -custom_slide_table = Table(u'custom_slide', metadata, - Column(u'id', types.Integer(), primary_key=True), - Column(u'title', types.Unicode(255), nullable=False), - Column(u'text', types.UnicodeText, nullable=False), - Column(u'credits', types.UnicodeText), - Column(u'theme_name', types.Unicode(128)) -) diff --git a/openlp/plugins/songs/lib/manager.py b/openlp/plugins/songs/lib/manager.py index 6cd9a90ad..f2edf6e75 100644 --- a/openlp/plugins/songs/lib/manager.py +++ b/openlp/plugins/songs/lib/manager.py @@ -132,6 +132,3 @@ class SongManager(Manager): Get book by name """ return self.session.query(Book).filter_by(name=name).first() - - def get_songs_for_theme(self, theme): - return self.session.query(Song).filter(Song.theme_name == theme).all() diff --git a/openlp/plugins/songs/songsplugin.py b/openlp/plugins/songs/songsplugin.py index b7ddd473e..45ee4fe46 100644 --- a/openlp/plugins/songs/songsplugin.py +++ b/openlp/plugins/songs/songsplugin.py @@ -187,7 +187,7 @@ class SongsPlugin(Plugin): return about_text def can_delete_theme(self, theme): - if len(self.manager.get_songs_for_theme(theme)) == 0: + filter = u'theme_name=%s' % theme + if not self.manager.get_all_objects_filtered(Song, filter): return True return False - diff --git a/openlp/plugins/songusage/forms/songusagedetailform.py b/openlp/plugins/songusage/forms/songusagedetailform.py index fb1d1c73d..bb19bc2e6 100644 --- a/openlp/plugins/songusage/forms/songusagedetailform.py +++ b/openlp/plugins/songusage/forms/songusagedetailform.py @@ -71,20 +71,19 @@ class SongUsageDetailForm(QtGui.QDialog, Ui_SongUsageDetailDialog): def accept(self): log.debug(u'Detailed report generated') - filename = u'usage_detail_%s_%s.txt' % \ - (self.FromDate.selectedDate().toString(u'ddMMyyyy'), - self.ToDate.selectedDate().toString(u'ddMMyyyy')) - usage = self.parent.songusagemanager.get_all_songusage(\ - self.FromDate.selectedDate(), \ - self.ToDate.selectedDate()) + filename = u'usage_detail_%s_%s.txt' % ( + self.FromDate.selectedDate().toString(u'ddMMyyyy'), + self.ToDate.selectedDate().toString(u'ddMMyyyy')) + usage = self.parent.songusagemanager.get_songusage_for_period( + self.FromDate.selectedDate(), self.ToDate.selectedDate()) outname = os.path.join(unicode(self.FileLineEdit.text()), filename) file = None try: file = open(outname, u'w') for instance in usage: - record = u'\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"\n' % \ - (instance.usagedate,instance.usagetime, instance.title, - instance.copyright, instance.ccl_number , instance.authors) + record = u'\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"\n' % ( + instance.usagedate, instance.usagetime, instance.title, + instance.copyright, instance.ccl_number, instance.authors) file.write(record) except IOError: log.exception(u'Failed to write out song usage records') diff --git a/openlp/plugins/songusage/lib/classes.py b/openlp/plugins/songusage/lib/classes.py deleted file mode 100644 index 885d87faf..000000000 --- a/openlp/plugins/songusage/lib/classes.py +++ /dev/null @@ -1,32 +0,0 @@ -# -*- coding: utf-8 -*- -# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4 - -############################################################################### -# OpenLP - Open Source Lyrics Projection # -# --------------------------------------------------------------------------- # -# Copyright (c) 2008-2010 Raoul Snyman # -# Portions copyright (c) 2008-2010 Tim Bentley, Jonathan Corwin, Michael # -# Gorven, Scott Guerrieri, Christian Richter, Maikel Stuivenberg, Martin # -# Thompson, Jon Tibble, Carsten Tinggaard # -# --------------------------------------------------------------------------- # -# This program is free software; you can redistribute it and/or modify it # -# under the terms of the GNU General Public License as published by the Free # -# Software Foundation; version 2 of the License. # -# # -# This program is distributed in the hope that it will be useful, but WITHOUT # -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # -# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # -# more details. # -# # -# You should have received a copy of the GNU General Public License along # -# with this program; if not, write to the Free Software Foundation, Inc., 59 # -# Temple Place, Suite 330, Boston, MA 02111-1307 USA # -############################################################################### - -from openlp.core.lib.db import BaseModel - -class SongUsageItem(BaseModel): - """ - Audit model - """ - pass diff --git a/openlp/plugins/songusage/lib/models.py b/openlp/plugins/songusage/lib/db.py similarity index 63% rename from openlp/plugins/songusage/lib/models.py rename to openlp/plugins/songusage/lib/db.py index a7babbaed..ffb720a58 100644 --- a/openlp/plugins/songusage/lib/models.py +++ b/openlp/plugins/songusage/lib/db.py @@ -22,18 +22,42 @@ # with this program; if not, write to the Free Software Foundation, Inc., 59 # # Temple Place, Suite 330, Boston, MA 02111-1307 USA # ############################################################################### +""" +The :mod:`db` module provides the database and schema that is the backend for +the SongUsage plugin +""" -from sqlalchemy import create_engine -from sqlalchemy.orm import scoped_session, sessionmaker, mapper +from sqlalchemy import Column, Table, types +from sqlalchemy.orm import mapper -from openlp.plugins.songusage.lib.meta import metadata -from openlp.plugins.songusage.lib.tables import * -from openlp.plugins.songusage.lib.classes import * +from openlp.core.lib.db import BaseModel, init_db + +class SongUsageItem(BaseModel): + """ + SongUsageItem model + """ + pass + +def init_schema(url): + """ + Setup the songusage database connection and initialise the database schema + + ``url`` + The database to setup + """ + session, metadata = init_db(url) + + songusage_table = Table(u'songusage_data', metadata, + Column(u'id', types.Integer(), primary_key=True), + Column(u'usagedate', types.Date, index=True, nullable=False), + Column(u'usagetime', types.Time, index=True, nullable=False), + Column(u'title', types.Unicode(255), nullable=False), + Column(u'authors', types.Unicode(255), nullable=False), + Column(u'copyright', types.Unicode(255)), + Column(u'ccl_number', types.Unicode(65)) + ) -def init_models(url): - engine = create_engine(url) - metadata.bind = engine - session = scoped_session(sessionmaker(autoflush=True, autocommit=False, - bind=engine)) mapper(SongUsageItem, songusage_table) + + metadata.create_all(checkfirst=True) return session diff --git a/openlp/plugins/songusage/lib/manager.py b/openlp/plugins/songusage/lib/manager.py index b830fdafd..363f06fb8 100644 --- a/openlp/plugins/songusage/lib/manager.py +++ b/openlp/plugins/songusage/lib/manager.py @@ -25,16 +25,14 @@ import logging -from PyQt4 import QtCore from sqlalchemy.exceptions import InvalidRequestError -from openlp.core.utils import AppLocation -from openlp.plugins.songusage.lib.models import init_models, metadata, \ - SongUsageItem +from openlp.core.lib.db import Manager +from openlp.plugins.songusage.lib.db import init_schema, SongUsageItem log = logging.getLogger(__name__) -class SongUsageManager(object): +class SongUsageManager(Manager): """ The Song Manager provides a central location for all database code. This class takes care of connecting to the database and running all the queries. @@ -47,98 +45,31 @@ class SongUsageManager(object): don't exist. """ log.debug(u'SongUsage Initialising') - settings = QtCore.QSettings() - settings.beginGroup(u'songusage') - self.db_url = u'' - db_type = unicode( - settings.value(u'db type', QtCore.QVariant(u'sqlite')).toString()) - if db_type == u'sqlite': - self.db_url = u'sqlite:///%s/songusage.sqlite' % \ - AppLocation.get_section_data_path(u'songusage') - else: - self.db_url = u'%s://%s:%s@%s/%s' % (db_type, - unicode(settings.value(u'db username', - QtCore.QVariant(u'')).toString()), - unicode(settings.value(u'db password', - QtCore.QVariant(u'')).toString()), - unicode(settings.value(u'db hostname', - QtCore.QVariant(u'')).toString()), - unicode(settings.value(u'db database', - QtCore.QVariant(u'')).toString())) - self.session = init_models(self.db_url) - metadata.create_all(checkfirst=True) - settings.endGroup() + Manager.__init__(self, u'songusage', init_schema) log.debug(u'SongUsage Initialised') - def get_all_songusage(self, start_date, end_date): + def get_songusage_for_period(self, start_date, end_date): """ - Returns the details of SongUsage + Returns the details of SongUsage for a designated time period + + ``start_date`` + The start of the period to return + + ``end_date`` + The end of the period to return """ return self.session.query(SongUsageItem) \ .filter(SongUsageItem.usagedate >= start_date.toPyDate()) \ .filter(SongUsageItem.usagedate < end_date.toPyDate()) \ - .order_by(SongUsageItem.usagedate, SongUsageItem.usagetime ).all() - - def insert_songusage(self, songusageitem): - """ - Saves an SongUsage to the database - """ - log.debug(u'SongUsage added') - try: - self.session.add(songusageitem) - self.session.commit() - return True - except InvalidRequestError: - self.session.rollback() - log.exception(u'SongUsage item failed to save') - return False - - def get_songusage(self, id=None): - """ - Returns the details of a SongUsage - """ - if id is None: - return SongUsageItem() - else: - return self.session.query(SongUsageItem).get(id) - - def delete_songusage(self, id): - """ - Delete a SongUsage record - """ - if id != 0: - songusageitem = self.get_songusage(id) - try: - self.session.delete(songusageitem) - self.session.commit() - return True - except InvalidRequestError: - self.session.rollback() - log.exception(u'SongUsage Item failed to delete') - return False - else: - return True - - def delete_all(self): - """ - Delete all Song Usage records - """ - try: - self.session.query(SongUsageItem).delete(synchronize_session=False) - self.session.commit() - return True - except InvalidRequestError: - self.session.rollback() - log.exception(u'Failed to delete all Song Usage items') - return False + .order_by(SongUsageItem.usagedate, SongUsageItem.usagetime).all() def delete_to_date(self, date): """ Delete SongUsage records before given date """ try: - self.session.query(SongUsageItem)\ - .filter(SongUsageItem.usagedate <= date)\ + self.session.query(SongUsageItem) \ + .filter(SongUsageItem.usagedate <= date) \ .delete(synchronize_session=False) self.session.commit() return True @@ -146,4 +77,3 @@ class SongUsageManager(object): self.session.rollback() log.exception(u'Failed to delete all Song Usage items to %s' % date) return False - diff --git a/openlp/plugins/songusage/lib/meta.py b/openlp/plugins/songusage/lib/meta.py deleted file mode 100644 index affa31969..000000000 --- a/openlp/plugins/songusage/lib/meta.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4 - -############################################################################### -# OpenLP - Open Source Lyrics Projection # -# --------------------------------------------------------------------------- # -# Copyright (c) 2008-2010 Raoul Snyman # -# Portions copyright (c) 2008-2010 Tim Bentley, Jonathan Corwin, Michael # -# Gorven, Scott Guerrieri, Christian Richter, Maikel Stuivenberg, Martin # -# Thompson, Jon Tibble, Carsten Tinggaard # -# --------------------------------------------------------------------------- # -# This program is free software; you can redistribute it and/or modify it # -# under the terms of the GNU General Public License as published by the Free # -# Software Foundation; version 2 of the License. # -# # -# This program is distributed in the hope that it will be useful, but WITHOUT # -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # -# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # -# more details. # -# # -# You should have received a copy of the GNU General Public License along # -# with this program; if not, write to the Free Software Foundation, Inc., 59 # -# Temple Place, Suite 330, Boston, MA 02111-1307 USA # -############################################################################### - -from sqlalchemy import MetaData - -__all__ = ['session', 'metadata', 'engine'] - -# SQLAlchemy database engine. Updated by model.init_model() -engine = None - -# SQLAlchemy session manager. Updated by model.init_model() -session = None - -# Global metadata. If you have multiple databases with overlapping table -# names, you'll need a metadata for each database -metadata = MetaData() diff --git a/openlp/plugins/songusage/lib/tables.py b/openlp/plugins/songusage/lib/tables.py deleted file mode 100644 index 008c722b1..000000000 --- a/openlp/plugins/songusage/lib/tables.py +++ /dev/null @@ -1,39 +0,0 @@ -# -*- coding: utf-8 -*- -# vim: autoindent shiftwidth=4 expandtab textwidth=80 tabstop=4 softtabstop=4 - -############################################################################### -# OpenLP - Open Source Lyrics Projection # -# --------------------------------------------------------------------------- # -# Copyright (c) 2008-2010 Raoul Snyman # -# Portions copyright (c) 2008-2010 Tim Bentley, Jonathan Corwin, Michael # -# Gorven, Scott Guerrieri, Christian Richter, Maikel Stuivenberg, Martin # -# Thompson, Jon Tibble, Carsten Tinggaard # -# --------------------------------------------------------------------------- # -# This program is free software; you can redistribute it and/or modify it # -# under the terms of the GNU General Public License as published by the Free # -# Software Foundation; version 2 of the License. # -# # -# This program is distributed in the hope that it will be useful, but WITHOUT # -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # -# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # -# more details. # -# # -# You should have received a copy of the GNU General Public License along # -# with this program; if not, write to the Free Software Foundation, Inc., 59 # -# Temple Place, Suite 330, Boston, MA 02111-1307 USA # -############################################################################### - -from sqlalchemy import Column, Table, types - -from openlp.plugins.songusage.lib.meta import metadata - -# Definition of the "songusage" table -songusage_table = Table(u'songusage_data', metadata, - Column(u'id', types.Integer(), primary_key=True), - Column(u'usagedate', types.Date, index=True, nullable=False), - Column(u'usagetime', types.Time, index=True, nullable=False), - Column(u'title', types.Unicode(255), nullable=False), - Column(u'authors', types.Unicode(255), nullable=False), - Column(u'copyright', types.Unicode(255)), - Column(u'ccl_number', types.Unicode(65)) -) diff --git a/openlp/plugins/songusage/songusageplugin.py b/openlp/plugins/songusage/songusageplugin.py index 6cbb08e1a..04292e069 100644 --- a/openlp/plugins/songusage/songusageplugin.py +++ b/openlp/plugins/songusage/songusageplugin.py @@ -23,16 +23,16 @@ # Temple Place, Suite 330, Boston, MA 02111-1307 USA # ############################################################################### -from datetime import datetime import logging +from datetime import datetime from PyQt4 import QtCore, QtGui from openlp.core.lib import Plugin, Receiver, build_icon, translate from openlp.plugins.songusage.lib import SongUsageManager from openlp.plugins.songusage.forms import SongUsageDetailForm, \ SongUsageDeleteForm -from openlp.plugins.songusage.lib.models import SongUsageItem +from openlp.plugins.songusage.lib.db import SongUsageItem log = logging.getLogger(__name__) @@ -146,7 +146,7 @@ class SongUsagePlugin(Plugin): song_usage_item.authors = u'' for author in audit[1]: song_usage_item.authors += author + u' ' - self.songusagemanager.insert_songusage(song_usage_item) + self.songusagemanager.insert_object(song_usage_item) def onSongUsageDelete(self): self.SongUsagedeleteform.exec_()