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

Revision 3528, 4.9 kB (checked in by jerome, 14 years ago)

Fixes #56.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
RevLine 
[3489]1# -*- coding: utf-8 -*-
[3275]2#
3# PyKota : Print Quotas for CUPS
4#
[3481]5# (c) 2003-2009 Jerome Alet <alet@librelogiciel.com>
[3275]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.
[3413]10#
[3275]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.
[3413]15#
[3275]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#
[2591]19# $Id$
20#
21#
22
[3184]23"""This module defines a class to access to a SQLite database backend."""
24
[3288]25from pykota.errors import PyKotaStorageError
26from pykota.storage import BaseStorage
[2591]27from pykota.storages.sql import SQLStorage
28
29try :
30    from pysqlite2 import dbapi2 as sqlite
[3413]31except ImportError :
[2591]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]
[3413]35
[2591]36class Storage(BaseStorage, SQLStorage) :
37    def __init__(self, pykotatool, host, dbname, user, passwd) :
38        """Opens the SQLite database connection."""
39        BaseStorage.__init__(self, pykotatool)
[3413]40
[3419]41        self.tool.logdebug("Trying to open database (dbname=%s)..." % repr(dbname))
[2591]42        self.database = sqlite.connect(dbname, isolation_level=None)
43        self.cursor = self.database.cursor()
[3419]44        self.closed = False
45        self.tool.logdebug("Database opened (dbname=%s)" % repr(dbname))
[3413]46
47    def close(self) :
[2591]48        """Closes the database connection."""
49        if not self.closed :
50            self.cursor.close()
51            self.database.close()
[3419]52            self.closed = True
[2591]53            self.tool.logdebug("Database closed.")
[3413]54
55    def beginTransaction(self) :
[2591]56        """Starts a transaction."""
57        self.cursor.execute("BEGIN;")
58        self.tool.logdebug("Transaction begins...")
[3413]59
60    def commitTransaction(self) :
[2591]61        """Commits a transaction."""
62        self.cursor.execute("COMMIT;")
63        self.tool.logdebug("Transaction committed.")
[3413]64
65    def rollbackTransaction(self) :
[2591]66        """Rollbacks a transaction."""
67        self.cursor.execute("ROLLBACK;")
68        self.tool.logdebug("Transaction aborted.")
[3413]69
[2591]70    def doRawSearch(self, query) :
71        """Does a raw search query."""
[3413]72        query = query.strip()
73        if not query.endswith(';') :
[2591]74            query += ';'
[3527]75        self.querydebug("QUERY : %s" % query)
[2591]76        try :
77            self.cursor.execute(query)
[3413]78        except self.database.Error, msg :
[3308]79            raise PyKotaStorageError, repr(msg)
[3413]80        else :
[2741]81            result = self.cursor.fetchall()
82            return result
[3413]83
84    def doSearch(self, query) :
[2591]85        """Does a search query."""
86        result = self.doRawSearch(query)
[3413]87        if result :
[2591]88            rows = []
89            fields = {}
90            for i in range(len(self.cursor.description)) :
91                fields[i] = self.cursor.description[i][0]
[3413]92            for row in result :
[2591]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
[3413]101                rows.append(rowdict)
102            return rows
103
[2591]104    def doModify(self, query) :
105        """Does a (possibly multiple) modify query."""
[3413]106        query = query.strip()
107        if not query.endswith(';') :
[2591]108            query += ';'
[3527]109        self.querydebug("QUERY : %s" % query)
[2591]110        try :
111            self.cursor.execute(query)
[3413]112        except self.database.Error, msg :
[2773]113            self.tool.logdebug("Query failed : %s" % repr(msg))
[3308]114            raise PyKotaStorageError, repr(msg)
[3413]115
[2591]116    def doQuote(self, field) :
117        """Quotes a field for use as a string in SQL queries."""
[3413]118        if type(field) == type(0.0) :
[2591]119            return field
[3413]120        elif type(field) == type(0) :
[2591]121            return field
[3413]122        elif type(field) == type(0L) :
[2591]123            return field
124        elif field is not None :
[3528]125            return ("'%s'" % field.replace("'", "''"))
[3413]126        else :
[2591]127            return "NULL"
[3413]128
[2593]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])]
[3413]133            for entry in result :
[2593]134                row = []
135                for value in entry :
136                    try :
137                        value = value.encode("UTF-8")
138                    except :
139                        pass
140                    row.append(value)
[3413]141                entries.append(tuple(row))
142            return entries
Note: See TracBrowser for help on using the browser.