|
| 1 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +# or more contributor license agreements. See the NOTICE file |
| 3 | +# distributed with this work for additional information |
| 4 | +# regarding copyright ownership. The ASF licenses this file |
| 5 | +# to you under the Apache License, Version 2.0 (the |
| 6 | +# "License"); you may not use this file except in compliance |
| 7 | +# with the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, |
| 12 | +# software distributed under the License is distributed on an |
| 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +# KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations |
| 16 | +# under the License. |
| 17 | + |
| 18 | +import re |
| 19 | +from datetime import datetime |
| 20 | +from re import Pattern |
| 21 | +from typing import Any, TYPE_CHECKING |
| 22 | + |
| 23 | +from flask_babel import lazy_gettext as _ |
| 24 | +from sqlalchemy import types |
| 25 | + |
| 26 | +from superset import db |
| 27 | +from superset.constants import QUERY_CANCEL_KEY, QUERY_EARLY_CANCEL_KEY, TimeGrain |
| 28 | +from superset.db_engine_specs.base import BaseEngineSpec, DatabaseCategory |
| 29 | +from superset.db_engine_specs.exceptions import ( |
| 30 | + SupersetDBAPIDatabaseError, |
| 31 | + SupersetDBAPIDataError, |
| 32 | + SupersetDBAPIError, |
| 33 | + SupersetDBAPIOperationalError, |
| 34 | + SupersetDBAPIProgrammingError, |
| 35 | +) |
| 36 | +from superset.errors import SupersetErrorType |
| 37 | +from superset.utils.core import GenericDataType, QueryStatus |
| 38 | + |
| 39 | +if TYPE_CHECKING: |
| 40 | + from superset.models.core import Database |
| 41 | + from superset.models.sql_lab import Query |
| 42 | + |
| 43 | +# Error messages surfaced by the ``opteryx-sqlalchemy`` driver. The engine |
| 44 | +# wraps object names in Markdown emphasis (`name` or *name*). |
| 45 | +CONNECTION_ACCESS_DENIED_REGEX = re.compile(r"Authentication error: (?P<detail>.*)") |
| 46 | +TABLE_DOES_NOT_EXIST_REGEX = re.compile( |
| 47 | + r"Dataset [`*]?(?P<table>[^`*]+?)[`*]? cannot be found" |
| 48 | +) |
| 49 | +COLUMN_DOES_NOT_EXIST_REGEX = re.compile( |
| 50 | + r"Column [`*]?(?P<column>[^`*]+?)[`*]? cannot be found" |
| 51 | +) |
| 52 | + |
| 53 | + |
| 54 | +def _time_bucket(magnitude: int, unit: str) -> str: |
| 55 | + """ |
| 56 | + Fixed-width buckets anchored at the Unix epoch. |
| 57 | +
|
| 58 | + ``TIME_BUCKET`` takes the magnitude first and the value last; the magnitude |
| 59 | + and unit must both be literals. |
| 60 | + """ |
| 61 | + return f"TIME_BUCKET({magnitude}, '{unit}', CAST({{col}} AS TIMESTAMP))" |
| 62 | + |
| 63 | + |
| 64 | +def _date_trunc(unit: str) -> str: |
| 65 | + # The CAST lets DATE (and string) columns be truncated: Opteryx's |
| 66 | + # DATE_TRUNC is only guaranteed over TIMESTAMP operands. |
| 67 | + return f"DATE_TRUNC('{unit}', CAST({{col}} AS TIMESTAMP))" |
| 68 | + |
| 69 | + |
| 70 | +class OpteryxEngineSpec(BaseEngineSpec): |
| 71 | + """ |
| 72 | + Engine spec for Opteryx (https://opteryx.app), a hosted SQL service built |
| 73 | + on the open-source Opteryx query engine. |
| 74 | +
|
| 75 | + Datasets are addressed as ``workspace.collection.dataset``. The |
| 76 | + ``opteryx-sqlalchemy`` dialect reports ``workspace.collection`` as the |
| 77 | + schema, so Superset lists one schema per collection and renders table |
| 78 | + references in the three-part form users write. |
| 79 | + """ |
| 80 | + |
| 81 | + engine = "opteryx" |
| 82 | + engine_name = "Opteryx" |
| 83 | + default_driver = "http" |
| 84 | + drivers = {"http": "Opteryx jobs API over HTTPS"} |
| 85 | + sqlalchemy_uri_placeholder = ( |
| 86 | + "opteryx://{client_id}:{client_secret}@opteryx.app:443/?ssl=true" |
| 87 | + ) |
| 88 | + |
| 89 | + # The driver talks to an HTTPS API whose service hostnames are derived from |
| 90 | + # the host in the URI; an SSH tunnel would replace that host with a local |
| 91 | + # forwarding address. |
| 92 | + disable_ssh_tunneling = True |
| 93 | + supports_file_upload = False |
| 94 | + |
| 95 | + # ``SELECT * FROM (WITH ... SELECT ...) AS virtual_table`` is rejected: |
| 96 | + # the CTE is not visible inside the derived table. |
| 97 | + allows_cte_in_subquery = False |
| 98 | + |
| 99 | + # The job ID that ``cancel_query`` needs exists only once the statement is |
| 100 | + # submitted; ``execute`` submits without waiting (see below). |
| 101 | + has_query_id_before_execute = False |
| 102 | + |
| 103 | + metadata = { |
| 104 | + "description": ( |
| 105 | + "Opteryx is a hosted SQL workspace on an open-source query engine. " |
| 106 | + "It queries files in S3 and GCS, Iceberg tables and PostgreSQL " |
| 107 | + "databases where they live." |
| 108 | + ), |
| 109 | + "logo": "opteryx.svg", |
| 110 | + "homepage_url": "https://opteryx.app/", |
| 111 | + "docs_url": "https://docs.opteryx.app/", |
| 112 | + "categories": [ |
| 113 | + DatabaseCategory.QUERY_ENGINES, |
| 114 | + DatabaseCategory.HOSTED_OPEN_SOURCE, |
| 115 | + ], |
| 116 | + "pypi_packages": ["opteryx-sqlalchemy"], |
| 117 | + "connection_string": ( |
| 118 | + "opteryx://{client_id}:{client_secret}@opteryx.app:443/?ssl=true" |
| 119 | + ), |
| 120 | + "default_port": 443, |
| 121 | + "parameters": { |
| 122 | + "client_id": "Client ID of an Opteryx API client", |
| 123 | + "client_secret": "Client secret of that API client", |
| 124 | + }, |
| 125 | + "notes": ( |
| 126 | + "Authenticates with OAuth client credentials. Tables are listed " |
| 127 | + "per collection: the schema is `workspace.collection`, and SQL " |
| 128 | + "refers to datasets as `workspace.collection.dataset`." |
| 129 | + ), |
| 130 | + "drivers": [ |
| 131 | + { |
| 132 | + "name": "opteryx-sqlalchemy", |
| 133 | + "pypi_package": "opteryx-sqlalchemy", |
| 134 | + "connection_string": ( |
| 135 | + "opteryx://{client_id}:{client_secret}@opteryx.app:443/?ssl=true" |
| 136 | + ), |
| 137 | + "is_recommended": True, |
| 138 | + } |
| 139 | + ], |
| 140 | + } |
| 141 | + |
| 142 | + _time_grain_expressions = { |
| 143 | + None: "{col}", |
| 144 | + TimeGrain.SECOND: _date_trunc("second"), |
| 145 | + TimeGrain.FIVE_SECONDS: _time_bucket(5, "second"), |
| 146 | + TimeGrain.THIRTY_SECONDS: _time_bucket(30, "second"), |
| 147 | + TimeGrain.MINUTE: _date_trunc("minute"), |
| 148 | + TimeGrain.FIVE_MINUTES: _time_bucket(5, "minute"), |
| 149 | + TimeGrain.TEN_MINUTES: _time_bucket(10, "minute"), |
| 150 | + TimeGrain.FIFTEEN_MINUTES: _time_bucket(15, "minute"), |
| 151 | + TimeGrain.THIRTY_MINUTES: _time_bucket(30, "minute"), |
| 152 | + TimeGrain.HALF_HOUR: _time_bucket(30, "minute"), |
| 153 | + TimeGrain.HOUR: _date_trunc("hour"), |
| 154 | + TimeGrain.SIX_HOURS: _time_bucket(6, "hour"), |
| 155 | + TimeGrain.DAY: _date_trunc("day"), |
| 156 | + # Opteryx weeks start on Monday (ISO). |
| 157 | + TimeGrain.WEEK: _date_trunc("week"), |
| 158 | + TimeGrain.WEEK_STARTING_MONDAY: _date_trunc("week"), |
| 159 | + TimeGrain.WEEK_STARTING_SUNDAY: ( |
| 160 | + "DATE_TRUNC('week', CAST({col} AS TIMESTAMP) + INTERVAL '1' DAY)" |
| 161 | + " - INTERVAL '1' DAY" |
| 162 | + ), |
| 163 | + TimeGrain.WEEK_ENDING_SATURDAY: ( |
| 164 | + "DATE_TRUNC('week', CAST({col} AS TIMESTAMP) + INTERVAL '1' DAY)" |
| 165 | + " + INTERVAL '5' DAY" |
| 166 | + ), |
| 167 | + TimeGrain.WEEK_ENDING_SUNDAY: ( |
| 168 | + "DATE_TRUNC('week', CAST({col} AS TIMESTAMP)) + INTERVAL '6' DAY" |
| 169 | + ), |
| 170 | + TimeGrain.MONTH: _date_trunc("month"), |
| 171 | + TimeGrain.QUARTER: _date_trunc("quarter"), |
| 172 | + TimeGrain.QUARTER_YEAR: _date_trunc("quarter"), |
| 173 | + TimeGrain.YEAR: _date_trunc("year"), |
| 174 | + } |
| 175 | + |
| 176 | + # Opteryx's storage types (INT8..INT64, FLOAT32/64, BOOL, NVARCHAR, ...) |
| 177 | + # are covered by the base mappings; unsigned integers are not. |
| 178 | + column_type_mappings = ( |
| 179 | + ( |
| 180 | + re.compile(r"^uint(8|16|32|64)?$", re.IGNORECASE), |
| 181 | + types.BigInteger(), |
| 182 | + GenericDataType.NUMERIC, |
| 183 | + ), |
| 184 | + ) |
| 185 | + |
| 186 | + custom_errors: dict[Pattern[str], tuple[str, SupersetErrorType, dict[str, Any]]] = { |
| 187 | + CONNECTION_ACCESS_DENIED_REGEX: ( |
| 188 | + _( |
| 189 | + "Opteryx rejected the client credentials: %(detail)s. Check the " |
| 190 | + "client ID and secret." |
| 191 | + ), |
| 192 | + SupersetErrorType.CONNECTION_ACCESS_DENIED_ERROR, |
| 193 | + {"invalid": ["username", "password"]}, |
| 194 | + ), |
| 195 | + TABLE_DOES_NOT_EXIST_REGEX: ( |
| 196 | + _( |
| 197 | + 'The dataset "%(table)s" does not exist or is not visible to this ' |
| 198 | + "client. Datasets are named workspace.collection.dataset." |
| 199 | + ), |
| 200 | + SupersetErrorType.TABLE_DOES_NOT_EXIST_ERROR, |
| 201 | + {}, |
| 202 | + ), |
| 203 | + COLUMN_DOES_NOT_EXIST_REGEX: ( |
| 204 | + _('The column "%(column)s" does not exist.'), |
| 205 | + SupersetErrorType.COLUMN_DOES_NOT_EXIST_ERROR, |
| 206 | + {}, |
| 207 | + ), |
| 208 | + } |
| 209 | + |
| 210 | + @classmethod |
| 211 | + def get_dbapi_exception_mapping(cls) -> dict[type[Exception], type[Exception]]: |
| 212 | + # pylint: disable=import-outside-toplevel |
| 213 | + try: |
| 214 | + from sqlalchemy_dialect import dbapi |
| 215 | + except ImportError: |
| 216 | + return {} |
| 217 | + |
| 218 | + # The driver raises the PEP 249 classes directly (lookup is by exact |
| 219 | + # type): OperationalError for authentication, connection and timeout |
| 220 | + # failures, ProgrammingError for statements the engine rejects. |
| 221 | + return { |
| 222 | + dbapi.Error: SupersetDBAPIError, |
| 223 | + dbapi.InterfaceError: SupersetDBAPIError, |
| 224 | + dbapi.DatabaseError: SupersetDBAPIDatabaseError, |
| 225 | + dbapi.DataError: SupersetDBAPIDataError, |
| 226 | + dbapi.IntegrityError: SupersetDBAPIDatabaseError, |
| 227 | + dbapi.InternalError: SupersetDBAPIDatabaseError, |
| 228 | + dbapi.NotSupportedError: SupersetDBAPIDatabaseError, |
| 229 | + dbapi.OperationalError: SupersetDBAPIOperationalError, |
| 230 | + dbapi.ProgrammingError: SupersetDBAPIProgrammingError, |
| 231 | + } |
| 232 | + |
| 233 | + @classmethod |
| 234 | + def get_function_names(cls, database: "Database") -> list[str]: |
| 235 | + # The driver ships the engine's function names, so autocomplete needs |
| 236 | + # no query (every Opteryx query counts against the account's quota). |
| 237 | + # pylint: disable=import-outside-toplevel |
| 238 | + try: |
| 239 | + from sqlalchemy_dialect.functions import FUNCTION_NAMES |
| 240 | + except ImportError: |
| 241 | + return [] |
| 242 | + return list(FUNCTION_NAMES) |
| 243 | + |
| 244 | + @classmethod |
| 245 | + def execute( |
| 246 | + cls, |
| 247 | + cursor: Any, |
| 248 | + query: str, |
| 249 | + database: "Database", |
| 250 | + **kwargs: Any, |
| 251 | + ) -> None: |
| 252 | + # SQL Lab passes ``async_``: submit the job and return, so its ID can be |
| 253 | + # recorded for Stop before the results are waited on. Fetching (or |
| 254 | + # reading the cursor's description) waits for the job. |
| 255 | + if not kwargs.get("async_") or not hasattr(cursor, "execute_async"): |
| 256 | + super().execute(cursor, query, database, **kwargs) |
| 257 | + return |
| 258 | + try: |
| 259 | + cursor.execute_async(query) |
| 260 | + except Exception as ex: |
| 261 | + raise cls.get_dbapi_mapped_exception(ex) from ex |
| 262 | + |
| 263 | + @classmethod |
| 264 | + def get_cancel_query_id(cls, cursor: Any, query: "Query") -> str | None: |
| 265 | + return getattr(cursor, "statement_handle", None) |
| 266 | + |
| 267 | + @classmethod |
| 268 | + def prepare_cancel_query(cls, query: "Query") -> None: |
| 269 | + # Submitting a job takes a round trip or two, so a Stop can arrive |
| 270 | + # before its ID is recorded; flag it for ``handle_cursor``. |
| 271 | + if QUERY_CANCEL_KEY not in query.extra: |
| 272 | + query.set_extra_json_key(QUERY_EARLY_CANCEL_KEY, True) |
| 273 | + |
| 274 | + @classmethod |
| 275 | + def handle_cursor(cls, cursor: Any, query: "Query") -> None: |
| 276 | + # Called once the job ID is recorded: cancel the job if Stop came first. |
| 277 | + cancel_query_id = cls.get_cancel_query_id(cursor, query) |
| 278 | + if cancel_query_id is None: |
| 279 | + return |
| 280 | + db.session.refresh(query) |
| 281 | + if ( |
| 282 | + query.extra.get(QUERY_EARLY_CANCEL_KEY) |
| 283 | + or query.status == QueryStatus.STOPPED |
| 284 | + ): |
| 285 | + cls.cancel_query(cursor, query, cancel_query_id) |
| 286 | + |
| 287 | + @classmethod |
| 288 | + def cancel_query(cls, cursor: Any, query: "Query", cancel_query_id: str) -> bool: |
| 289 | + # Job IDs look like ``20261108120000-a1b2c3d4e5f6g7h8``; the ID becomes |
| 290 | + # part of the cancel URL. |
| 291 | + if not cls.validate_cancel_query_id(cancel_query_id, r"^[A-Za-z0-9-]+$"): |
| 292 | + return False |
| 293 | + try: |
| 294 | + return bool(cursor.cancel(cancel_query_id)) |
| 295 | + except Exception: # pylint: disable=broad-except |
| 296 | + return False |
| 297 | + |
| 298 | + @classmethod |
| 299 | + def epoch_to_dttm(cls) -> str: |
| 300 | + return "FROM_UNIXTIME({col})" |
| 301 | + |
| 302 | + @classmethod |
| 303 | + def convert_dttm( |
| 304 | + cls, target_type: str, dttm: datetime, db_extra: dict[str, Any] | None = None |
| 305 | + ) -> str | None: |
| 306 | + # Opteryx rejects type-prefixed literals (TIMESTAMP '...'); CAST is the |
| 307 | + # supported spelling. |
| 308 | + sqla_type = cls.get_sqla_column_type(target_type) |
| 309 | + if isinstance(sqla_type, types.Date): |
| 310 | + return f"CAST('{dttm.date().isoformat()}' AS DATE)" |
| 311 | + if isinstance(sqla_type, types.DateTime): |
| 312 | + dttm_formatted = dttm.isoformat(sep=" ", timespec="microseconds") |
| 313 | + return f"CAST('{dttm_formatted}' AS TIMESTAMP)" |
| 314 | + return None |
0 commit comments