comparison MySQLdb/connections.py @ 14:7773efbe9b30 MySQLdb

Formatting and PyLint fixes. Final score: 8.21/10
author adustman
date Mon, 26 Feb 2007 18:08:28 +0000
parents 0e37ee00beb7
children a275593a1630
comparison
equal deleted inserted replaced
13:eb90cceaee92 14:7773efbe9b30
1 """ 1 """
2 MySQLdb Connections
3 -------------------
2 4
3 This module implements connections for MySQLdb. Presently there is 5 This module implements connections for MySQLdb. Presently there is
4 only one class: Connection. Others are unlikely. However, you might 6 only one class: Connection. Others are unlikely. However, you might
5 want to make your own subclasses. In most cases, you will probably 7 want to make your own subclasses. In most cases, you will probably
6 override Connection.default_cursor with a non-standard Cursor class. 8 override Connection.default_cursor with a non-standard Cursor class.
7 9
8 """ 10 """
9 import cursors 11
10 from _mysql_exceptions import Warning, Error, InterfaceError, DataError, \ 12 __revision__ = "$Revision$"[11:-2]
11 DatabaseError, OperationalError, IntegrityError, InternalError, \ 13 __author__ = "$Author$"[9:-2]
12 NotSupportedError, ProgrammingError 14
13 import types, _mysql 15 from MySQLdb.cursors import Cursor
16 import _mysql
14 17
15 18
16 def defaulterrorhandler(connection, cursor, errorclass, errorvalue): 19 def defaulterrorhandler(connection, cursor, errorclass, errorvalue):
17 """ 20 """
18
19 If cursor is not None, (errorclass, errorvalue) is appended to 21 If cursor is not None, (errorclass, errorvalue) is appended to
20 cursor.messages; otherwise it is appended to 22 cursor.messages; otherwise it is appended to connection.messages. Then
21 connection.messages. Then errorclass is raised with errorvalue as 23 errorclass is raised with errorvalue as the value.
22 the value. 24
23 25 You can override this with your own error handler by assigning it to the
24 You can override this with your own error handler by assigning it 26 instance.
25 to the instance.
26
27 """ 27 """
28 error = errorclass, errorvalue 28 error = errorclass, errorvalue
29 if cursor: 29 if cursor:
30 cursor.messages.append(error) 30 cursor.messages.append(error)
31 else: 31 else:
37 37
38 class Connection(_mysql.connection): 38 class Connection(_mysql.connection):
39 39
40 """MySQL Database Connection Object""" 40 """MySQL Database Connection Object"""
41 41
42 default_cursor = cursors.Cursor 42 default_cursor = Cursor
43 43 errorhandler = defaulterrorhandler
44
45 from _mysql_exceptions import Warning, Error, InterfaceError, DataError, \
46 DatabaseError, OperationalError, IntegrityError, InternalError, \
47 NotSupportedError, ProgrammingError
48
44 def __init__(self, *args, **kwargs): 49 def __init__(self, *args, **kwargs):
45 """ 50 """
46 51 Create a connection to the database. It is strongly recommended that
47 Create a connection to the database. It is strongly recommended 52 you only use keyword parameters. Consult the MySQL C API documentation
48 that you only use keyword parameters. Consult the MySQL C API 53 for more information.
49 documentation for more information.
50 54
51 host 55 host
52 string, host to connect 56 string, host to connect
53 57
54 user 58 user
123 127
124 There are a number of undocumented, non-standard methods. See the 128 There are a number of undocumented, non-standard methods. See the
125 documentation for the MySQL C API for some hints on what they do. 129 documentation for the MySQL C API for some hints on what they do.
126 130
127 """ 131 """
128 from constants import CLIENT, FIELD_TYPE 132 from MySQLdb.constants import CLIENT, FIELD_TYPE
129 from converters import conversions 133 from MySQLdb.converters import conversions
130 from weakref import proxy, WeakValueDictionary 134 from weakref import proxy
131 135
132 import types
133
134 kwargs2 = kwargs.copy() 136 kwargs2 = kwargs.copy()
135 137
136 if kwargs.has_key('conv'): 138 if kwargs.has_key('conv'):
137 conv = kwargs['conv'] 139 conv = kwargs['conv']
138 else: 140 else:
157 159
158 use_unicode = kwargs2.pop('use_unicode', use_unicode) 160 use_unicode = kwargs2.pop('use_unicode', use_unicode)
159 sql_mode = kwargs2.pop('sql_mode', '') 161 sql_mode = kwargs2.pop('sql_mode', '')
160 162
161 client_flag = kwargs.get('client_flag', 0) 163 client_flag = kwargs.get('client_flag', 0)
162 client_version = tuple([ int(n) for n in _mysql.get_client_info().split('.')[:2] ]) 164 client_version = tuple(
165 [ int(n) for n in _mysql.get_client_info().split('.')[:2] ])
163 if client_version >= (4, 1): 166 if client_version >= (4, 1):
164 client_flag |= CLIENT.MULTI_STATEMENTS 167 client_flag |= CLIENT.MULTI_STATEMENTS
165 if client_version >= (5, 0): 168 if client_version >= (5, 0):
166 client_flag |= CLIENT.MULTI_RESULTS 169 client_flag |= CLIENT.MULTI_RESULTS
167 170
168 kwargs2['client_flag'] = client_flag 171 kwargs2['client_flag'] = client_flag
169 172
170 super(Connection, self).__init__(*args, **kwargs2) 173 super(Connection, self).__init__(*args, **kwargs2)
171 174
172 self.encoders = dict([ (k, v) for k, v in conv.items() 175 self.encoders = dict(
173 if type(k) is not int ]) 176 [ (k, v) for k, v in conv.items()
174 177 if type(k) is not int ])
175 self._server_version = tuple([ int(n) for n in self.get_server_info().split('.')[:2] ]) 178
179 self._server_version = tuple(
180 [ int(n) for n in self.get_server_info().split('.')[:2] ])
176 181
177 db = proxy(self) 182 db = proxy(self)
178 def _get_string_literal(): 183 def _get_string_literal():
179 def string_literal(obj, dummy=None): 184 def string_literal(obj, dummy=None):
180 return db.string_literal(obj) 185 return db.string_literal(obj)
204 self.converter[FIELD_TYPE.STRING].append((None, string_decoder)) 209 self.converter[FIELD_TYPE.STRING].append((None, string_decoder))
205 self.converter[FIELD_TYPE.VAR_STRING].append((None, string_decoder)) 210 self.converter[FIELD_TYPE.VAR_STRING].append((None, string_decoder))
206 self.converter[FIELD_TYPE.VARCHAR].append((None, string_decoder)) 211 self.converter[FIELD_TYPE.VARCHAR].append((None, string_decoder))
207 self.converter[FIELD_TYPE.BLOB].append((None, string_decoder)) 212 self.converter[FIELD_TYPE.BLOB].append((None, string_decoder))
208 213
209 self.encoders[types.StringType] = string_literal 214 self.encoders[str] = string_literal
210 self.encoders[types.UnicodeType] = unicode_literal 215 self.encoders[unicode] = unicode_literal
211 self._transactional = self.server_capabilities & CLIENT.TRANSACTIONS 216 self._transactional = self.server_capabilities & CLIENT.TRANSACTIONS
212 if self._transactional: 217 if self._transactional:
213 # PEP-249 requires autocommit to be initially off 218 # PEP-249 requires autocommit to be initially off
214 self.autocommit(False) 219 self.autocommit(False)
215 self.messages = [] 220 self.messages = []
216 221
217 def cursor(self, cursorclass=None): 222 def cursor(self, cursorclass=None):
218 """ 223 """
219 224 Create a cursor on which queries may be performed. The optional
220 Create a cursor on which queries may be performed. The 225 cursorclass parameter is used to create the Cursor. By default,
221 optional cursorclass parameter is used to create the 226 self.cursorclass=cursors.Cursor is used.
222 Cursor. By default, self.cursorclass=cursors.Cursor is
223 used.
224
225 """ 227 """
226 return (cursorclass or self.cursorclass)(self) 228 return (cursorclass or self.cursorclass)(self)
227 229
228 def __enter__(self): return self.cursor() 230 def __enter__(self):
229 231 return self.cursor()
230 def __exit__(self, exc, value, tb): 232
233 def __exit__(self, exc, value, traceback):
231 if exc: 234 if exc:
232 self.rollback() 235 self.rollback()
233 else: 236 else:
234 self.commit() 237 self.commit()
235 238
236 def literal(self, o): 239 def literal(self, obj):
237 """ 240 """
238 241 If obj is a single object, returns an SQL literal as a string. If
239 If o is a single object, returns an SQL literal as a string. 242 obj is a non-string sequence, the items of the sequence are converted
240 If o is a non-string sequence, the items of the sequence are 243 and returned as a sequence.
241 converted and returned as a sequence. 244
242 245 Non-standard. For internal use; do not use this in your applications.
243 Non-standard. For internal use; do not use this in your 246 """
244 applications. 247 return self.escape(obj, self.encoders)
245 248
246 """
247 return self.escape(o, self.encoders)
248
249 def begin(self):
250 """Explicitly begin a connection. Non-standard.
251 DEPRECATED: Will be removed in 1.3.
252 Use an SQL BEGIN statement instead."""
253 from warnings import warn
254 warn("begin() is non-standard and will be removed in 1.3",
255 DeprecationWarning, 2)
256 self.query("BEGIN")
257
258 if not hasattr(_mysql.connection, 'warning_count'): 249 if not hasattr(_mysql.connection, 'warning_count'):
259 250
260 def warning_count(self): 251 def warning_count(self):
261 """Return the number of warnings generated from the 252 """Return the number of warnings generated from the last query.
262 last query. This is derived from the info() method.""" 253 This is derived from the info() method."""
263 from string import atoi
264 info = self.info() 254 info = self.info()
265 if info: 255 if info:
266 return atoi(info.split()[-1]) 256 return int(info.split()[-1])
267 else: 257 else:
268 return 0 258 return 0
269 259
270 def set_character_set(self, charset): 260 def set_character_set(self, charset):
271 """Set the connection character set to charset. The character 261 """Set the connection character set to charset. The character set can
272 set can only be changed in MySQL-4.1 and newer. If you try 262 only be changed in MySQL-4.1 and newer. If you try to change the
273 to change the character set from the current value in an 263 character set from the current value in an older version,
274 older version, NotSupportedError will be raised.""" 264 NotSupportedError will be raised."""
275 if self.character_set_name() != charset: 265 if self.character_set_name() != charset:
276 try: 266 try:
277 super(Connection, self).set_character_set(charset) 267 super(Connection, self).set_character_set(charset)
278 except AttributeError: 268 except AttributeError:
279 if self._server_version < (4, 1): 269 if self._server_version < (4, 1):
280 raise NotSupportedError, "server is too old to set charset" 270 raise self.NotSupportedError, "server is too old to set charset"
281 self.query('SET NAMES %s' % charset) 271 self.query('SET NAMES %s' % charset)
282 self.store_result() 272 self.store_result()
283 self.string_decoder.charset = charset 273 self.string_decoder.charset = charset
284 self.unicode_literal.charset = charset 274 self.unicode_literal.charset = charset
285 275
286 def set_sql_mode(self, sql_mode): 276 def set_sql_mode(self, sql_mode):
287 """Set the connection sql_mode. See MySQL documentation for 277 """Set the connection sql_mode. See MySQL documentation for legal
288 legal values.""" 278 values."""
289 if self._server_version < (4, 1): 279 if self._server_version < (4, 1):
290 raise NotSupportedError, "server is too old to set sql_mode" 280 raise self.NotSupportedError, "server is too old to set sql_mode"
291 self.query("SET SESSION sql_mode='%s'" % sql_mode) 281 self.query("SET SESSION sql_mode='%s'" % sql_mode)
292 self.store_result() 282 self.store_result()
293 283
294 def show_warnings(self): 284 def show_warnings(self):
295 """Return detailed information about warnings as a 285 """Return detailed information about warnings as a sequence of tuples
296 sequence of tuples of (Level, Code, Message). This 286 of (Level, Code, Message). This is only supported in MySQL-4.1 and up.
297 is only supported in MySQL-4.1 and up. If your server 287 If your server is an earlier version, an empty sequence is
298 is an earlier version, an empty sequence is returned.""" 288 returned."""
299 if self._server_version < (4,1): return () 289 if self._server_version < (4, 1): return ()
300 self.query("SHOW WARNINGS") 290 self.query("SHOW WARNINGS")
301 r = self.store_result() 291 result = self.store_result()
302 warnings = r.fetch_row(0) 292 warnings = result.fetch_row(0)
303 return warnings 293 return warnings
304 294
305 Warning = Warning
306 Error = Error
307 InterfaceError = InterfaceError
308 DatabaseError = DatabaseError
309 DataError = DataError
310 OperationalError = OperationalError
311 IntegrityError = IntegrityError
312 InternalError = InternalError
313 ProgrammingError = ProgrammingError
314 NotSupportedError = NotSupportedError
315
316 errorhandler = defaulterrorhandler