root / pykota / trunk / pykota / storages / sqlitestorage.py @ 3288

Revision 3288, 5.7 kB (checked in by jerome, 16 years ago)

Moved all exceptions definitions to a dedicated module.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
RevLine 
[3275]1# -*- coding: UTF-8 -*-
2#
3# PyKota : Print Quotas for CUPS
4#
5# (c) 2003, 2004, 2005, 2006, 2007, 2008 Jerome Alet <alet@librelogiciel.com>
6# This program is free software: you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation, either version 3 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program.  If not, see <http://www.gnu.org/licenses/>.
18#
[2591]19# $Id$
20#
21#
22
[3184]23"""This module defines a class to access to a SQLite database backend."""
24
[2741]25import time
26
[3288]27from pykota.errors import PyKotaStorageError
28from pykota.storage import BaseStorage
[2591]29from pykota.storages.sql import SQLStorage
30
31try :
32    from pysqlite2 import dbapi2 as sqlite
33except ImportError :   
34    import sys
35    # TODO : to translate or not to translate ?
36    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the PySQLite module installed correctly." % sys.version.split()[0]
37
38class Storage(BaseStorage, SQLStorage) :
39    def __init__(self, pykotatool, host, dbname, user, passwd) :
40        """Opens the SQLite database connection."""
41        BaseStorage.__init__(self, pykotatool)
42       
43        self.tool.logdebug("Trying to open database (dbname=%s)..." % dbname)
44        self.database = sqlite.connect(dbname, isolation_level=None)
45        self.cursor = self.database.cursor()
46        self.closed = 0
47        self.tool.logdebug("Database opened (dbname=%s)" % dbname)
48           
49    def close(self) :   
50        """Closes the database connection."""
51        if not self.closed :
52            self.cursor.close()
53            self.database.close()
54            self.closed = 1
55            self.tool.logdebug("Database closed.")
56       
57    def beginTransaction(self) :   
58        """Starts a transaction."""
[2741]59        self.before = time.time()
[2591]60        self.cursor.execute("BEGIN;")
61        self.tool.logdebug("Transaction begins...")
62       
63    def commitTransaction(self) :   
64        """Commits a transaction."""
65        self.cursor.execute("COMMIT;")
[2741]66        after = time.time()
[2591]67        self.tool.logdebug("Transaction committed.")
[3183]68        #self.tool.logdebug("Transaction duration : %.4f seconds" % (after - self.before))
[2591]69       
70    def rollbackTransaction(self) :     
71        """Rollbacks a transaction."""
72        self.cursor.execute("ROLLBACK;")
[2741]73        after = time.time()
[2591]74        self.tool.logdebug("Transaction aborted.")
[3183]75        #self.tool.logdebug("Transaction duration : %.4f seconds" % (after - self.before))
[2591]76       
77    def doRawSearch(self, query) :
78        """Does a raw search query."""
79        query = query.strip()   
80        if not query.endswith(';') :   
81            query += ';'
82        try :
[2741]83            before = time.time()
[2591]84            self.tool.logdebug("QUERY : %s" % query)
85            self.cursor.execute(query)
86        except self.database.Error, msg :   
87            raise PyKotaStorageError, str(msg)
88        else :   
[2741]89            result = self.cursor.fetchall()
90            after = time.time()
[3183]91            #self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
[2741]92            return result
[2591]93           
94    def doSearch(self, query) :       
95        """Does a search query."""
96        result = self.doRawSearch(query)
97        if result : 
98            rows = []
99            fields = {}
100            for i in range(len(self.cursor.description)) :
101                fields[i] = self.cursor.description[i][0]
102            for row in result :   
103                rowdict = {}
104                for field in fields.keys() :
105                    value = row[field]
106                    try :
107                        value = value.encode("UTF-8")
108                    except :
109                        pass
110                    rowdict[fields[field]] = value
111                rows.append(rowdict)   
112            return rows   
113       
114    def doModify(self, query) :
115        """Does a (possibly multiple) modify query."""
116        query = query.strip()   
117        if not query.endswith(';') :   
118            query += ';'
119        try :
[2741]120            before = time.time()
[2591]121            self.tool.logdebug("QUERY : %s" % query)
122            self.cursor.execute(query)
123        except self.database.Error, msg :   
[2773]124            self.tool.logdebug("Query failed : %s" % repr(msg))
[2591]125            raise PyKotaStorageError, str(msg)
[2741]126        else :   
127            after = time.time()
[3183]128            #self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
[2591]129           
130    def doQuote(self, field) :
131        """Quotes a field for use as a string in SQL queries."""
132        if type(field) == type(0.0) : 
133            return field
134        elif type(field) == type(0) :   
135            return field
136        elif type(field) == type(0L) :   
137            return field
138        elif field is not None :
139            return ("'%s'" % field.replace("'", "''")).decode("UTF-8")
140        else :     
141            return "NULL"
[2593]142           
143    def prepareRawResult(self, result) :
144        """Prepares a raw result by including the headers."""
145        if result :
146            entries = [tuple([f[0] for f in self.cursor.description])]
147            for entry in result :   
148                row = []
149                for value in entry :
150                    try :
151                        value = value.encode("UTF-8")
152                    except :
153                        pass
154                    row.append(value)
155                entries.append(tuple(row))   
156            return entries   
157       
Note: See TracBrowser for help on using the browser.