Skip to content

Commit f064692

Browse files
committed
'BEGIN' on __enter__ if autocommit is enabled.
1 parent 470eb56 commit f064692

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

MySQLdb/connections.py

+24-3
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,9 @@ class object, used to create cursors (keyword only)
187187

188188
kwargs2['client_flag'] = client_flag
189189

190+
# PEP-249 requires autocommit to be initially off
191+
autocommit = kwargs2.pop('autocommit', False)
192+
190193
super(Connection, self).__init__(*args, **kwargs2)
191194
self.cursorclass = cursorclass
192195
self.encoders = dict([ (k, v) for k, v in conv.items()
@@ -229,13 +232,29 @@ def string_decoder(s):
229232
self.encoders[types.StringType] = string_literal
230233
self.encoders[types.UnicodeType] = unicode_literal
231234
self._transactional = self.server_capabilities & CLIENT.TRANSACTIONS
235+
self._autocommit = None
232236
if self._transactional:
233-
# PEP-249 requires autocommit to be initially off
234-
autocommit = kwargs2.pop('autocommit', False)
235237
if autocommit is not None:
236-
self.autocommit(bool(autocommit))
238+
self.autocommit(autocommit)
237239
self.messages = []
238240

241+
def autocommit(self, on):
242+
on = bool(on)
243+
_mysql.connection.autocommit(self, on)
244+
self._autocommit = on
245+
246+
def get_autocommit(self):
247+
if self._autocommit is None:
248+
self._update_autocommit()
249+
return self._autocommit
250+
251+
def _update_autocommit(self):
252+
cursor = cursors.Cursor(self)
253+
cursor.execute("SELECT @@AUTOCOMMIT")
254+
row = cursor.fetchone()
255+
self._autocommit = bool(row[0])
256+
cursor.close()
257+
239258
def cursor(self, cursorclass=None):
240259
"""
241260
@@ -248,6 +267,8 @@ def cursor(self, cursorclass=None):
248267
return (cursorclass or self.cursorclass)(self)
249268

250269
def __enter__(self):
270+
if self.get_autocommit():
271+
self.query("BEGIN")
251272
return self.cursor()
252273

253274
def __exit__(self, exc, value, tb):

0 commit comments

Comments
 (0)