comparison MySQLdb/connections.py @ 18:d55bfb1a4701 MySQLdb

Tons of changes from major refactoring/cleanup. This is all really broken right now. In particular, all results are returned as strings.
author adustman
date Fri, 14 Mar 2008 23:06:29 +0000
parents a275593a1630
children 597efa4e0311
comparison
equal deleted inserted replaced
17:7c7a89123d65 18:d55bfb1a4701
9 9
10 """ 10 """
11 11
12 __revision__ = "$Revision$"[11:-2] 12 __revision__ = "$Revision$"[11:-2]
13 __author__ = "$Author$"[9:-2] 13 __author__ = "$Author$"[9:-2]
14
15 from MySQLdb.cursors import Cursor
16 import _mysql
17 14
18 15
19 def defaulterrorhandler(connection, cursor, errorclass, errorvalue): 16 def defaulterrorhandler(connection, cursor, errorclass, errorvalue):
20 """ 17 """
21 If cursor is not None, (errorclass, errorvalue) is appended to 18 If cursor is not None, (errorclass, errorvalue) is appended to
33 del cursor 30 del cursor
34 del connection 31 del connection
35 raise errorclass, errorvalue 32 raise errorclass, errorvalue
36 33
37 34
38 class Connection(_mysql.connection): 35 class Connection(object):
39 36
40 """MySQL Database Connection Object""" 37 """MySQL Database Connection Object"""
41 38
42 default_cursor = Cursor
43 errorhandler = defaulterrorhandler 39 errorhandler = defaulterrorhandler
44 40
45 from _mysql_exceptions import Warning, Error, InterfaceError, DataError, \ 41 from MySQLdb.exceptions import Warning, Error, InterfaceError, DataError, \
46 DatabaseError, OperationalError, IntegrityError, InternalError, \ 42 DatabaseError, OperationalError, IntegrityError, InternalError, \
47 NotSupportedError, ProgrammingError 43 NotSupportedError, ProgrammingError
48 44
49 def __init__(self, *args, **kwargs): 45 def __init__(self, *args, **kwargs):
50 """ 46 """
129 documentation for the MySQL C API for some hints on what they do. 125 documentation for the MySQL C API for some hints on what they do.
130 126
131 """ 127 """
132 from MySQLdb.constants import CLIENT, FIELD_TYPE 128 from MySQLdb.constants import CLIENT, FIELD_TYPE
133 from MySQLdb.converters import conversions 129 from MySQLdb.converters import conversions
130 from MySQLdb.cursors import Cursor
131 import _mysql
134 from weakref import proxy 132 from weakref import proxy
135 133
136 kwargs2 = kwargs.copy() 134 kwargs2 = kwargs.copy()
137 135
138 if kwargs.has_key('conv'): 136 if kwargs.has_key('conv'):
145 if isinstance(k, int): 143 if isinstance(k, int):
146 if isinstance(v, list): 144 if isinstance(v, list):
147 conv2[k] = v[:] 145 conv2[k] = v[:]
148 else: 146 else:
149 conv2[k] = v 147 conv2[k] = v
150 kwargs2['conv'] = conv2 148 #kwargs2['conv'] = conv2
151 149
152 self.cursorclass = kwargs2.pop('cursorclass', self.default_cursor) 150 self.cursorclass = kwargs2.pop('cursorclass', Cursor)
153 charset = kwargs2.pop('charset', '') 151 charset = kwargs2.pop('charset', '')
154 152
155 if charset: 153 if charset:
156 use_unicode = True 154 use_unicode = True
157 else: 155 else:
168 if client_version >= (5, 0): 166 if client_version >= (5, 0):
169 client_flag |= CLIENT.MULTI_RESULTS 167 client_flag |= CLIENT.MULTI_RESULTS
170 168
171 kwargs2['client_flag'] = client_flag 169 kwargs2['client_flag'] = client_flag
172 170
173 super(Connection, self).__init__(*args, **kwargs2) 171 self._db = _mysql.connection(*args, **kwargs2)
174 172
175 self.encoders = dict( 173 self.encoders = dict(
176 [ (k, v) for k, v in conv.items() 174 [ (k, v) for k, v in conv.items()
177 if type(k) is not int ]) 175 if type(k) is not int ])
178 176
179 self._server_version = tuple( 177 self._server_version = tuple(
180 [ int(n) for n in self.get_server_info().split('.')[:2] ]) 178 [ int(n) for n in self._db.get_server_info().split('.')[:2] ])
181 179
182 db = proxy(self) 180 db = proxy(self)
183 def _get_string_literal(): 181 def _get_string_literal():
184 def string_literal(obj, dummy=None): 182 def string_literal(obj, dummy=None):
185 return db.string_literal(obj) 183 return self._db.string_literal(obj)
186 return string_literal 184 return string_literal
187 185
188 def _get_unicode_literal(): 186 def _get_unicode_literal():
189 def unicode_literal(u, dummy=None): 187 def unicode_literal(u, dummy=None):
190 return db.literal(u.encode(unicode_literal.charset)) 188 return self.literal(u.encode(unicode_literal.charset))
191 return unicode_literal 189 return unicode_literal
192 190
193 def _get_string_decoder(): 191 def _get_string_decoder():
194 def string_decoder(s): 192 def string_decoder(s):
195 return s.decode(string_decoder.charset) 193 return s.decode(string_decoder.charset)
197 195
198 string_literal = _get_string_literal() 196 string_literal = _get_string_literal()
199 self.unicode_literal = unicode_literal = _get_unicode_literal() 197 self.unicode_literal = unicode_literal = _get_unicode_literal()
200 self.string_decoder = string_decoder = _get_string_decoder() 198 self.string_decoder = string_decoder = _get_string_decoder()
201 if not charset: 199 if not charset:
202 charset = self.character_set_name() 200 charset = self._db.character_set_name()
203 self.set_character_set(charset) 201 self._db.set_character_set(charset)
204 202
205 if sql_mode: 203 if sql_mode:
206 self.set_sql_mode(sql_mode) 204 self.set_sql_mode(sql_mode)
207 205
208 if use_unicode: 206 #if use_unicode:
209 self.converter[FIELD_TYPE.STRING].append((None, string_decoder)) 207 #self._db.converter[FIELD_TYPE.STRING].append((None, string_decoder))
210 self.converter[FIELD_TYPE.VAR_STRING].append((None, string_decoder)) 208 #self._db.converter[FIELD_TYPE.VAR_STRING].append((None, string_decoder))
211 self.converter[FIELD_TYPE.VARCHAR].append((None, string_decoder)) 209 #self._db.converter[FIELD_TYPE.VARCHAR].append((None, string_decoder))
212 self.converter[FIELD_TYPE.BLOB].append((None, string_decoder)) 210 #self._db.converter[FIELD_TYPE.BLOB].append((None, string_decoder))
213 211
214 self.encoders[str] = string_literal 212 self.encoders[str] = string_literal
215 self.encoders[unicode] = unicode_literal 213 self.encoders[unicode] = unicode_literal
216 self._transactional = self.server_capabilities & CLIENT.TRANSACTIONS 214 string_decoder.charset = charset
215 unicode_literal.charset = charset
216 self._transactional = self._db.server_capabilities & CLIENT.TRANSACTIONS
217 if self._transactional: 217 if self._transactional:
218 # PEP-249 requires autocommit to be initially off 218 # PEP-249 requires autocommit to be initially off
219 self.autocommit(False) 219 self.autocommit(False)
220 self.messages = [] 220 self.messages = []
221 221
222 def autocommit(self, do_autocommit):
223 return self._db.autocommit(do_autocommit)
224
225 def commit(self):
226 return self._db.commit()
227
228 def rollback(self):
229 return self._db.rollback()
230
231 def close(self):
232 return self._db.close()
233
222 def cursor(self, cursorclass=None): 234 def cursor(self, cursorclass=None):
223 """ 235 """
224 Create a cursor on which queries may be performed. The optional 236 Create a cursor on which queries may be performed. The optional
225 cursorclass parameter is used to create the Cursor. By default, 237 cursorclass parameter is used to create the Cursor. By default,
226 self.cursorclass=cursors.Cursor is used. 238 self.cursorclass=cursors.Cursor is used.
242 obj is a non-string sequence, the items of the sequence are converted 254 obj is a non-string sequence, the items of the sequence are converted
243 and returned as a sequence. 255 and returned as a sequence.
244 256
245 Non-standard. For internal use; do not use this in your applications. 257 Non-standard. For internal use; do not use this in your applications.
246 """ 258 """
247 return self.escape(obj, self.encoders) 259 return self._db.escape(obj, self.encoders)
248 260
249 if not hasattr(_mysql.connection, 'warning_count'): 261 def _warning_count(self):
250 262 """Return the number of warnings generated from the last query."""
251 def warning_count(self): 263 if hasattr(self._db, "warning_count"):
252 """Return the number of warnings generated from the last query. 264 return self._db.warning_count()
253 This is derived from the info() method.""" 265 else:
254 info = self.info() 266 info = self._db.info()
255 if info: 267 if info:
256 return int(info.split()[-1]) 268 return int(info.split()[-1])
257 else: 269 else:
258 return 0 270 return 0
259 271 def character_set_name(self):
272 return self._db.character_set_name()
273
260 def set_character_set(self, charset): 274 def set_character_set(self, charset):
261 """Set the connection character set to charset. The character set can 275 """Set the connection character set to charset. The character set can
262 only be changed in MySQL-4.1 and newer. If you try to change the 276 only be changed in MySQL-4.1 and newer. If you try to change the
263 character set from the current value in an older version, 277 character set from the current value in an older version,
264 NotSupportedError will be raised. 278 NotSupportedError will be raised.
265 279
266 Non-standard. It is better to set the character set when creating the 280 Non-standard. It is better to set the character set when creating the
267 connection using the charset parameter.""" 281 connection using the charset parameter."""
268 if self.character_set_name() != charset: 282 if self.character_set_name() != charset:
269 try: 283 try:
270 super(Connection, self).set_character_set(charset) 284 self._db.set_character_set(charset)
271 except AttributeError: 285 except AttributeError:
272 if self._server_version < (4, 1): 286 if self._server_version < (4, 1):
273 raise self.NotSupportedError, "server is too old to set charset" 287 raise self.NotSupportedError, "server is too old to set charset"
274 self.query('SET NAMES %s' % charset) 288 self._db.query('SET NAMES %s' % charset)
275 self.store_result() 289 self._db.store_result()
276 self.string_decoder.charset = charset 290 self.string_decoder.charset = charset
277 self.unicode_literal.charset = charset 291 self.unicode_literal.charset = charset
278 292
279 def set_sql_mode(self, sql_mode): 293 def set_sql_mode(self, sql_mode):
280 """Set the connection sql_mode. See MySQL documentation for legal 294 """Set the connection sql_mode. See MySQL documentation for legal
282 296
283 Non-standard. It is better to set this when creating the connection 297 Non-standard. It is better to set this when creating the connection
284 using the sql_mode parameter.""" 298 using the sql_mode parameter."""
285 if self._server_version < (4, 1): 299 if self._server_version < (4, 1):
286 raise self.NotSupportedError, "server is too old to set sql_mode" 300 raise self.NotSupportedError, "server is too old to set sql_mode"
287 self.query("SET SESSION sql_mode='%s'" % sql_mode) 301 self._db.query("SET SESSION sql_mode='%s'" % sql_mode)
288 self.store_result() 302 self._db.store_result()
289 303
290 def show_warnings(self): 304 def _show_warnings(self):
291 """Return detailed information about warnings as a sequence of tuples 305 """Return detailed information about warnings as a sequence of tuples
292 of (Level, Code, Message). This is only supported in MySQL-4.1 and up. 306 of (Level, Code, Message). This is only supported in MySQL-4.1 and up.
293 If your server is an earlier version, an empty sequence is returned. 307 If your server is an earlier version, an empty sequence is returned.
294 308
295 Non-standard. This is invoked automatically after executing a query, 309 Non-standard. This is invoked automatically after executing a query,
296 so you should not usually call it yourself.""" 310 so you should not usually call it yourself."""
297 if self._server_version < (4, 1): return () 311 if self._server_version < (4, 1): return ()
298 self.query("SHOW WARNINGS") 312 self._db.query("SHOW WARNINGS")
299 result = self.store_result() 313 result = self._db.store_result()
300 warnings = result.fetch_row(0) 314 warnings = result.fetch_row(0)
301 return warnings 315 return warnings
302 316