Skip to content

Commit

Permalink
fix(db_api): ensure DDL statements are being executed (#290)
Browse files Browse the repository at this point in the history
* fix(db_api): DDLs are not executed immediately in autocommit mode

* fix DDLs committing, add system tests

* erase insert statement
  • Loading branch information
Ilya Gurov authored Mar 25, 2021
1 parent e5d4901 commit baa02ee
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
5 changes: 4 additions & 1 deletion google/cloud/spanner_dbapi/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,10 @@ def commit(self):
"""
if self._autocommit:
warnings.warn(AUTOCOMMIT_MODE_WARNING, UserWarning, stacklevel=2)
elif self.inside_transaction:
return

self.run_prior_DDL_statements()
if self.inside_transaction:
try:
self._transaction.commit()
self._release_session()
Expand Down
2 changes: 2 additions & 0 deletions google/cloud/spanner_dbapi/cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,8 @@ def execute(self, sql, args=None):
ddl = ddl.strip()
if ddl:
self.connection._ddl_statements.append(ddl)
if self.connection.autocommit:
self.connection.run_prior_DDL_statements()
return

# For every other operation, we've got to ensure that
Expand Down
48 changes: 48 additions & 0 deletions tests/system/test_system_dbapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,54 @@ def test_execute_many(self):
self.assertEqual(res[0], 1)
conn.close()

def test_DDL_autocommit(self):
"""Check that DDLs in autocommit mode are immediately executed."""
conn = Connection(Config.INSTANCE, self._db)
conn.autocommit = True

cur = conn.cursor()
cur.execute(
"""
CREATE TABLE Singers (
SingerId INT64 NOT NULL,
Name STRING(1024),
) PRIMARY KEY (SingerId)
"""
)
conn.close()

# if previous DDL wasn't committed, the next DROP TABLE
# statement will fail with a ProgrammingError
conn = Connection(Config.INSTANCE, self._db)
cur = conn.cursor()

cur.execute("DROP TABLE Singers")
conn.commit()

def test_DDL_commit(self):
"""Check that DDLs in commit mode are executed on calling `commit()`."""
conn = Connection(Config.INSTANCE, self._db)
cur = conn.cursor()

cur.execute(
"""
CREATE TABLE Singers (
SingerId INT64 NOT NULL,
Name STRING(1024),
) PRIMARY KEY (SingerId)
"""
)
conn.commit()
conn.close()

# if previous DDL wasn't committed, the next DROP TABLE
# statement will fail with a ProgrammingError
conn = Connection(Config.INSTANCE, self._db)
cur = conn.cursor()

cur.execute("DROP TABLE Singers")
conn.commit()


def clear_table(transaction):
"""Clear the test table."""
Expand Down

0 comments on commit baa02ee

Please sign in to comment.