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

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

Changed license to GNU GPL v3 or later.
Changed Python source encoding from ISO-8859-15 to UTF-8 (only ASCII
was used anyway).

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