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

Revision 3413, 4.9 kB (checked in by jerome, 16 years ago)

Removed unnecessary spaces at EOL.

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