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

Revision 2622, 5.1 kB (checked in by jerome, 18 years ago)

Added 2006 to the copyright's years.

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