damccorm commented on code in PR #41465:
URL: https://github.com/apache/beam/pull/41465#discussion_r4671565897


##########
sdks/python/apache_beam/transforms/enrichment_handlers/bigquery.py:
##########
@@ -29,14 +34,370 @@
 from apache_beam.pvalue import Row
 from apache_beam.transforms.enrichment import EnrichmentSourceHandler
 
-QueryFn = Callable[[beam.Row], str]
+__all__ = ['BigQueryEnrichmentHandler']
+
+QueryFn = Callable[[beam.Row], Union[str, tuple[str, Sequence[Any]]]]
 ConditionValueFn = Callable[[beam.Row], list[Any]]
+PlaceholderRenderer = Callable[[str, str, bool], str]
 
 _LOGGER = logging.getLogger(__name__)
 
+MAX_BQ_QUERY_PARAMETERS = 10000
+
+SIMPLE_IDENTIFIER_PATTERN = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*$')
+_SIMPLE_IDENTIFIER_PREFIX = re.compile(r'[A-Za-z_][A-Za-z0-9_]*')
+_SYS_VAR_PREFIX = re.compile(r'[A-Za-z_][A-Za-z0-9_.]*')
+_TABLE_SEGMENT = (
+    r'(?:`(?:[A-Za-z0-9_:$-]+\.)*[A-Za-z0-9_:$-]+`|[A-Za-z0-9_:$-]+)')
+TABLE_NAME_PATTERN = re.compile(rf'^{_TABLE_SEGMENT}(?:\.{_TABLE_SEGMENT})*$')
+_COLUMN_SEGMENT = r'(?:`[A-Za-z_][A-Za-z0-9_]*`|[A-Za-z_][A-Za-z0-9_]*)'
+COLUMN_NAME_PATTERN = re.compile(
+    rf'^(?:\*|{_COLUMN_SEGMENT}(?:\.{_COLUMN_SEGMENT})*)$')
+
+
+def validate_bigquery_identifier(
+    identifier: str, param_name: str, pattern: re.Pattern[str]) -> None:
+  if (not isinstance(identifier, str) or not identifier or '--' in identifier 
or
+      '/*' in identifier or '*/' in identifier or
+      not pattern.match(identifier)):
+    raise ValueError(f"Invalid BigQuery {param_name}: {identifier!r}")
+
+
+def _validate_brace_spec(raw_spec: str, sql: str) -> str:
+  spec = raw_spec.strip()
+  if spec == '' or spec.isdigit() or SIMPLE_IDENTIFIER_PATTERN.match(spec):
+    return spec
+  raise ValueError(
+      f"Invalid placeholder {{{raw_spec}}} in SQL template: {sql!r}")
+
+
+def _find_closing_quote(sql: str, start: int, quote: str) -> int:
+  n = len(sql)
+  j = start
+  while j < n:
+    if sql.startswith(quote, j):
+      return j
+    if sql[j] == '\\':
+      if j + 1 >= n:
+        raise ValueError(f"Unterminated escape in SQL string literal: {sql!r}")
+      j += 2
+      continue
+    j += 1
+  raise ValueError(f"Unterminated string literal in SQL template: {sql!r}")
+
+
+def scan_sql_template(sql: str, render_placeholder: PlaceholderRenderer) -> 
str:

Review Comment:
   Thanks for thinking through all the SQL edge cases here! I wonder if we can 
get away with something much simpler, though — maintaining a ~200-line custom 
GoogleSQL scanner (for comments, raw/triple-quoted strings, and rewriting 
partial string literals into `CONCAT(...)`) adds quite a bit of complexity to 
keep up with over time.
   
   Since the untrusted input is the per-row values rather than the template 
string itself, what do you think about using a small regex that converts legacy 
`'{}'` / `{}` placeholders to `?` (and `'{key}'` / `{key}` to `@...` in vector 
search) while passing native `?` placeholders through? For cases like `LIKE` 
with partial strings, users can write `CONCAT('%', ?)` directly in their 
template instead of us rewriting string literals implicitly.



##########
sdks/python/apache_beam/ml/rag/enrichment/bigquery_vector_search.py:
##########
@@ -28,10 +31,136 @@
 from apache_beam.ml.rag.types import EmbeddableItem
 from apache_beam.ml.rag.types import Embedding
 from apache_beam.transforms.enrichment import EnrichmentSourceHandler
+from apache_beam.transforms.enrichment_handlers.bigquery import 
COLUMN_NAME_PATTERN
+from apache_beam.transforms.enrichment_handlers.bigquery import 
MAX_BQ_QUERY_PARAMETERS
+from apache_beam.transforms.enrichment_handlers.bigquery import 
SIMPLE_IDENTIFIER_PATTERN
+from apache_beam.transforms.enrichment_handlers.bigquery import 
TABLE_NAME_PATTERN
+from apache_beam.transforms.enrichment_handlers.bigquery import 
scan_sql_template
+from apache_beam.transforms.enrichment_handlers.bigquery import 
to_query_parameter
+from apache_beam.transforms.enrichment_handlers.bigquery import 
validate_bigquery_identifier
 
 _LOGGER = logging.getLogger(__name__)
 
 
+def _format_sql_string_literal(value: str) -> str:
+  escaped = value.replace('\\', '\\\\').replace("'", "\\'")
+  return f"'{escaped}'"
+
+
+def _extract_metadata_template_keys(template: str) -> tuple[str, ...]:
+  keys: list[str] = []
+
+  def _collect(kind: str, spec: str, in_string: bool) -> str:
+    del in_string
+    if kind == 'qmark' or (kind == 'brace' and (spec == '' or spec.isdigit())):
+      raise ValueError(
+          "String metadata_restriction_template only supports named metadata "
+          f"placeholders such as '{{key}}' or '@key', got: {template!r}")
+    keys.append(spec)
+    return '@_placeholder'
+
+  scan_sql_template(template, _collect)
+  return tuple(dict.fromkeys(keys))
+
+
+def _parameterize_callable_tuple(

Review Comment:
   We could probably skip adding the new `(sql, params)` tuple return support 
for `query_fn` and callable `metadata_restriction_template` altogether (or 
defer it to a follow-up PR if there's a strong use case). Leaving out the new 
API surface and parameter-renaming logic would keep this PR focused on safely 
parameterizing the existing template-based paths.



##########
sdks/python/apache_beam/transforms/enrichment_handlers/bigquery.py:
##########
@@ -29,14 +34,370 @@
 from apache_beam.pvalue import Row
 from apache_beam.transforms.enrichment import EnrichmentSourceHandler
 
-QueryFn = Callable[[beam.Row], str]
+__all__ = ['BigQueryEnrichmentHandler']
+
+QueryFn = Callable[[beam.Row], Union[str, tuple[str, Sequence[Any]]]]
 ConditionValueFn = Callable[[beam.Row], list[Any]]
+PlaceholderRenderer = Callable[[str, str, bool], str]
 
 _LOGGER = logging.getLogger(__name__)
 
+MAX_BQ_QUERY_PARAMETERS = 10000
+
+SIMPLE_IDENTIFIER_PATTERN = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*$')
+_SIMPLE_IDENTIFIER_PREFIX = re.compile(r'[A-Za-z_][A-Za-z0-9_]*')
+_SYS_VAR_PREFIX = re.compile(r'[A-Za-z_][A-Za-z0-9_.]*')
+_TABLE_SEGMENT = (
+    r'(?:`(?:[A-Za-z0-9_:$-]+\.)*[A-Za-z0-9_:$-]+`|[A-Za-z0-9_:$-]+)')
+TABLE_NAME_PATTERN = re.compile(rf'^{_TABLE_SEGMENT}(?:\.{_TABLE_SEGMENT})*$')
+_COLUMN_SEGMENT = r'(?:`[A-Za-z_][A-Za-z0-9_]*`|[A-Za-z_][A-Za-z0-9_]*)'
+COLUMN_NAME_PATTERN = re.compile(
+    rf'^(?:\*|{_COLUMN_SEGMENT}(?:\.{_COLUMN_SEGMENT})*)$')
+
+
+def validate_bigquery_identifier(

Review Comment:
   I'd actually recommend skipping identifier validation on `table_name` and 
`column_names` here. Those are static pipeline construction args rather than 
per-element data, and strict ASCII regexes like `COLUMN_NAME_PATTERN` / 
`TABLE_NAME_PATTERN` risk breaking valid existing pipelines (for example, 
`column_names` using aliases or expressions like `col AS alias`, or BigQuery 
table names with non-ASCII characters or spaces inside backticks).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to