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

Revision 3184, 5.8 kB (checked in by jerome, 17 years ago)

Added some docstrings.

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