Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
164 changes: 162 additions & 2 deletions google/cloud/managed_spark_connect/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -799,6 +799,164 @@ def _session_state_attrs(session: Any) -> Dict[str, Any]:
return attrs


_LAZY_SQL_KEYWORDS = frozenset({"select", "values", "table"})


def _skip_sql_ws_and_comments(sql: str, pos: int) -> int:
"""Advance ``pos`` past whitespace, ``--`` comments, and ``/* ... */``."""
n = len(sql)
while pos < n:
if sql[pos].isspace():
pos += 1
elif sql.startswith("--", pos):
nl = sql.find("\n", pos + 2)
pos = n if nl == -1 else nl + 1
elif sql.startswith("/*", pos):
depth, pos = 1, pos + 2
while pos < n and depth > 0:
if sql.startswith("/*", pos):
depth, pos = depth + 1, pos + 2
elif sql.startswith("*/", pos):
depth, pos = depth - 1, pos + 2
else:
pos += 1
else:
break
return pos


def _next_sql_token(sql: str, pos: int) -> Tuple[Optional[str], int]:
"""Return the next lexical SQL token and offset, skipping comments."""
pos = _skip_sql_ws_and_comments(sql, pos)
n = len(sql)
if pos >= n:
return None, pos
ch = sql[pos]
if ch in ("(", ")", ","):
return ch, pos + 1
if ch in ("'", '"', "`"):
Comment thread
ptch314 marked this conversation as resolved.
Resolved
start, pos = pos, pos + 1
while pos < n:
if sql[pos] == "\\" and ch != "`":
pos += 2
elif sql[pos] == ch:
pos += 1
if pos < n and sql[pos] == ch:
pos += 1
else:
break
else:
pos += 1
return sql[start:pos], pos
if ch in ("r", "R") and pos + 1 < n and sql[pos + 1] in ("'", '"'):
quote = sql[pos + 1]
end = sql.find(quote, pos + 2)
end = n if end == -1 else end + 1
return sql[pos:end], end
if ch.isalpha() or ch == "_":
end = pos + 1
while end < n and (sql[end].isalnum() or sql[end] == "_"):
end += 1
return sql[pos:end], end
return ch, pos + 1


def _skip_sql_parens(sql: str, pos: int) -> Optional[int]:
"""Skip past a parenthesized block whose opening ``(`` was just read."""
depth = 1
while depth > 0:
tok, pos = _next_sql_token(sql, pos)
if tok is None:
return None
if tok == "(":
depth += 1
elif tok == ")":
depth -= 1
return pos


def _is_lazy_from_statement(query: str, pos: int) -> bool:
"""Return False if a FROM statement has a top-level INSERT INTO/OVERWRITE."""
tok, pos = _next_sql_token(query, pos)
while tok is not None:
if tok == "(":
Comment thread
ptch314 marked this conversation as resolved.
Resolved
next_pos = _skip_sql_parens(query, pos)
if next_pos is None:
return False
tok, pos = _next_sql_token(query, next_pos)
continue
if tok.lower() == "insert":
next_tok, pos = _next_sql_token(query, pos)
if next_tok is not None and next_tok.lower() in (
"into",
"overwrite",
):
return False
tok = next_tok
continue
tok, pos = _next_sql_token(query, pos)
return True


def _is_lazy_sql_query(query: str) -> bool:
"""Whether a SQL statement is a lazy query rather than eager DML/DDL."""
tok, pos = _next_sql_token(query, 0)
while True:
while tok == "(":
tok, pos = _next_sql_token(query, pos)
if tok is None:
return False
kw = tok.lower()
if kw in _LAZY_SQL_KEYWORDS:
return True
if kw == "from":
return _is_lazy_from_statement(query, pos)
if kw != "with":
return False

tok, pos = _next_sql_token(query, pos)
if tok is not None and tok.lower() == "recursive":
tok, pos = _next_sql_token(query, pos)

while True:
if tok is None or not (
tok.startswith(("`", '"')) or tok[0].isalpha() or tok[0] == "_"
):
return False
tok, pos = _next_sql_token(query, pos)
had_paren = False
if tok == "(":
next_pos = _skip_sql_parens(query, pos)
if next_pos is None:
return False
tok, pos = _next_sql_token(query, next_pos)
had_paren = True
if tok is not None and tok.lower() == "as":
tok, pos = _next_sql_token(query, pos)
if tok is not None and tok.lower() == "not":
tok, pos = _next_sql_token(query, pos)
if tok is not None and tok.lower() == "materialized":
tok, pos = _next_sql_token(query, pos)
if tok != "(":
return False
next_pos = _skip_sql_parens(query, pos)
if next_pos is None:
return False
tok, pos = _next_sql_token(query, next_pos)
elif tok == "(":
next_pos = _skip_sql_parens(query, pos)
if next_pos is None:
return False
tok, pos = _next_sql_token(query, next_pos)
elif not had_paren:
return False

if tok == ",":
tok, pos = _next_sql_token(query, pos)
continue
break


class ManagedSparkSession(SparkSession):
"""The entry point to programming Spark with the Dataset and DataFrame API.

Expand Down Expand Up @@ -2567,12 +2725,14 @@ def _set_tqdm_factory(cls, factory: Optional[Callable[..., Any]]) -> None:

@staticmethod
def _sql_lazy_transformation(req):
# Select SQL command
# Lazy SQL query (SELECT, VALUES, TABLE, FROM, or WITH ... query)
try:
query = req.plan.command.sql_command.input.sql.query
return "select" in query.strip().lower().split()
except AttributeError:
return False
if not isinstance(query, str):
return False
return _is_lazy_sql_query(query)

def _monitored_stream(
self,
Expand Down
50 changes: 31 additions & 19 deletions tests/unit/test_cell_monitoring.py
Original file line number Diff line number Diff line change
Expand Up @@ -612,16 +612,20 @@ def _exec_behavior(req, *a, **kw):
self.assertEqual(s.client._execute(lazy_req, {}), "exec-ok")
self.assertNotIn(lazy_req.operation_id, poller.begun)

dml_req = s.client._execute_plan_request_with_metadata()
dml_req.plan.command.sql_command.input.sql.query = (
"INSERT INTO test_table_2 VALUES (1)"
)
self.assertEqual(s.client._execute(dml_req, {}), "exec-ok")
self.assertIn(dml_req.operation_id, poller.begun)
self.assertEqual(
poller.finished[-1],
(dml_req.operation_id, "SUCCEEDED"),
)
for eager_sql in (
"INSERT INTO test_table_2 VALUES (1)",
"INSERT INTO dst SELECT * FROM src",
"CREATE TABLE dst AS SELECT * FROM src",
"FROM src INSERT INTO dst SELECT *",
):
dml_req = s.client._execute_plan_request_with_metadata()
dml_req.plan.command.sql_command.input.sql.query = eager_sql
self.assertEqual(s.client._execute(dml_req, {}), "exec-ok")
self.assertIn(dml_req.operation_id, poller.begun)
self.assertEqual(
poller.finished[-1],
(dml_req.operation_id, "SUCCEEDED"),
)

req_mutate = s.client._execute_plan_request_with_metadata()
orig_mutate_id = req_mutate.operation_id
Expand All @@ -644,18 +648,26 @@ def _exec_behavior(req, *a, **kw):
mock_classify.assert_not_called()
mock_link.assert_called_once_with(req_unmon.operation_id)

mock_link.reset_mock()
eager_unmon = s.client._execute_plan_request_with_metadata()
eager_unmon.plan.command.sql_command.input.sql.query = (
"INSERT INTO test_table_2 VALUES (1)"
)
self.assertEqual(s.client._execute(eager_unmon, {}), "exec-ok")
mock_link.assert_called_once_with(eager_unmon.operation_id)
for eager_sql in (
"INSERT INTO test_table_2 VALUES (1)",
"INSERT INTO dst SELECT * FROM src",
"CREATE TABLE dst AS SELECT * FROM src",
"WITH cte AS (SELECT 1) INSERT INTO dst SELECT * FROM cte",
):
mock_link.reset_mock()
eager_unmon = s.client._execute_plan_request_with_metadata()
eager_unmon.plan.command.sql_command.input.sql.query = (
eager_sql
)
self.assertEqual(
s.client._execute(eager_unmon, {}), "exec-ok"
)
mock_link.assert_called_once_with(eager_unmon.operation_id)

mock_link.reset_mock()
lazy_unmon = s.client._execute_plan_request_with_metadata()
lazy_unmon.plan.command.sql_command.input.sql.query = (
"SELECT * FROM tbl"
"-- comment\nSELECT * FROM tbl"
)
self.assertEqual(s.client._execute(lazy_unmon, {}), "exec-ok")
mock_link.assert_not_called()
Expand Down Expand Up @@ -746,7 +758,7 @@ def _fake_stream(req, *a, **kw):

req_unmon_dml = s.client._execute_plan_request_with_metadata()
req_unmon_dml.plan.command.sql_command.input.sql.query = (
"INSERT INTO test_table_2 VALUES (1)"
"INSERT INTO dst SELECT * FROM src"
)
self.assertEqual(
list(
Expand Down
78 changes: 78 additions & 0 deletions tests/unit/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -2761,6 +2761,84 @@ def test_sql_lazy_transformation(self):
)
)

def _make_sql_req(query: str) -> ExecutePlanRequest:
return ExecutePlanRequest(
session_id="mock-session_id-from-super",
client_type="mock-client_type-from-super",
plan=Plan(
command=Command(
sql_command=SqlCommand(
input=Relation(sql=SQL(query=query))
)
)
),
tags=["mock-tag-from-super"],
user_context=UserContext(user_id="mock-user-from-super"),
operation_id=test_uuid,
)

lazy_queries = [
Comment thread
ptch314 marked this conversation as resolved.
Resolved
"SELECT 1",
"-- lead comment\n/* block SELECT INSERT */\n SELECT * FROM tbl",
"/* /* nested */ */ (SELECT * FROM tbl)",
"VALUES (1, 'a'), (2, 'b')",
"TABLE catalog.db.tbl",
"FROM tbl SELECT a, b",
"WITH cte AS (SELECT 1) SELECT * FROM cte",
"WITH RECURSIVE cte(n) AS (\n SELECT 1 UNION ALL SELECT n + 1 FROM cte WHERE n < 5\n) SELECT * FROM cte",
"WITH cte1 AS (SELECT ') AS INSERT' AS s), cte2(x) AS (SELECT 1) (SELECT * FROM cte1)",
"WITH `select_cte` AS (SELECT 1) VALUES (1)",
Comment thread
ptch314 marked this conversation as resolved.
Resolved
'WITH "select_cte" AS (SELECT 1) VALUES (1)',
"WITH cte (SELECT 1) SELECT * FROM cte",
"WITH cte(a) (SELECT 1) SELECT * FROM cte",
r"WITH cte AS (SELECT r'C:\temp\' AS p) SELECT * FROM cte",
"WITH cte1 AS (SELECT 1) (WITH cte2 AS (SELECT 2) SELECT * FROM cte1, cte2)",
]
for query in lazy_queries:
with self.subTest(lazy=query):
self.assertTrue(
ManagedSparkSession._sql_lazy_transformation(
_make_sql_req(query)
)
)

eager_queries = [
"INSERT INTO dst SELECT * FROM src",
"INSERT OVERWRITE TABLE dst SELECT * FROM src",
"CREATE TABLE dst AS SELECT * FROM src",
"CREATE OR REPLACE TABLE dst USING DELTA AS SELECT * FROM src",
"REPLACE TABLE dst AS SELECT * FROM src",
"MERGE INTO tgt USING (SELECT * FROM src) s ON tgt.id = s.id WHEN MATCHED THEN DELETE",
"UPDATE tgt SET v = 1 WHERE id IN (SELECT id FROM src)",
"DELETE FROM tgt WHERE id IN (SELECT id FROM src)",
"CACHE TABLE cached AS SELECT * FROM src",
"COPY INTO dst FROM (SELECT * FROM src)",
"WITH cte AS (SELECT 1) INSERT INTO dst SELECT * FROM cte",
'WITH "my_cte" AS (SELECT 1) INSERT INTO dst SELECT * FROM "my_cte"',
"WITH cte AS (SELECT 1), cte2(a) AS (SELECT 2) MERGE INTO tgt USING cte2 ON tgt.a = cte2.a WHEN MATCHED THEN DELETE",
"WITH cte AS (SELECT 1) UPDATE tgt SET a = 1 WHERE EXISTS (SELECT 1 FROM cte)",
"WITH cte AS (SELECT 1) DELETE FROM tgt WHERE id IN (SELECT id FROM cte)",
"FROM src INSERT INTO dst SELECT *",
"FROM src INSERT OVERWRITE TABLE dst SELECT *",
"FROM src INSERT OVERWRITE DIRECTORY '/tmp/out' SELECT *",
"WITH cte AS (SELECT 1) FROM cte INSERT INTO dst SELECT *",
r"WITH cte AS (SELECT r'a\' AS p, 'b) SELECT 1' AS q) INSERT INTO dst SELECT * FROM cte",
"-- comment only\n/* also comment */",
"",
]
for query in eager_queries:
with self.subTest(eager=query):
self.assertFalse(
ManagedSparkSession._sql_lazy_transformation(
_make_sql_req(query)
)
)

self.assertFalse(
ManagedSparkSession._sql_lazy_transformation(mock.MagicMock())
)
self.assertFalse(ManagedSparkSession._sql_lazy_transformation(object()))

@mock.patch("google.auth.default")
@mock.patch("google.cloud.dataproc_v1.SessionControllerClient")
@mock.patch("pyspark.sql.connect.client.SparkConnectClient.config")
Expand Down
Loading