Skip to content

Commit

Permalink
feat(db_api): support executing several DDLs separated by semicolon (#…
Browse files Browse the repository at this point in the history
…277)

* feat(db_api): support executing several DDLs separated by semicolon

* add a unit test

* add a line with a "newline" symbol into test
  • Loading branch information
Ilya Gurov committed Mar 18, 2021
1 parent 1b0ce1d commit 801ddc8
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
5 changes: 4 additions & 1 deletion google/cloud/spanner_dbapi/cursor.py
Expand Up @@ -174,7 +174,10 @@ def execute(self, sql, args=None):
try:
classification = parse_utils.classify_stmt(sql)
if classification == parse_utils.STMT_DDL:
self.connection._ddl_statements.append(sql)
for ddl in sql.split(";"):
ddl = ddl.strip()
if ddl:
self.connection._ddl_statements.append(ddl)
return

# For every other operation, we've got to ensure that
Expand Down
30 changes: 30 additions & 0 deletions tests/unit/spanner_dbapi/test_cursor.py
Expand Up @@ -862,3 +862,33 @@ def test_fetchmany_retry_aborted_statements_checksums_mismatch(self):
cursor.fetchmany(len(row))

run_mock.assert_called_with(statement, retried=True)

def test_ddls_with_semicolon(self):
"""
Check that one script with several DDL statements separated
with semicolons is splitted into several DDLs.
"""
from google.cloud.spanner_dbapi.connection import connect

EXP_DDLS = [
"CREATE TABLE table_name (row_id INT64) PRIMARY KEY ()",
"DROP INDEX index_name",
"DROP TABLE table_name",
]

with mock.patch(
"google.cloud.spanner_v1.instance.Instance.exists", return_value=True,
):
with mock.patch(
"google.cloud.spanner_v1.database.Database.exists", return_value=True,
):
connection = connect("test-instance", "test-database")

cursor = connection.cursor()
cursor.execute(
"CREATE TABLE table_name (row_id INT64) PRIMARY KEY ();"
"DROP INDEX index_name;\n"
"DROP TABLE table_name;"
)

self.assertEqual(connection._ddl_statements, EXP_DDLS)

0 comments on commit 801ddc8

Please sign in to comment.