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
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)
[3531]40        self.doModify = self.doQuery
[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
[3531]45        try :
46            self.doQuery("PRAGMA foreign_keys = True;")
47        except PyKotaStorageError :
48            pass
[3419]49        self.tool.logdebug("Database opened (dbname=%s)" % repr(dbname))
[3413]50
51    def close(self) :
[2591]52        """Closes the database connection."""
53        if not self.closed :
54            self.cursor.close()
55            self.database.close()
[3419]56            self.closed = True
[2591]57            self.tool.logdebug("Database closed.")
[3413]58
59    def beginTransaction(self) :
[2591]60        """Starts a transaction."""
61        self.cursor.execute("BEGIN;")
62        self.tool.logdebug("Transaction begins...")
[3413]63
64    def commitTransaction(self) :
[2591]65        """Commits a transaction."""
66        self.cursor.execute("COMMIT;")
67        self.tool.logdebug("Transaction committed.")
[3413]68
69    def rollbackTransaction(self) :
[2591]70        """Rollbacks a transaction."""
71        self.cursor.execute("ROLLBACK;")
72        self.tool.logdebug("Transaction aborted.")
[3413]73
[3531]74    def doQuery(self, query) :
75        """Executes an SQL query."""
[3413]76        query = query.strip()
77        if not query.endswith(';') :
[2591]78            query += ';'
[3527]79        self.querydebug("QUERY : %s" % query)
[2591]80        try :
81            self.cursor.execute(query)
[3413]82        except self.database.Error, msg :
[3531]83            self.tool.logdebug("Query failed : %s" % repr(msg))
[3308]84            raise PyKotaStorageError, repr(msg)
[3413]85
[3531]86    def doRawSearch(self, query) :
87        """Executes a raw search query."""
88        self.doQuery(query)
89        result = self.cursor.fetchall()
90        return result
91
[3413]92    def doSearch(self, query) :
[2591]93        """Does a search query."""
94        result = self.doRawSearch(query)
[3413]95        if result :
[2591]96            rows = []
97            fields = {}
98            for i in range(len(self.cursor.description)) :
99                fields[i] = self.cursor.description[i][0]
[3413]100            for row in result :
[2591]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
[3413]109                rows.append(rowdict)
110            return rows
111
[2591]112    def doQuote(self, field) :
113        """Quotes a field for use as a string in SQL queries."""
[3413]114        if type(field) == type(0.0) :
[2591]115            return field
[3413]116        elif type(field) == type(0) :
[2591]117            return field
[3413]118        elif type(field) == type(0L) :
[2591]119            return field
120        elif field is not None :
[3528]121            return ("'%s'" % field.replace("'", "''"))
[3413]122        else :
[2591]123            return "NULL"
[3413]124
[2593]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])]
[3413]129            for entry in result :
[2593]130                row = []
131                for value in entry :
132                    try :
133                        value = value.encode("UTF-8")
134                    except :
135                        pass
136                    row.append(value)
[3413]137                entries.append(tuple(row))
138            return entries
Note: See TracBrowser for help on using the browser.