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

Revision 3531, 4.8 kB (checked in by jerome, 14 years ago)

Fix which fixes 56 for good. References 60.

  • 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-2009 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        self.doModify = self.doQuery
41        self.tool.logdebug("Trying to open database (dbname=%s)..." % repr(dbname))
42        self.database = sqlite.connect(dbname, isolation_level=None)
43        self.cursor = self.database.cursor()
44        self.closed = False
45        try :
46            self.doQuery("PRAGMA foreign_keys = True;")
47        except PyKotaStorageError :
48            pass
49        self.tool.logdebug("Database opened (dbname=%s)" % repr(dbname))
50
51    def close(self) :
52        """Closes the database connection."""
53        if not self.closed :
54            self.cursor.close()
55            self.database.close()
56            self.closed = True
57            self.tool.logdebug("Database closed.")
58
59    def beginTransaction(self) :
60        """Starts a transaction."""
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        self.tool.logdebug("Transaction committed.")
68
69    def rollbackTransaction(self) :
70        """Rollbacks a transaction."""
71        self.cursor.execute("ROLLBACK;")
72        self.tool.logdebug("Transaction aborted.")
73
74    def doQuery(self, query) :
75        """Executes an SQL query."""
76        query = query.strip()
77        if not query.endswith(';') :
78            query += ';'
79        self.querydebug("QUERY : %s" % query)
80        try :
81            self.cursor.execute(query)
82        except self.database.Error, msg :
83            self.tool.logdebug("Query failed : %s" % repr(msg))
84            raise PyKotaStorageError, repr(msg)
85
86    def doRawSearch(self, query) :
87        """Executes a raw search query."""
88        self.doQuery(query)
89        result = self.cursor.fetchall()
90        return result
91
92    def doSearch(self, query) :
93        """Does a search query."""
94        result = self.doRawSearch(query)
95        if result :
96            rows = []
97            fields = {}
98            for i in range(len(self.cursor.description)) :
99                fields[i] = self.cursor.description[i][0]
100            for row in result :
101                rowdict = {}
102                for field in fields.keys() :
103                    value = row[field]
104                    try :
105                        value = value.encode("UTF-8")
106                    except :
107                        pass
108                    rowdict[fields[field]] = value
109                rows.append(rowdict)
110            return rows
111
112    def doQuote(self, field) :
113        """Quotes a field for use as a string in SQL queries."""
114        if type(field) == type(0.0) :
115            return field
116        elif type(field) == type(0) :
117            return field
118        elif type(field) == type(0L) :
119            return field
120        elif field is not None :
121            return ("'%s'" % field.replace("'", "''"))
122        else :
123            return "NULL"
124
125    def prepareRawResult(self, result) :
126        """Prepares a raw result by including the headers."""
127        if result :
128            entries = [tuple([f[0] for f in self.cursor.description])]
129            for entry in result :
130                row = []
131                for value in entry :
132                    try :
133                        value = value.encode("UTF-8")
134                    except :
135                        pass
136                    row.append(value)
137                entries.append(tuple(row))
138            return entries
Note: See TracBrowser for help on using the browser.