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

Revision 2773, 5.8 kB (checked in by jerome, 18 years ago)

pkusers is now optimized like pkprinters, pkbcodes and edpykota.

  • 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 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
25import time
26
27from pykota.storage import PyKotaStorageError,BaseStorage,StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageJob,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
28from pykota.storages.sql import SQLStorage
29
30try :
31    from pysqlite2 import dbapi2 as sqlite
32except ImportError :   
33    import sys
34    # TODO : to translate or not to translate ?
35    raise PyKotaStorageError, "This python version (%s) doesn't seem to have the PySQLite module installed correctly." % sys.version.split()[0]
36
37class Storage(BaseStorage, SQLStorage) :
38    def __init__(self, pykotatool, host, dbname, user, passwd) :
39        """Opens the SQLite database connection."""
40        BaseStorage.__init__(self, pykotatool)
41       
42        self.tool.logdebug("Trying to open database (dbname=%s)..." % dbname)
43        self.database = sqlite.connect(dbname, isolation_level=None)
44        self.cursor = self.database.cursor()
45        self.closed = 0
46        self.tool.logdebug("Database opened (dbname=%s)" % dbname)
47           
48    def close(self) :   
49        """Closes the database connection."""
50        if not self.closed :
51            self.cursor.close()
52            self.database.close()
53            self.closed = 1
54            self.tool.logdebug("Database closed.")
55       
56    def beginTransaction(self) :   
57        """Starts a transaction."""
58        self.before = time.time()
59        self.cursor.execute("BEGIN;")
60        self.tool.logdebug("Transaction begins...")
61       
62    def commitTransaction(self) :   
63        """Commits a transaction."""
64        self.cursor.execute("COMMIT;")
65        after = time.time()
66        self.tool.logdebug("Transaction committed.")
67        self.tool.logdebug("Transaction duration : %.4f seconds" % (after - self.before))
68       
69    def rollbackTransaction(self) :     
70        """Rollbacks a transaction."""
71        self.cursor.execute("ROLLBACK;")
72        after = time.time()
73        self.tool.logdebug("Transaction aborted.")
74        self.tool.logdebug("Transaction duration : %.4f seconds" % (after - self.before))
75       
76    def doRawSearch(self, query) :
77        """Does a raw search query."""
78        query = query.strip()   
79        if not query.endswith(';') :   
80            query += ';'
81        try :
82            before = time.time()
83            self.tool.logdebug("QUERY : %s" % query)
84            self.cursor.execute(query)
85        except self.database.Error, msg :   
86            raise PyKotaStorageError, str(msg)
87        else :   
88            result = self.cursor.fetchall()
89            after = time.time()
90            self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
91            return result
92           
93    def doSearch(self, query) :       
94        """Does a search query."""
95        result = self.doRawSearch(query)
96        if result : 
97            rows = []
98            fields = {}
99            for i in range(len(self.cursor.description)) :
100                fields[i] = self.cursor.description[i][0]
101            for row in result :   
102                rowdict = {}
103                for field in fields.keys() :
104                    value = row[field]
105                    try :
106                        value = value.encode("UTF-8")
107                    except :
108                        pass
109                    rowdict[fields[field]] = value
110                rows.append(rowdict)   
111            return rows   
112       
113    def doModify(self, query) :
114        """Does a (possibly multiple) modify query."""
115        query = query.strip()   
116        if not query.endswith(';') :   
117            query += ';'
118        try :
119            before = time.time()
120            self.tool.logdebug("QUERY : %s" % query)
121            self.cursor.execute(query)
122        except self.database.Error, msg :   
123            self.tool.logdebug("Query failed : %s" % repr(msg))
124            raise PyKotaStorageError, str(msg)
125        else :   
126            after = time.time()
127            self.tool.logdebug("Query Duration : %.4f seconds" % (after - before))
128           
129    def doQuote(self, field) :
130        """Quotes a field for use as a string in SQL queries."""
131        if type(field) == type(0.0) : 
132            return field
133        elif type(field) == type(0) :   
134            return field
135        elif type(field) == type(0L) :   
136            return field
137        elif field is not None :
138            return ("'%s'" % field.replace("'", "''")).decode("UTF-8")
139        else :     
140            return "NULL"
141           
142    def prepareRawResult(self, result) :
143        """Prepares a raw result by including the headers."""
144        if result :
145            entries = [tuple([f[0] for f in self.cursor.description])]
146            for entry in result :   
147                row = []
148                for value in entry :
149                    try :
150                        value = value.encode("UTF-8")
151                    except :
152                        pass
153                    row.append(value)
154                entries.append(tuple(row))   
155            return entries   
156       
Note: See TracBrowser for help on using the browser.