villebro commented on code in PR #14225: URL: https://github.com/apache/superset/pull/14225#discussion_r1043915605
########## superset/db_engine_specs/superset.py: ########## @@ -0,0 +1,435 @@ +# 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. + +""" +A native Superset database. + +This module introduces a new SQLAlchemy dialect, ``superset://``, together with a +corresponding DB engine spec. When using the native database users can query any table in +any other database. + +For example, to query the ``birth_names`` that comes in the ``examples`` database: + + SELECT * FROM "superset.examples.birth_names"; + +Queries can join data from multiple databases, and data can be read from one table and +inserted into another: + + INSERT INTO "superset.db2.table" SELECT * FROM "superset.db1.table"; + +Note that ``CREATE TABLE`` is not supported, so the table needs be created beforehand. + +Also be careful about performance. Only filtering, sorting, limiting and offsetting are +done in the databases. Joins and aggregations are done using SQLite in memory, so it's +recommended to configure the native database to run asynchronous queries, to prevent +overloading the web server. +""" + +import datetime +import operator +import urllib.parse +from functools import wraps +from typing import ( + Any, + Callable, + cast, + Dict, + Iterator, + List, + Optional, + Tuple, + Type, + TypeVar, +) + +from shillelagh.adapters.base import Adapter +from shillelagh.backends.apsw.dialects.base import APSWDialect +from shillelagh.exceptions import ProgrammingError +from shillelagh.fields import ( + Blob, + Boolean, + Date, + DateTime, + Field, + Float, + Integer, + Order, + String, + Time, +) +from shillelagh.filters import Equal, Filter, Range +from shillelagh.typing import RequestedOrder, Row +from sqlalchemy import MetaData, Table +from sqlalchemy.engine.url import URL +from sqlalchemy.exc import NoSuchTableError +from sqlalchemy.sql import Select, select + +from superset import db, security_manager, sql_parse +from superset.db_engine_specs.sqlite import SqliteEngineSpec + + +class SupersetEngineSpec(SqliteEngineSpec): + """ + Internal engine for Superset + + This DB engine spec is a meta-database. It uses the shillelagh library + to build a DB that can operate across different Superset databases. + """ + + engine = "superset" + engine_name = "Superset native database" + default_driver = "" + sqlalchemy_uri_placeholder = "superset://" + + supports_file_upload = False + + +# pylint: disable=abstract-method +class SupersetAPSWDialect(APSWDialect): + + """ + A SQLAlchemy dialect for an internal Superset engine. + + This dialect allows query to be executed across different Superset + databases. For example, to read data from the `birth_names` table in the + `examples` databases: + + >>> engine = create_engine('superset://') + >>> conn = engine.connect() + >>> results = conn.execute('SELECT * FROM "superset.examples.birth_names"') + + Queries can also join data across different Superset databases. + + The dialect is built in top of the shillelagh library, leveraging SQLite to + create virtual tables on-the-fly proxying Superset tables. The + `SupersetShillelaghAdapter` adapter is responsible for returning data when a + Superset table is accessed. + """ + + name = "superset" + + def create_connect_args(self, url: URL) -> Tuple[Tuple[()], Dict[str, Any]]: + return ( + (), + { + "path": ":memory:", + "adapters": ["superset"], + "adapter_kwargs": {}, + "safe": True, + "isolation_level": self.isolation_level, + }, + ) + + +# pylint: disable=invalid-name +F = TypeVar("F", bound=Callable[..., Any]) + + +def check_dml(method: F) -> F: + """ + Decorator that prevents DML against databases where it's not allowed. + """ + + @wraps(method) + def wrapper(self: "SupersetShillelaghAdapter", *args: Any, **kwargs: Any) -> Any: + # pylint: disable=protected-access + if not self._allow_dml: + raise ProgrammingError(f'DML not enabled in database "{self.database}"') + return method(self, *args, **kwargs) + + return cast(F, wrapper) + + +def has_rowid(method: F) -> F: + """ + Decorator that prevents updates/deletes on tables without a rowid. + """ + + @wraps(method) + def wrapper(self: "SupersetShillelaghAdapter", *args: Any, **kwargs: Any) -> Any: + # pylint: disable=protected-access + if not self._rowid: + raise ProgrammingError( + "Can only modify data in a table with a single, integer, primary key" + ) + return method(self, *args, **kwargs) + + return cast(F, wrapper) + + +# pylint: disable=too-many-instance-attributes +class SupersetShillelaghAdapter(Adapter): Review Comment: For clarity, would it make sense to place these in a separate package? It feels like this may be outside the scope of a typical db engine spec, and if we were to encapsulate this in a separate package (e.g. under `/extensions` or even just under `/db_engine_specs`, then it would be more clear that this is in fact not a db engine spec, but actually a Shillelagh adapter ########## superset/config.py: ########## @@ -1327,6 +1327,8 @@ def EMAIL_HEADER_MUTATOR( # pylint: disable=invalid-name,unused-argument # Some sqlalchemy connection strings can open Superset to security risks. # Typically these should not be allowed. PREVENT_UNSAFE_DB_CONNECTIONS = True +# Allows users to add a ``superset://`` DB that can query across databases. +ENABLE_SUPERSET_META_DB = False Review Comment: I know we aren't very consistent in using configs vs feature flags, but should this be a FF until it's been considered stable? -- 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] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
