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 MySQL database backend.""" |
---|
24 | |
---|
25 | from pykota.errors import PyKotaStorageError |
---|
26 | from pykota.storage import BaseStorage |
---|
27 | from pykota.storages.sql import SQLStorage |
---|
28 | |
---|
29 | try : |
---|
30 | import MySQLdb |
---|
31 | except 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 MySQL module installed correctly." % sys.version.split()[0] |
---|
35 | |
---|
36 | class Storage(BaseStorage, SQLStorage) : |
---|
37 | def __init__(self, pykotatool, host, dbname, user, passwd) : |
---|
38 | """Opens the MySQL database connection.""" |
---|
39 | BaseStorage.__init__(self, pykotatool) |
---|
40 | try : |
---|
41 | (host, port) = host.split(":") |
---|
42 | port = int(port) |
---|
43 | except ValueError : |
---|
44 | port = 3306 # Use the default MySQL port |
---|
45 | |
---|
46 | self.tool.logdebug("Trying to open database (host=%s, port=%s, dbname=%s, user=%s)..." \ |
---|
47 | % (repr(host), |
---|
48 | repr(port), |
---|
49 | repr(dbname), |
---|
50 | repr(user))) |
---|
51 | try : |
---|
52 | self.database = MySQLdb.connect(host=host, |
---|
53 | port=port, |
---|
54 | db=dbname, |
---|
55 | user=user, |
---|
56 | passwd=passwd, |
---|
57 | charset="utf8") |
---|
58 | except TypeError : |
---|
59 | self.tool.logdebug("'charset' argument not allowed with this version of python-mysqldb, retrying without...") |
---|
60 | self.database = MySQLdb.connect(host=host, |
---|
61 | port=port, |
---|
62 | db=dbname, |
---|
63 | user=user, |
---|
64 | passwd=passwd) |
---|
65 | |
---|
66 | try : |
---|
67 | self.database.autocommit(1) |
---|
68 | except AttributeError : |
---|
69 | raise PyKotaStorageError, _("Your version of python-mysqldb is too old. Please install a newer release.") |
---|
70 | self.cursor = self.database.cursor() |
---|
71 | self.cursor.execute("SET NAMES 'utf8';") |
---|
72 | self.cursor.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED;") # Same as PostgreSQL and Oracle's default |
---|
73 | self.closed = False |
---|
74 | self.tool.logdebug("Database opened (host=%s, port=%s, dbname=%s, user=%s)" \ |
---|
75 | % (repr(host), |
---|
76 | repr(port), |
---|
77 | repr(dbname), |
---|
78 | repr(user))) |
---|
79 | try : |
---|
80 | # Here we try to select a string (an é) which is |
---|
81 | # already encoded in UTF-8. If python-mysqldb suffers from |
---|
82 | # the double encoding problem, we will catch the exception |
---|
83 | # and activate a workaround. |
---|
84 | self.cursor.execute("SELECT '%s';" % (chr(0xc3) + chr(0xa9))) # é in UTF-8 |
---|
85 | self.cursor.fetchall() |
---|
86 | except UnicodeDecodeError : |
---|
87 | self.needsworkaround = True |
---|
88 | self.tool.logdebug("Database needs encoding workaround.") |
---|
89 | else : |
---|
90 | self.needsworkaround = False |
---|
91 | self.tool.logdebug("Database doesn't need encoding workaround.") |
---|
92 | |
---|
93 | def close(self) : |
---|
94 | """Closes the database connection.""" |
---|
95 | if not self.closed : |
---|
96 | self.cursor.close() |
---|
97 | self.database.close() |
---|
98 | self.closed = True |
---|
99 | self.tool.logdebug("Database closed.") |
---|
100 | |
---|
101 | def beginTransaction(self) : |
---|
102 | """Starts a transaction.""" |
---|
103 | self.cursor.execute("BEGIN;") |
---|
104 | self.tool.logdebug("Transaction begins...") |
---|
105 | |
---|
106 | def commitTransaction(self) : |
---|
107 | """Commits a transaction.""" |
---|
108 | self.database.commit() |
---|
109 | self.tool.logdebug("Transaction committed.") |
---|
110 | |
---|
111 | def rollbackTransaction(self) : |
---|
112 | """Rollbacks a transaction.""" |
---|
113 | self.database.rollback() |
---|
114 | self.tool.logdebug("Transaction aborted.") |
---|
115 | |
---|
116 | def doRawSearch(self, query) : |
---|
117 | """Does a raw search query.""" |
---|
118 | query = query.strip() |
---|
119 | if not query.endswith(';') : |
---|
120 | query += ';' |
---|
121 | self.querydebug("QUERY : %s" % query) |
---|
122 | if self.needsworkaround : |
---|
123 | query = query.decode("UTF-8") |
---|
124 | try : |
---|
125 | self.cursor.execute(query) |
---|
126 | except self.database.Error, msg : |
---|
127 | raise PyKotaStorageError, repr(msg) |
---|
128 | else : |
---|
129 | # This returns a list of lists. Integers are returned as longs. |
---|
130 | return self.cursor.fetchall() |
---|
131 | |
---|
132 | def doSearch(self, query) : |
---|
133 | """Does a search query.""" |
---|
134 | result = self.doRawSearch(query) |
---|
135 | if result : |
---|
136 | rows = [] |
---|
137 | fields = {} |
---|
138 | for i in range(len(self.cursor.description)) : |
---|
139 | fields[i] = self.cursor.description[i][0] |
---|
140 | for row in result : |
---|
141 | rowdict = {} |
---|
142 | for field in fields.keys() : |
---|
143 | rowdict[fields[field]] = row[field] |
---|
144 | rows.append(rowdict) |
---|
145 | # returns a list of dicts |
---|
146 | return rows |
---|
147 | |
---|
148 | def doModify(self, query) : |
---|
149 | """Does a (possibly multiple) modify query.""" |
---|
150 | query = query.strip() |
---|
151 | if not query.endswith(';') : |
---|
152 | query += ';' |
---|
153 | self.querydebug("QUERY : %s" % query) |
---|
154 | if self.needsworkaround : |
---|
155 | query = query.decode("UTF-8") |
---|
156 | try : |
---|
157 | self.cursor.execute(query) |
---|
158 | except self.database.Error, msg : |
---|
159 | self.tool.logdebug("Query failed : %s" % repr(msg)) |
---|
160 | raise PyKotaStorageError, repr(msg) |
---|
161 | |
---|
162 | def doQuote(self, field) : |
---|
163 | """Quotes a field for use as a string in SQL queries.""" |
---|
164 | if type(field) == type(0.0) : |
---|
165 | return field |
---|
166 | elif type(field) == type(0) : |
---|
167 | return field |
---|
168 | elif type(field) == type(0L) : |
---|
169 | return field |
---|
170 | elif field is not None : |
---|
171 | return self.database.string_literal(field) |
---|
172 | else : |
---|
173 | return "NULL" |
---|
174 | |
---|
175 | def prepareRawResult(self, result) : |
---|
176 | """Prepares a raw result by including the headers.""" |
---|
177 | if result : |
---|
178 | return [tuple([f[0] for f in self.cursor.description])] \ |
---|
179 | + list(result) |
---|