Skip to content

Commit

Permalink
Merge pull request #12 from KLab/autocommit_on
Browse files Browse the repository at this point in the history
Support keyword argument to initially autocommit=on
  • Loading branch information
farcepest committed Aug 18, 2013
2 parents 39406ea + f064692 commit c8b2744
Showing 1 changed file with 30 additions and 2 deletions.
32 changes: 30 additions & 2 deletions MySQLdb/connections.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,11 @@ class object, used to create cursors (keyword only)
local_infile
integer, non-zero enables LOAD LOCAL INFILE; zero disables
autocommit
If False (default), autocommit is disabled.
If True, autocommit is enabled.
If None, autocommit isn't set and server default is used.
There are a number of undocumented, non-standard methods. See the
documentation for the MySQL C API for some hints on what they do.
Expand Down Expand Up @@ -182,6 +187,9 @@ class object, used to create cursors (keyword only)

kwargs2['client_flag'] = client_flag

# PEP-249 requires autocommit to be initially off
autocommit = kwargs2.pop('autocommit', False)

super(Connection, self).__init__(*args, **kwargs2)
self.cursorclass = cursorclass
self.encoders = dict([ (k, v) for k, v in conv.items()
Expand Down Expand Up @@ -224,11 +232,29 @@ def string_decoder(s):
self.encoders[types.StringType] = string_literal
self.encoders[types.UnicodeType] = unicode_literal
self._transactional = self.server_capabilities & CLIENT.TRANSACTIONS
self._autocommit = None
if self._transactional:
# PEP-249 requires autocommit to be initially off
self.autocommit(False)
if autocommit is not None:
self.autocommit(autocommit)
self.messages = []

def autocommit(self, on):
on = bool(on)
_mysql.connection.autocommit(self, on)
self._autocommit = on

def get_autocommit(self):
if self._autocommit is None:
self._update_autocommit()
return self._autocommit

def _update_autocommit(self):
cursor = cursors.Cursor(self)
cursor.execute("SELECT @@AUTOCOMMIT")
row = cursor.fetchone()
self._autocommit = bool(row[0])
cursor.close()

def cursor(self, cursorclass=None):
"""
Expand All @@ -241,6 +267,8 @@ def cursor(self, cursorclass=None):
return (cursorclass or self.cursorclass)(self)

def __enter__(self):
if self.get_autocommit():
self.query("BEGIN")
return self.cursor()

def __exit__(self, exc, value, tb):
Expand Down

0 comments on commit c8b2744

Please sign in to comment.