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


##########
sdks/python/apache_beam/cli/main.py:
##########
@@ -88,17 +92,31 @@
 Every other --flag is passed to the pipeline as a Beam pipeline option.
 """ + _EXIT_CODES
 
+_SQL_EPILOG = """\
+examples:
+  beam sql
+  beam sql --io csv --io parquet

Review Comment:
   This set of examples is not completely clear to me. What does `beam sql` do 
if you don't pass in a query? Similarly, what does `beam sql --io csv --io 
parquet` do? Are these valid on their own?
   
   It would be good to have an example that shows reading from a CSV file, 
doing some filtering/aggregation, and writing to a parquet sink.
   
   I also don't see that level of functionality tested (I was trying to use 
that to find an example) - could we add an E2E test that confirms you can run 
sql with a set of IOs?



##########
sdks/python/apache_beam/cli/main.py:
##########
@@ -88,17 +92,31 @@
 Every other --flag is passed to the pipeline as a Beam pipeline option.
 """ + _EXIT_CODES
 
+_SQL_EPILOG = """\
+examples:
+  beam sql
+  beam sql --io csv --io parquet
+  beam sql -e "SELECT 1 + 1 AS two;"
+  beam sql --runner dataflow --io google-cloud-platform

Review Comment:
   What does `--io google-cloud-platform` do?



##########
sdks/python/apache_beam/cli/sql.py:
##########
@@ -0,0 +1,837 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Launches the Apache Beam SQL shell (`BeamSqlLine`) for `beam sql`.
+
+`scripts/beam-sql.sh` builds a self-contained shaded uber-JAR with Maven
+Wrapper, caches it in `~/.beam/cache/`, and starts `BeamSqlLine`. This module
+does the same in Python with identical cache paths and filenames, so cached
+JARs and `~/.beam/maven-wrapper/` are shared between `beam-sql.sh` and
+`beam sql`, while checking for a real Java 11+ runtime (catching macOS's
+`/usr/bin/java` stub and older JDKs) without needing `curl`, `sed`, or GNU
+`sort -V`.
+"""
+
+import contextlib
+import errno
+import json
+import os
+import re
+import shutil
+import stat
+import subprocess
+import sys
+import tempfile
+import textwrap
+import threading
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+import xml.etree.ElementTree as ET
+import zipfile
+from pathlib import Path
+from xml.sax.saxutils import escape as xml_escape
+
+_EXIT_FAILED = 1
+_EXIT_USAGE = 2
+_EXIT_MISSING_DEPENDENCY = 4
+
+
+class SqlError(Exception):
+  """An error in `beam sql`, reported to the user with `exit_code`."""
+  def __init__(self, message, exit_code):
+    super().__init__(message)
+    self.exit_code = exit_code
+
+
+_MAIN_CLASS = 'org.apache.beam.sdk.extensions.sql.jdbc.BeamSqlLine'
+_WRAPPER_MAIN_CLASS = 'org.apache.maven.wrapper.MavenWrapperMain'
+
+# Supported runners and the extra Maven dependency each needs, matching
+# `scripts/beam-sql.sh`. DirectRunner is already a transitive dependency of
+# `beam-sdks-java-extensions-sql-jdbc`.
+_RUNNER_ARTIFACTS = {
+    'direct': None,
+    'dataflow': 'beam-runners-google-cloud-dataflow-java',
+}
+
+_VALID_ARTIFACT_PART = re.compile(r'^[a-z0-9][a-z0-9._-]*$')
+_ANSI_SEQ_RE = re.compile(
+    r'\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b[@-_]')
+_CTRL_CHARS_RE = re.compile(r'[\x00-\x1f\x7f-\x9f]')
+
+_SQL_LOCKS_GUARD = threading.Lock()
+_SQL_INPROC_LOCKS: dict[str, threading.RLock] = {}
+_SQL_LOCK_DEPTH: dict[tuple[str, int], int] = {}
+
+
+def _sanitize_log_token(text: str) -> str:
+  return _CTRL_CHARS_RE.sub('', _ANSI_SEQ_RE.sub('', str(text)))
+
+
+def _is_valid_jar(jar_path: str) -> bool:
+  return (
+      os.path.isfile(jar_path) and not os.path.islink(jar_path) and
+      zipfile.is_zipfile(jar_path))
+
+
[email protected]
+def _file_lock(lock_path: str):
+  abs_key = os.path.abspath(str(lock_path))
+  lock_dir = os.path.dirname(abs_key) or '.'
+  with _SQL_LOCKS_GUARD:
+    inproc_lk = _SQL_INPROC_LOCKS.setdefault(abs_key, threading.RLock())
+  with inproc_lk:
+    depth_key = (abs_key, threading.get_ident())
+    depth = _SQL_LOCK_DEPTH.get(depth_key, 0)
+    if depth > 0:
+      _SQL_LOCK_DEPTH[depth_key] = depth + 1
+      try:
+        yield
+      finally:
+        _SQL_LOCK_DEPTH[depth_key] = depth
+      return
+
+    if any(os.path.islink(p) for p in (lock_dir, lock_path, abs_key)):
+      raise SqlError(f'refusing symlinked lock path {lock_path!r}', 
_EXIT_USAGE)
+    os.makedirs(lock_dir, mode=0o700, exist_ok=True)
+    if any(os.path.islink(p) for p in (lock_dir, lock_path, abs_key)):
+      raise SqlError(f'refusing symlinked lock path {lock_path!r}', 
_EXIT_USAGE)
+    open_flags = os.O_CREAT | os.O_RDWR | getattr(os, 'O_NOFOLLOW', 0)
+    try:
+      fd = os.open(abs_key, open_flags, 0o600)
+    except OSError as exc:
+      if exc.errno == getattr(errno, 'ELOOP', -1):
+        raise SqlError(
+            f'refusing symlinked lock path {lock_path!r}',
+            _EXIT_USAGE) from None
+      raise
+    if not stat.S_ISREG(os.fstat(fd).st_mode):
+      os.close(fd)
+      raise SqlError(
+          f'lock path {lock_path!r} must be a regular file', _EXIT_USAGE)
+
+    try:
+      if os.name == 'nt':
+        import msvcrt
+        os.lseek(fd, 0, os.SEEK_SET)
+        with contextlib.suppress(OSError):
+          if os.fstat(fd).st_size == 0:
+            os.write(fd, b'\0')
+            os.lseek(fd, 0, os.SEEK_SET)
+        while True:
+          try:
+            msvcrt.locking(fd, msvcrt.LK_LOCK, 1)
+            break
+          except OSError:
+            time.sleep(0.05)
+      else:
+        import fcntl
+        fcntl.flock(fd, fcntl.LOCK_EX)
+      _SQL_LOCK_DEPTH[depth_key] = 1
+      yield
+    finally:
+      _SQL_LOCK_DEPTH.pop(depth_key, None)
+      with contextlib.suppress(OSError):
+        if os.name == 'nt':
+          import msvcrt
+          os.lseek(fd, 0, os.SEEK_SET)
+          msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
+        else:
+          import fcntl
+          fcntl.flock(fd, fcntl.LOCK_UN)
+      os.close(fd)
+
+
+def _installed_beam_version() -> str:
+  """Reads the installed `apache-beam` version without importing the SDK."""
+  version_file = Path(__file__).resolve().parents[1] / 'version.py'
+  if version_file.is_file():
+    match = re.search(
+        r"__version__\s*=\s*['\"]([^'\"]+)['\"]",
+        version_file.read_text(encoding='utf-8'))
+    if match:
+      return match.group(1)
+  import importlib.metadata
+  try:
+    return importlib.metadata.version('apache-beam')
+  except importlib.metadata.PackageNotFoundError:
+    from apache_beam import version as beam_version
+    return beam_version.__version__
+
+
+def run(
+    version=None,
+    runner='direct',
+    ios=(),
+    list_versions=False,
+    list_ios=False,
+    list_runners=False,
+    debug=False,
+    sqlline_args=(),
+    beam_home=None):
+  """Runs `beam sql` and returns the process exit code."""
+  if list_versions:
+    return _list_versions()
+  if list_ios:
+    return _list_ios()
+
+  resolved_version = _resolve_version(version)
+  if list_runners:
+    return _list_runners(resolved_version)
+
+  runner_key = _normalize_runner(runner)
+  clean_ios = _normalize_ios(ios)
+  java_bin, java_home = _find_java()
+
+  home = beam_home or os.path.expanduser(os.environ.get('BEAM_HOME', 
'~/.beam'))
+  if os.path.islink(home):
+    raise SqlError(
+        f'refusing symlinked BEAM_HOME directory {home!r}', _EXIT_USAGE)
+  cache_dir = os.path.join(home, 'cache')
+  os.makedirs(cache_dir, mode=0o700, exist_ok=True)
+  jar_path = os.path.join(
+      cache_dir,
+      
f"beam-{resolved_version}_runner-{runner_key}_ios-{'-'.join(clean_ios)}.jar"
+  )
+  if os.path.islink(cache_dir) or os.path.islink(jar_path):
+    raise SqlError(
+        f'refusing symlinked Beam SQL cache path {jar_path!r}', _EXIT_USAGE)
+
+  with _file_lock(f'{jar_path}.lock'):
+    cached_ready = _is_valid_jar(jar_path)
+
+  if cached_ready:
+    print(
+        f'Using cached Beam SQL JAR: {_sanitize_log_token(jar_path)}',
+        file=sys.stderr)
+  else:
+    wrapper_jar = _ensure_maven_wrapper(home)
+    _build_shaded_jar(
+        wrapper_jar,
+        java_home=java_home,
+        version=resolved_version,
+        runner_key=runner_key,
+        ios=clean_ios,
+        jar_path=jar_path,
+        debug=debug,
+        java_bin=java_bin)
+
+  cmd = [java_bin, '-cp', jar_path, _MAIN_CLASS, *sqlline_args]
+  if debug:
+    print('+ ' + ' '.join(_sanitize_log_token(c) for c in cmd), 
file=sys.stderr)
+  with subprocess.Popen(cmd) as proc:
+    while True:
+      try:
+        rc = proc.wait()
+        return 128 - rc if rc < 0 else rc
+      except KeyboardInterrupt:
+        pass
+
+
+def _resolve_version(version):
+  """Returns the Maven release version to use for Beam SQL artifacts."""
+  if version:
+    if '..' in version or not _VALID_ARTIFACT_PART.match(version.lower()):
+      raise SqlError(f'invalid Beam version {version!r}', _EXIT_USAGE)
+    return re.sub(r'-snapshot$', '-SNAPSHOT', version, flags=re.IGNORECASE)
+  installed = _installed_beam_version()
+  if ('.dev' not in installed and
+      not re.search(r'rc\d+$', installed, re.IGNORECASE) and
+      '..' not in installed and _VALID_ARTIFACT_PART.match(installed.lower())):
+    return re.sub(r'-snapshot$', '-SNAPSHOT', installed, flags=re.IGNORECASE)
+  # A development checkout (`2.XX.0.dev`) has no published Maven JARs; fall
+  # back to the latest release on Maven Central, matching `beam-sql.sh`.
+  versions = _fetch_maven_versions()
+  if not versions:
+    raise SqlError(
+        f'installed Apache Beam version is {installed!r} (unreleased) and '
+        'Maven Central could not be reached; pass --version <release>',
+        _EXIT_FAILED)
+  latest = versions[0]
+  print(
+      f'Installed Beam is {_sanitize_log_token(installed)}; using latest '
+      f'released Beam SQL {_sanitize_log_token(latest)} '
+      '(override with --version).',
+      file=sys.stderr)
+  return latest
+
+
+def _normalize_runner(runner):
+  name = (runner or 'direct').strip().lower()
+  if name.endswith('runner') and name != 'runner':
+    name = name[:-len('runner')]
+  if name not in _RUNNER_ARTIFACTS:
+    raise SqlError(
+        f"unsupported runner {runner!r} for beam sql; "
+        f"supported runners: {', '.join(_RUNNER_ARTIFACTS)}",
+        _EXIT_USAGE)
+  return name
+
+
+def _normalize_ios(ios):
+  seen = set()
+  for raw in ios:
+    name = raw.strip().lower()
+    if not name or '..' in name or not _VALID_ARTIFACT_PART.match(name):
+      raise SqlError(
+          f'invalid --io connector {raw!r}; run `beam sql --list-ios` to see '
+          'available connectors',
+          _EXIT_USAGE)
+    seen.add(name)
+  return sorted(seen)
+
+
+_JAVA_VERSION_RE = re.compile(r'version "(\d+)(?:\.(\d+))?')
+_MIN_JAVA_MAJOR = 11
+_WARN_UNSUPPORTED_JAVA_MAJOR = 26
+
+
+def _find_java():
+  """Locates `java`, verifies Java 11+, and returns `(java_bin, java_home)`."""
+  java_exe = 'java.exe' if os.name == 'nt' else 'java'
+  env_home = os.environ.get('JAVA_HOME', '').strip()
+  if env_home:
+    java_bin = os.path.join(env_home, 'bin', java_exe)
+    if not os.path.isfile(java_bin) and os.name == 'nt':
+      fallback = os.path.join(env_home, 'bin', 'java')
+      if os.path.isfile(fallback):
+        java_bin = fallback
+    if not os.path.isfile(java_bin):
+      raise SqlError(
+          f'JAVA_HOME={env_home!r} does not contain bin/{java_exe}; '
+          'Beam SQL requires Java 11 or newer',
+          _EXIT_MISSING_DEPENDENCY)
+  else:
+    java_bin = shutil.which('java')
+    if not java_bin:
+      raise SqlError(
+          "'java' command not found; Beam SQL requires Java 11 or newer. "
+          'Install OpenJDK 11+ or set JAVA_HOME.',
+          _EXIT_MISSING_DEPENDENCY)
+
+  try:
+    proc = subprocess.run([java_bin, '-version'],
+                          capture_output=True,
+                          text=True,
+                          check=False)
+  except OSError as e:
+    raise SqlError(
+        f'could not execute {java_bin!r}: {e}\n'
+        '  Beam SQL requires Java 11 or newer; install OpenJDK 11+ or set '
+        'JAVA_HOME',
+        _EXIT_MISSING_DEPENDENCY) from None
+
+  match = _JAVA_VERSION_RE.search(f'{proc.stderr}\n{proc.stdout}')
+  if proc.returncode != 0 or not match:
+    raise SqlError(
+        'no working Java runtime found; Beam SQL requires Java 11 or newer. '
+        'Install OpenJDK 11+ or set JAVA_HOME.',
+        _EXIT_MISSING_DEPENDENCY)
+
+  first, second = int(match.group(1)), int(match.group(2) or 0)
+  major = second if first == 1 else first
+  if major < _MIN_JAVA_MAJOR:
+    raise SqlError(
+        f'Beam SQL requires Java {_MIN_JAVA_MAJOR} or newer '
+        f'(found Java {major} at {java_bin}). '
+        'Install OpenJDK 11+ or set JAVA_HOME.',
+        _EXIT_MISSING_DEPENDENCY)
+  if major >= _WARN_UNSUPPORTED_JAVA_MAJOR:
+    print(
+        f'warning: Java {major} ({java_bin}) may be newer than Beam SQL '
+        'supports; if queries fail with a ByteBuddy error, set JAVA_HOME to '
+        'Java 11, 17, or 21',
+        file=sys.stderr)
+
+  java_home = env_home or os.path.dirname(
+      os.path.dirname(os.path.realpath(java_bin)))

Review Comment:
   On macOS when JAVA_HOME isn't set, shutil.which('java') resolves to 
/usr/bin/java, which is an Apple launcher binary rather than a symlink. 
realpath stays /usr/bin/java, so java_home ends up as /usr—and when 
_build_shaded_jar exports JAVA_HOME=/usr into the subprocess env, /usr/bin/java 
tries to use /usr as the JDK root and fails to find a runtime (similar issue on 
Windows with javapath\java.exe shims).
   
   Could we run java -XshowSettings:properties -version above and read 
java.home = ... from that output instead (falling back to realpath if it's 
missing)?



##########
sdks/python/apache_beam/cli/sql.py:
##########
@@ -0,0 +1,837 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Launches the Apache Beam SQL shell (`BeamSqlLine`) for `beam sql`.
+
+`scripts/beam-sql.sh` builds a self-contained shaded uber-JAR with Maven
+Wrapper, caches it in `~/.beam/cache/`, and starts `BeamSqlLine`. This module
+does the same in Python with identical cache paths and filenames, so cached
+JARs and `~/.beam/maven-wrapper/` are shared between `beam-sql.sh` and
+`beam sql`, while checking for a real Java 11+ runtime (catching macOS's
+`/usr/bin/java` stub and older JDKs) without needing `curl`, `sed`, or GNU
+`sort -V`.
+"""
+
+import contextlib
+import errno
+import json
+import os
+import re
+import shutil
+import stat
+import subprocess
+import sys
+import tempfile
+import textwrap
+import threading
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+import xml.etree.ElementTree as ET
+import zipfile
+from pathlib import Path
+from xml.sax.saxutils import escape as xml_escape
+
+_EXIT_FAILED = 1
+_EXIT_USAGE = 2
+_EXIT_MISSING_DEPENDENCY = 4
+
+
+class SqlError(Exception):
+  """An error in `beam sql`, reported to the user with `exit_code`."""
+  def __init__(self, message, exit_code):
+    super().__init__(message)
+    self.exit_code = exit_code
+
+
+_MAIN_CLASS = 'org.apache.beam.sdk.extensions.sql.jdbc.BeamSqlLine'
+_WRAPPER_MAIN_CLASS = 'org.apache.maven.wrapper.MavenWrapperMain'
+
+# Supported runners and the extra Maven dependency each needs, matching
+# `scripts/beam-sql.sh`. DirectRunner is already a transitive dependency of
+# `beam-sdks-java-extensions-sql-jdbc`.
+_RUNNER_ARTIFACTS = {
+    'direct': None,
+    'dataflow': 'beam-runners-google-cloud-dataflow-java',
+}
+
+_VALID_ARTIFACT_PART = re.compile(r'^[a-z0-9][a-z0-9._-]*$')
+_ANSI_SEQ_RE = re.compile(
+    r'\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b[@-_]')
+_CTRL_CHARS_RE = re.compile(r'[\x00-\x1f\x7f-\x9f]')
+
+_SQL_LOCKS_GUARD = threading.Lock()
+_SQL_INPROC_LOCKS: dict[str, threading.RLock] = {}
+_SQL_LOCK_DEPTH: dict[tuple[str, int], int] = {}
+
+
+def _sanitize_log_token(text: str) -> str:
+  return _CTRL_CHARS_RE.sub('', _ANSI_SEQ_RE.sub('', str(text)))
+
+
+def _is_valid_jar(jar_path: str) -> bool:
+  return (
+      os.path.isfile(jar_path) and not os.path.islink(jar_path) and
+      zipfile.is_zipfile(jar_path))
+
+
[email protected]
+def _file_lock(lock_path: str):
+  abs_key = os.path.abspath(str(lock_path))
+  lock_dir = os.path.dirname(abs_key) or '.'
+  with _SQL_LOCKS_GUARD:
+    inproc_lk = _SQL_INPROC_LOCKS.setdefault(abs_key, threading.RLock())
+  with inproc_lk:
+    depth_key = (abs_key, threading.get_ident())
+    depth = _SQL_LOCK_DEPTH.get(depth_key, 0)
+    if depth > 0:
+      _SQL_LOCK_DEPTH[depth_key] = depth + 1
+      try:
+        yield
+      finally:
+        _SQL_LOCK_DEPTH[depth_key] = depth
+      return
+
+    if any(os.path.islink(p) for p in (lock_dir, lock_path, abs_key)):
+      raise SqlError(f'refusing symlinked lock path {lock_path!r}', 
_EXIT_USAGE)
+    os.makedirs(lock_dir, mode=0o700, exist_ok=True)
+    if any(os.path.islink(p) for p in (lock_dir, lock_path, abs_key)):
+      raise SqlError(f'refusing symlinked lock path {lock_path!r}', 
_EXIT_USAGE)
+    open_flags = os.O_CREAT | os.O_RDWR | getattr(os, 'O_NOFOLLOW', 0)
+    try:
+      fd = os.open(abs_key, open_flags, 0o600)
+    except OSError as exc:
+      if exc.errno == getattr(errno, 'ELOOP', -1):
+        raise SqlError(
+            f'refusing symlinked lock path {lock_path!r}',
+            _EXIT_USAGE) from None
+      raise
+    if not stat.S_ISREG(os.fstat(fd).st_mode):
+      os.close(fd)
+      raise SqlError(
+          f'lock path {lock_path!r} must be a regular file', _EXIT_USAGE)
+
+    try:
+      if os.name == 'nt':
+        import msvcrt
+        os.lseek(fd, 0, os.SEEK_SET)
+        with contextlib.suppress(OSError):
+          if os.fstat(fd).st_size == 0:
+            os.write(fd, b'\0')
+            os.lseek(fd, 0, os.SEEK_SET)
+        while True:
+          try:
+            msvcrt.locking(fd, msvcrt.LK_LOCK, 1)
+            break
+          except OSError:
+            time.sleep(0.05)
+      else:
+        import fcntl
+        fcntl.flock(fd, fcntl.LOCK_EX)
+      _SQL_LOCK_DEPTH[depth_key] = 1
+      yield
+    finally:
+      _SQL_LOCK_DEPTH.pop(depth_key, None)
+      with contextlib.suppress(OSError):
+        if os.name == 'nt':
+          import msvcrt
+          os.lseek(fd, 0, os.SEEK_SET)
+          msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
+        else:
+          import fcntl
+          fcntl.flock(fd, fcntl.LOCK_UN)
+      os.close(fd)
+
+
+def _installed_beam_version() -> str:
+  """Reads the installed `apache-beam` version without importing the SDK."""
+  version_file = Path(__file__).resolve().parents[1] / 'version.py'
+  if version_file.is_file():
+    match = re.search(
+        r"__version__\s*=\s*['\"]([^'\"]+)['\"]",
+        version_file.read_text(encoding='utf-8'))
+    if match:
+      return match.group(1)
+  import importlib.metadata
+  try:
+    return importlib.metadata.version('apache-beam')
+  except importlib.metadata.PackageNotFoundError:
+    from apache_beam import version as beam_version
+    return beam_version.__version__
+
+
+def run(
+    version=None,
+    runner='direct',
+    ios=(),
+    list_versions=False,
+    list_ios=False,
+    list_runners=False,
+    debug=False,
+    sqlline_args=(),
+    beam_home=None):
+  """Runs `beam sql` and returns the process exit code."""
+  if list_versions:
+    return _list_versions()
+  if list_ios:
+    return _list_ios()
+
+  resolved_version = _resolve_version(version)
+  if list_runners:
+    return _list_runners(resolved_version)
+
+  runner_key = _normalize_runner(runner)
+  clean_ios = _normalize_ios(ios)
+  java_bin, java_home = _find_java()
+
+  home = beam_home or os.path.expanduser(os.environ.get('BEAM_HOME', 
'~/.beam'))
+  if os.path.islink(home):
+    raise SqlError(
+        f'refusing symlinked BEAM_HOME directory {home!r}', _EXIT_USAGE)
+  cache_dir = os.path.join(home, 'cache')
+  os.makedirs(cache_dir, mode=0o700, exist_ok=True)
+  jar_path = os.path.join(
+      cache_dir,
+      
f"beam-{resolved_version}_runner-{runner_key}_ios-{'-'.join(clean_ios)}.jar"
+  )
+  if os.path.islink(cache_dir) or os.path.islink(jar_path):
+    raise SqlError(
+        f'refusing symlinked Beam SQL cache path {jar_path!r}', _EXIT_USAGE)
+
+  with _file_lock(f'{jar_path}.lock'):
+    cached_ready = _is_valid_jar(jar_path)
+
+  if cached_ready:
+    print(
+        f'Using cached Beam SQL JAR: {_sanitize_log_token(jar_path)}',
+        file=sys.stderr)
+  else:
+    wrapper_jar = _ensure_maven_wrapper(home)
+    _build_shaded_jar(
+        wrapper_jar,
+        java_home=java_home,
+        version=resolved_version,
+        runner_key=runner_key,
+        ios=clean_ios,
+        jar_path=jar_path,
+        debug=debug,
+        java_bin=java_bin)
+
+  cmd = [java_bin, '-cp', jar_path, _MAIN_CLASS, *sqlline_args]
+  if debug:
+    print('+ ' + ' '.join(_sanitize_log_token(c) for c in cmd), 
file=sys.stderr)
+  with subprocess.Popen(cmd) as proc:
+    while True:
+      try:
+        rc = proc.wait()
+        return 128 - rc if rc < 0 else rc
+      except KeyboardInterrupt:
+        pass
+
+
+def _resolve_version(version):
+  """Returns the Maven release version to use for Beam SQL artifacts."""
+  if version:
+    if '..' in version or not _VALID_ARTIFACT_PART.match(version.lower()):
+      raise SqlError(f'invalid Beam version {version!r}', _EXIT_USAGE)
+    return re.sub(r'-snapshot$', '-SNAPSHOT', version, flags=re.IGNORECASE)
+  installed = _installed_beam_version()
+  if ('.dev' not in installed and
+      not re.search(r'rc\d+$', installed, re.IGNORECASE) and
+      '..' not in installed and _VALID_ARTIFACT_PART.match(installed.lower())):
+    return re.sub(r'-snapshot$', '-SNAPSHOT', installed, flags=re.IGNORECASE)
+  # A development checkout (`2.XX.0.dev`) has no published Maven JARs; fall
+  # back to the latest release on Maven Central, matching `beam-sql.sh`.
+  versions = _fetch_maven_versions()
+  if not versions:
+    raise SqlError(
+        f'installed Apache Beam version is {installed!r} (unreleased) and '
+        'Maven Central could not be reached; pass --version <release>',
+        _EXIT_FAILED)
+  latest = versions[0]
+  print(
+      f'Installed Beam is {_sanitize_log_token(installed)}; using latest '
+      f'released Beam SQL {_sanitize_log_token(latest)} '
+      '(override with --version).',
+      file=sys.stderr)
+  return latest
+
+
+def _normalize_runner(runner):
+  name = (runner or 'direct').strip().lower()
+  if name.endswith('runner') and name != 'runner':
+    name = name[:-len('runner')]
+  if name not in _RUNNER_ARTIFACTS:
+    raise SqlError(
+        f"unsupported runner {runner!r} for beam sql; "
+        f"supported runners: {', '.join(_RUNNER_ARTIFACTS)}",
+        _EXIT_USAGE)
+  return name
+
+
+def _normalize_ios(ios):
+  seen = set()
+  for raw in ios:
+    name = raw.strip().lower()
+    if not name or '..' in name or not _VALID_ARTIFACT_PART.match(name):
+      raise SqlError(
+          f'invalid --io connector {raw!r}; run `beam sql --list-ios` to see '
+          'available connectors',
+          _EXIT_USAGE)
+    seen.add(name)
+  return sorted(seen)
+
+
+_JAVA_VERSION_RE = re.compile(r'version "(\d+)(?:\.(\d+))?')
+_MIN_JAVA_MAJOR = 11
+_WARN_UNSUPPORTED_JAVA_MAJOR = 26
+
+
+def _find_java():
+  """Locates `java`, verifies Java 11+, and returns `(java_bin, java_home)`."""
+  java_exe = 'java.exe' if os.name == 'nt' else 'java'
+  env_home = os.environ.get('JAVA_HOME', '').strip()
+  if env_home:
+    java_bin = os.path.join(env_home, 'bin', java_exe)
+    if not os.path.isfile(java_bin) and os.name == 'nt':
+      fallback = os.path.join(env_home, 'bin', 'java')
+      if os.path.isfile(fallback):
+        java_bin = fallback
+    if not os.path.isfile(java_bin):
+      raise SqlError(
+          f'JAVA_HOME={env_home!r} does not contain bin/{java_exe}; '
+          'Beam SQL requires Java 11 or newer',
+          _EXIT_MISSING_DEPENDENCY)
+  else:
+    java_bin = shutil.which('java')
+    if not java_bin:
+      raise SqlError(
+          "'java' command not found; Beam SQL requires Java 11 or newer. "
+          'Install OpenJDK 11+ or set JAVA_HOME.',
+          _EXIT_MISSING_DEPENDENCY)
+
+  try:
+    proc = subprocess.run([java_bin, '-version'],
+                          capture_output=True,
+                          text=True,
+                          check=False)
+  except OSError as e:
+    raise SqlError(
+        f'could not execute {java_bin!r}: {e}\n'
+        '  Beam SQL requires Java 11 or newer; install OpenJDK 11+ or set '
+        'JAVA_HOME',
+        _EXIT_MISSING_DEPENDENCY) from None
+
+  match = _JAVA_VERSION_RE.search(f'{proc.stderr}\n{proc.stdout}')
+  if proc.returncode != 0 or not match:
+    raise SqlError(
+        'no working Java runtime found; Beam SQL requires Java 11 or newer. '
+        'Install OpenJDK 11+ or set JAVA_HOME.',
+        _EXIT_MISSING_DEPENDENCY)
+
+  first, second = int(match.group(1)), int(match.group(2) or 0)
+  major = second if first == 1 else first
+  if major < _MIN_JAVA_MAJOR:
+    raise SqlError(
+        f'Beam SQL requires Java {_MIN_JAVA_MAJOR} or newer '
+        f'(found Java {major} at {java_bin}). '
+        'Install OpenJDK 11+ or set JAVA_HOME.',
+        _EXIT_MISSING_DEPENDENCY)
+  if major >= _WARN_UNSUPPORTED_JAVA_MAJOR:
+    print(
+        f'warning: Java {major} ({java_bin}) may be newer than Beam SQL '
+        'supports; if queries fail with a ByteBuddy error, set JAVA_HOME to '
+        'Java 11, 17, or 21',
+        file=sys.stderr)
+
+  java_home = env_home or os.path.dirname(
+      os.path.dirname(os.path.realpath(java_bin)))
+  return java_bin, java_home
+
+
+# Same Maven Wrapper, Iceberg, GCS connector, and repository constants as
+# `scripts/beam-sql.sh` on upstream master (#40958, #41090).

Review Comment:
   Nit: since these versions and the POM dependency/shading rules (delta, 
iceberg, the Conscrypt exclusion, etc.) now live in both scripts/beam-sql.sh 
and sql.py, could we also add a quick comment in scripts/beam-sql.sh pointing 
here so future updates don't accidentally update one and miss the other?



-- 
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