You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by "fdolce (via GitHub)" <gi...@apache.org> on 2026/09/21 09:32:10 UTC
[PR] [FLINK-40427][python] Add catalog management and catalog table I/O to DataFrame API [flink]
fdolce opened a new pull request, #29262:
URL: https://github.com/apache/flink/pull/29262
## What is the purpose of the change
This pull request adds catalog support to the PyFlink DataFrame API. Until now a DataFrame could only be created from in-memory data or via `read_generic`, and written via `write_generic`. Users could not create or switch catalogs, nor read from or write to tables registered in a catalog, without dropping down to the Table API or SQL. This change exposes catalog and database management as module-level functions and adds `read_catalog_table` / `DataFrame.write_catalog_table` for catalog table I/O, mirroring `CREATE CATALOG`, `USE CATALOG`, `USE`, and `INSERT [OVERWRITE] INTO`.
It also makes Flink-side user errors friendlier: `ValidationException` and `SqlParserException` raised from the JVM (unknown table, malformed path, invalid connector options, bad watermark expression, ...) are now surfaced as a Python `ValueError` carrying Flink's message and chained to the original `Py4JJavaError`, instead of a raw Py4J stack trace. This applies to the new functions and to the existing `read_generic` / `write_generic`.
## Brief change log
- New module `pyflink.dataframe.catalog` with `create_catalog`, `get_catalog`, `use_catalog`, `get_current_catalog`, `list_catalogs`, `use_database`, `get_current_database`, `list_databases`, all operating on the shared DataFrame `TableEnvironment`
- New `pyflink.dataframe.read_catalog_table(path)` that resolves `table`, `db.table`, or `catalog.db.table` against the current catalog/database
- New `DataFrame.write_catalog_table(path, *, overwrite=False)`; the insert is shared with `write_generic` through a private `_execute_insert` helper that keeps the wait-for-completion behaviour on local/MiniCluster execution
- New module `pyflink.dataframe.errors` with `_raise_as_value_error`, which translates Flink `ValidationException` / `SqlParserException` (including subclasses) into `ValueError` and re-raises everything else unchanged, so exceptions PyFlink already maps (e.g. `CatalogException`) keep their type
- `read_generic` and `write_generic` now route Flink errors through the same translation
- Python-side argument validation (`TypeError` for wrong types, `ValueError` for empty names/keys, duplicate catalog names, unknown catalog/database names)
- All new public functions re-exported from `pyflink.dataframe` and marked `@PublicEvolving`
- Sphinx docs: new `catalog.rst` reference page, `read_catalog_table` and `DataFrame.write_catalog_table` added to `io.rst`
## Verifying this change
This change added tests and can be verified as follows:
- `pyflink/dataframe/tests/test_catalog.py` (`CatalogTests`): descriptor construction for `create_catalog`, argument validation, duplicate catalog rejection, catalog/database navigation, unknown-name rejection, translation of Flink `ValidationException` into `ValueError`, non-user errors passing through untranslated, and use of the DataFrame `TableEnvironment
- `pyflink/dataframe/tests/test_io.py` (`CatalogTableIOTests`): path resolution for `read_catalog_table` (short, qualified, and fully qualified paths), invalid path handling, `write_catalog_table` argument passing incl. `overwrite`, wait-for-completion on local and MiniCluster execution targets, error translation for both read and write, and an end-to-end round trmemory` catalog
- `test_io.py` also adds `test_read_geners` and `test_write_generic_translates_flink_erroric I/O
## Does this pull request potentially affearts:
- Dependencies (does it add or upgrade a
- The public API, i.e., is any changed class annotated with `@Public(Evolving)`: yes (new `@PublicEvolving` functions in `pyflink.dataframe` and a new on `DataFrame`)
- The serializers: no
- The runtime per-record code paths (performance sensitive): no
- Anything that affects deployment or rets components), Checkpointing,Kubernetes/Yarn, ZooKeeper: no
- The S3 file system connector: no
## Documentation
- Does this pull request introduce a new feature? yes
- If yes, how is the feature documented?ce: new `catalog.rst`, updated `io.rst`)
and docstrings with examples on every new
---
##### Was generative AI tooling used to co-author this PR?
- [X] Yes (please specify the tool below)
Generated-by: Claude Code
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40427][python] Add catalog management and catalog table I/O to DataFrame API [flink]
Posted by "dianfu (via GitHub)" <gi...@apache.org>.
dianfu commented on code in PR #29262:
URL: https://github.com/apache/flink/pull/29262#discussion_r4092277839
##########
flink-python/pyflink/dataframe/io.py:
##########
@@ -189,4 +185,155 @@ def read_generic(
source_schema = _build_source_schema(schema, computed_columns, watermark)
descriptor = _build_generic_descriptor(connector, options, source_schema)
table_environment = get_or_create_table_environment()
- return DataFrame(table_environment.from_descriptor(descriptor))
+ try:
+ table = table_environment.from_descriptor(descriptor)
+ except Exception as error:
+ _raise_as_value_error(error)
+ return DataFrame(table)
+
+
+def _extend_catalog_table(
+ table: Table,
+ computed_columns: Optional[Dict[str, str]],
+ watermark: Optional[Tuple[str, str]],
+) -> Table:
+ """
+ Read the catalog table behind ``table`` with extra computed columns and, optionally, a
+ different watermark.
+
+ Flink has no way to add columns to an existing table at read time, so this builds a nameless
+ copy of the table definition with the new schema and reads from that instead. Everything else
+ is copied over unchanged: options, partition keys, distribution, snapshot, connection and
+ comment. The connector sees the same table it always did, only with more columns. The real
+ catalog table is not touched.
+
+ This is the same thing ``TableEnvironment.from(TableDescriptor)`` does in Java. We build the
+ ``CatalogTable`` ourselves because ``TableDescriptor`` cannot take a distribution or snapshot
+ object directly.
+
+ Tables whose catalog supplies the connector, such as Paimon or Hive, cannot be extended this
+ way: the copy has no catalog to ask, so it would not know which connector to use. That is why
+ the ``connector`` option is required.
+ """
+ jvm = get_gateway().jvm
+ catalog = jvm.org.apache.flink.table.catalog
+
+ source = table._j_table.getQueryOperation().getContextResolvedTable()
+ identifier = source.getIdentifier().asSummaryString()
+ source_table = source.getTable()
+ table_kind = source_table.getTableKind()
+ if table_kind != catalog.CatalogBaseTable.TableKind.TABLE:
+ raise ValueError(
+ f"{identifier} is a {table_kind.name().lower()}; computed columns and watermarks can "
+ f"only be added to tables"
+ )
+ if not source_table.getOptions().get("connector"):
Review Comment:
@fdolce Thanks a lot for the detailed explanation, makes much sense to me! Could you rebase the PR to resolve the conflicts with master? Let's address the remaining improvements in a follow-up ticket.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40427][python] Add catalog management and catalog table I/O to DataFrame API [flink]
Posted by "fdolce (via GitHub)" <gi...@apache.org>.
fdolce commented on PR #29262:
URL: https://github.com/apache/flink/pull/29262#issuecomment-5835270492
Uh, sorry, I missed that, will take a look.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40427][python] Add catalog management and catalog table I/O to DataFrame API [flink]
Posted by "dianfu (via GitHub)" <gi...@apache.org>.
dianfu commented on code in PR #29262:
URL: https://github.com/apache/flink/pull/29262#discussion_r4090832598
##########
flink-python/pyflink/dataframe/io.py:
##########
@@ -189,4 +185,155 @@ def read_generic(
source_schema = _build_source_schema(schema, computed_columns, watermark)
descriptor = _build_generic_descriptor(connector, options, source_schema)
table_environment = get_or_create_table_environment()
- return DataFrame(table_environment.from_descriptor(descriptor))
+ try:
+ table = table_environment.from_descriptor(descriptor)
+ except Exception as error:
+ _raise_as_value_error(error)
+ return DataFrame(table)
+
+
+def _extend_catalog_table(
+ table: Table,
+ computed_columns: Optional[Dict[str, str]],
+ watermark: Optional[Tuple[str, str]],
+) -> Table:
+ """
+ Read the catalog table behind ``table`` with extra computed columns and, optionally, a
+ different watermark.
+
+ Flink has no way to add columns to an existing table at read time, so this builds a nameless
+ copy of the table definition with the new schema and reads from that instead. Everything else
+ is copied over unchanged: options, partition keys, distribution, snapshot, connection and
+ comment. The connector sees the same table it always did, only with more columns. The real
+ catalog table is not touched.
+
+ This is the same thing ``TableEnvironment.from(TableDescriptor)`` does in Java. We build the
+ ``CatalogTable`` ourselves because ``TableDescriptor`` cannot take a distribution or snapshot
+ object directly.
+
+ Tables whose catalog supplies the connector, such as Paimon or Hive, cannot be extended this
+ way: the copy has no catalog to ask, so it would not know which connector to use. That is why
+ the ``connector`` option is required.
+ """
+ jvm = get_gateway().jvm
+ catalog = jvm.org.apache.flink.table.catalog
+
+ source = table._j_table.getQueryOperation().getContextResolvedTable()
+ identifier = source.getIdentifier().asSummaryString()
+ source_table = source.getTable()
+ table_kind = source_table.getTableKind()
+ if table_kind != catalog.CatalogBaseTable.TableKind.TABLE:
+ raise ValueError(
+ f"{identifier} is a {table_kind.name().lower()}; computed columns and watermarks can "
+ f"only be added to tables"
+ )
+ if not source_table.getOptions().get("connector"):
Review Comment:
This means that `computed_columns` and `watermark` cannot be used with catalog-native tables such as Paimon tables, Fluss tables, etc. Do you think it makes sense to also support this kind of table? If so, I'm fine to create a separate ticket for it if it requires substantial changes.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40427][python] Add catalog management and catalog table I/O to DataFrame API [flink]
Posted by "dianfu (via GitHub)" <gi...@apache.org>.
dianfu commented on code in PR #29262:
URL: https://github.com/apache/flink/pull/29262#discussion_r4069972382
##########
flink-python/pyflink/dataframe/io.py:
##########
@@ -189,4 +192,45 @@ def read_generic(
source_schema = _build_source_schema(schema, computed_columns, watermark)
descriptor = _build_generic_descriptor(connector, options, source_schema)
table_environment = get_or_create_table_environment()
- return DataFrame(table_environment.from_descriptor(descriptor))
+ try:
+ table = table_environment.from_descriptor(descriptor)
+ except Exception as error:
+ _raise_as_value_error(error)
+ return DataFrame(table)
+
+
+@PublicEvolving()
+def read_catalog_table(path: str) -> DataFrame:
Review Comment:
Could we make the `read_catalog_table` API accepts `computed_columns` and `watermark`?
##########
flink-python/pyflink/dataframe/catalog.py:
##########
@@ -0,0 +1,257 @@
+################################################################################
+# 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.
+################################################################################
+
+from typing import Dict, List, Optional
+
+from pyflink.common import Configuration
+from pyflink.dataframe.context import get_or_create_table_environment
+from pyflink.dataframe.errors import _raise_as_value_error
+from pyflink.table.catalog import Catalog, CatalogDescriptor
+from pyflink.util.api_stability_decorators import PublicEvolving
+
+__all__ = [
+ "create_catalog",
+ "get_catalog",
+ "use_catalog",
+ "get_current_catalog",
+ "list_catalogs",
+ "use_database",
+ "get_current_database",
+ "list_databases",
+]
+
+
+def _validate_name(name: str, what: str) -> None:
+ if not isinstance(name, str):
+ raise TypeError(f"{what} must be a string")
+ if not name:
+ raise ValueError(f"{what} must not be empty")
+
+
+def _validate_catalog_options(options: Dict[str, str]) -> None:
+ if not isinstance(options, dict):
+ raise TypeError("options must be a dict of string keys and values")
+ for key, value in options.items():
+ if not isinstance(key, str):
+ raise TypeError("option keys must be strings")
+ if not key:
+ raise ValueError("option keys must not be empty")
+ if not isinstance(value, str):
+ raise TypeError(f"option {key!r} must have a string value")
+
+
+@PublicEvolving()
+def create_catalog(name: str, options: Dict[str, str]) -> None:
+ """
+ Create a catalog in the environment used by DataFrame operations.
+
+ The ``type`` option selects the catalog factory, which must be available through Flink's
+ factory discovery mechanism. The remaining options are passed to that factory. This mirrors the
+ ``CREATE CATALOG`` SQL statement.
+
+ :param name: Name under which the catalog is created.
+ :param options: Catalog options, including the ``type`` option.
+ :raises TypeError: If ``name`` is not a string or ``options`` is not a dict of strings.
+ :raises ValueError: If ``name`` or an option key is empty, if a catalog named ``name`` already
+ exists, or if Flink cannot create a catalog from ``options``.
+ :raises ~pyflink.util.exceptions.CatalogException: If the catalog reports an error while
+ being created.
+
+ Example::
+
+ >>> import pyflink.dataframe as pf
+ >>> pf.create_catalog("my_catalog", {"type": "generic_in_memory"})
+ >>> pf.list_catalogs()
+ ['default_catalog', 'my_catalog']
+
+ .. versionadded:: 2.4.0
+ """
+ _validate_name(name, "name")
+ _validate_catalog_options(options)
+ table_environment = get_or_create_table_environment()
+ if name in table_environment.list_catalogs():
+ raise ValueError(f"a catalog named {name!r} already exists")
+
+ configuration = Configuration()
+ for key, value in options.items():
+ configuration.set_string(key, value)
+ descriptor = CatalogDescriptor.of(name, configuration)
+ try:
+ table_environment.create_catalog(name, descriptor)
+ except Exception as error:
+ _raise_as_value_error(error)
+
+
+@PublicEvolving()
+def get_catalog(name: str) -> Optional[Catalog]:
+ """
+ Return a registered catalog by name.
+
+ :param name: Name of the catalog.
+ :return: The :class:`~pyflink.table.catalog.Catalog`, or ``None`` if no catalog is registered
+ under ``name``.
+ :raises TypeError: If ``name`` is not a string.
+ :raises ValueError: If ``name`` is empty.
+
+ Example::
+
+ >>> import pyflink.dataframe as pf
+ >>> pf.create_catalog("my_catalog", {"type": "generic_in_memory"})
+ >>> pf.get_catalog("my_catalog").list_databases()
+ ['default']
+ >>> pf.get_catalog("missing") is None
+ True
+
+ .. versionadded:: 2.4.0
+ """
+ _validate_name(name, "name")
+ return get_or_create_table_environment().get_catalog(name)
+
+
+@PublicEvolving()
+def use_catalog(name: str) -> None:
+ """
+ Set the current catalog.
+
+ Table paths without a catalog part, such as ``my_table`` or ``my_database.my_table``, are
+ resolved against the current catalog. Switching the catalog also resets the current database to
+ the default database of the new catalog.
+
+ :param name: Name of a registered catalog.
+ :raises TypeError: If ``name`` is not a string.
+ :raises ValueError: If ``name`` is empty or no catalog named ``name`` exists.
+
+ Example::
+
+ >>> import pyflink.dataframe as pf
+ >>> pf.create_catalog("my_catalog", {"type": "generic_in_memory"})
+ >>> pf.use_catalog("my_catalog")
+ >>> pf.get_current_catalog()
+ 'my_catalog'
+
+ .. versionadded:: 2.4.0
+ """
+ _validate_name(name, "name")
+ table_environment = get_or_create_table_environment()
+ if name not in table_environment.list_catalogs():
+ raise ValueError(f"no catalog named {name!r} exists")
+ table_environment.use_catalog(name)
+
+
+@PublicEvolving()
+def get_current_catalog() -> str:
+ """
+ Return the name of the current catalog.
+
+ :return: The current catalog name.
+
+ Example::
+
+ >>> import pyflink.dataframe as pf
+ >>> pf.get_current_catalog()
+ 'default_catalog'
+
+ .. versionadded:: 2.4.0
+ """
+ return get_or_create_table_environment().get_current_catalog()
+
+
+@PublicEvolving()
+def list_catalogs() -> List[str]:
+ """
+ Return the names of all registered catalogs.
+
+ :return: Catalog names.
+
+ Example::
+
+ >>> import pyflink.dataframe as pf
+ >>> pf.list_catalogs()
+ ['default_catalog']
+
+ .. versionadded:: 2.4.0
+ """
+ return get_or_create_table_environment().list_catalogs()
+
+
+@PublicEvolving()
+def use_database(name: str) -> None:
+ """
+ Set the current database within the current catalog.
+
+ Table paths without a database part, such as ``my_table``, are resolved against the current
+ database.
+
+ :param name: Name of a database in the current catalog.
+ :raises TypeError: If ``name`` is not a string.
+ :raises ValueError: If ``name`` is empty or the current catalog has no database named
+ ``name``.
+
+ Example::
+
+ >>> import pyflink.dataframe as pf
+ >>> pf.use_database("default_database")
+ >>> pf.get_current_database()
+ 'default_database'
+
+ .. versionadded:: 2.4.0
+ """
+ _validate_name(name, "name")
+ table_environment = get_or_create_table_environment()
+ if name not in table_environment.list_databases():
Review Comment:
Do you think if it makes sense to remove the `list_databases` API call and rely on `use_database` which will perform the `databaseExists` check. It would avoid potential expensive remote or large catalog, the current precheck adds an unnecessary full-list RPC and may fail for a user who can access a known database but is not allowed to enumerate every database. We could also remove the `list_catalogs()` check in `use_catalog()`.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40427][python] Add catalog management and catalog table I/O to DataFrame API [flink]
Posted by "fdolce (via GitHub)" <gi...@apache.org>.
fdolce commented on code in PR #29262:
URL: https://github.com/apache/flink/pull/29262#discussion_r4091925474
##########
flink-python/pyflink/dataframe/io.py:
##########
@@ -189,4 +185,155 @@ def read_generic(
source_schema = _build_source_schema(schema, computed_columns, watermark)
descriptor = _build_generic_descriptor(connector, options, source_schema)
table_environment = get_or_create_table_environment()
- return DataFrame(table_environment.from_descriptor(descriptor))
+ try:
+ table = table_environment.from_descriptor(descriptor)
+ except Exception as error:
+ _raise_as_value_error(error)
+ return DataFrame(table)
+
+
+def _extend_catalog_table(
+ table: Table,
+ computed_columns: Optional[Dict[str, str]],
+ watermark: Optional[Tuple[str, str]],
+) -> Table:
+ """
+ Read the catalog table behind ``table`` with extra computed columns and, optionally, a
+ different watermark.
+
+ Flink has no way to add columns to an existing table at read time, so this builds a nameless
+ copy of the table definition with the new schema and reads from that instead. Everything else
+ is copied over unchanged: options, partition keys, distribution, snapshot, connection and
+ comment. The connector sees the same table it always did, only with more columns. The real
+ catalog table is not touched.
+
+ This is the same thing ``TableEnvironment.from(TableDescriptor)`` does in Java. We build the
+ ``CatalogTable`` ourselves because ``TableDescriptor`` cannot take a distribution or snapshot
+ object directly.
+
+ Tables whose catalog supplies the connector, such as Paimon or Hive, cannot be extended this
+ way: the copy has no catalog to ask, so it would not know which connector to use. That is why
+ the ``connector`` option is required.
+ """
+ jvm = get_gateway().jvm
+ catalog = jvm.org.apache.flink.table.catalog
+
+ source = table._j_table.getQueryOperation().getContextResolvedTable()
+ identifier = source.getIdentifier().asSummaryString()
+ source_table = source.getTable()
+ table_kind = source_table.getTableKind()
+ if table_kind != catalog.CatalogBaseTable.TableKind.TABLE:
+ raise ValueError(
+ f"{identifier} is a {table_kind.name().lower()}; computed columns and watermarks can "
+ f"only be added to tables"
+ )
+ if not source_table.getOptions().get("connector"):
Review Comment:
The way this is implemented, Flink needs to find a connector for the table we read, because the connector is what actually reads the data. Instead of reading the original table directly, we build a new table definition with the extra columns or watermark, and Flink has to work out which connector serves it. Most tables make that easy with a connector option, like 'connector' = 'kafka', which Flink uses to find the matching connector on the classpath. Catalog-native tables like Paimon or Fluss don't have that option, because the catalog itself is the connector. Flink asks the catalog for its connector through Catalog.getFactory(). The catalog also knows things the table's own options don't include, such as where the warehouse lives or how to reach the cluster.
The catch is that Flink only asks the catalog when the table being read is stored in that catalog. Our new table definition isn't stored anywhere, so Flink falls back to the connector option, finds nothing, and the read fails. Setting the option by hand wouldn't fix it in general either, since the connector often still needs those catalog-level settings.
Fixing this properly means changing the Java side of the planner. The new table definition would need to remember which catalog it came from, so the planner can still ask that catalog for its connector. That touches how the planner picks a connector for every table it reads. It also touches how compiled plans are saved and restored, because a restored plan would lose that catalog link unless we store it. I think those are outside the scope of this PR, so a separate ticket for it makes sense.
That said, computed_columns on its own could work for these tables today. We'd read the table as it is and add the columns as a projection on top, which doesn't need a new table definition at all. The watermark is the only part that has to be declared in the schema. The downside is that the two arguments would then behave differently on catalog-native tables: computed_columns would work and watermark would still be rejected. I think it makes sense to do both in the follow-up ticket.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40427][python] Add catalog management and catalog table I/O to DataFrame API [flink]
Posted by "fdolce (via GitHub)" <gi...@apache.org>.
fdolce commented on code in PR #29262:
URL: https://github.com/apache/flink/pull/29262#discussion_r4092525400
##########
flink-python/pyflink/dataframe/io.py:
##########
@@ -189,4 +185,155 @@ def read_generic(
source_schema = _build_source_schema(schema, computed_columns, watermark)
descriptor = _build_generic_descriptor(connector, options, source_schema)
table_environment = get_or_create_table_environment()
- return DataFrame(table_environment.from_descriptor(descriptor))
+ try:
+ table = table_environment.from_descriptor(descriptor)
+ except Exception as error:
+ _raise_as_value_error(error)
+ return DataFrame(table)
+
+
+def _extend_catalog_table(
+ table: Table,
+ computed_columns: Optional[Dict[str, str]],
+ watermark: Optional[Tuple[str, str]],
+) -> Table:
+ """
+ Read the catalog table behind ``table`` with extra computed columns and, optionally, a
+ different watermark.
+
+ Flink has no way to add columns to an existing table at read time, so this builds a nameless
+ copy of the table definition with the new schema and reads from that instead. Everything else
+ is copied over unchanged: options, partition keys, distribution, snapshot, connection and
+ comment. The connector sees the same table it always did, only with more columns. The real
+ catalog table is not touched.
+
+ This is the same thing ``TableEnvironment.from(TableDescriptor)`` does in Java. We build the
+ ``CatalogTable`` ourselves because ``TableDescriptor`` cannot take a distribution or snapshot
+ object directly.
+
+ Tables whose catalog supplies the connector, such as Paimon or Hive, cannot be extended this
+ way: the copy has no catalog to ask, so it would not know which connector to use. That is why
+ the ``connector`` option is required.
+ """
+ jvm = get_gateway().jvm
+ catalog = jvm.org.apache.flink.table.catalog
+
+ source = table._j_table.getQueryOperation().getContextResolvedTable()
+ identifier = source.getIdentifier().asSummaryString()
+ source_table = source.getTable()
+ table_kind = source_table.getTableKind()
+ if table_kind != catalog.CatalogBaseTable.TableKind.TABLE:
+ raise ValueError(
+ f"{identifier} is a {table_kind.name().lower()}; computed columns and watermarks can "
+ f"only be added to tables"
+ )
+ if not source_table.getOptions().get("connector"):
Review Comment:
Ok, rebased
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40427][python] Add catalog management and catalog table I/O to DataFrame API [flink]
Posted by "fdolce (via GitHub)" <gi...@apache.org>.
fdolce commented on code in PR #29262:
URL: https://github.com/apache/flink/pull/29262#discussion_r4091925474
##########
flink-python/pyflink/dataframe/io.py:
##########
@@ -189,4 +185,155 @@ def read_generic(
source_schema = _build_source_schema(schema, computed_columns, watermark)
descriptor = _build_generic_descriptor(connector, options, source_schema)
table_environment = get_or_create_table_environment()
- return DataFrame(table_environment.from_descriptor(descriptor))
+ try:
+ table = table_environment.from_descriptor(descriptor)
+ except Exception as error:
+ _raise_as_value_error(error)
+ return DataFrame(table)
+
+
+def _extend_catalog_table(
+ table: Table,
+ computed_columns: Optional[Dict[str, str]],
+ watermark: Optional[Tuple[str, str]],
+) -> Table:
+ """
+ Read the catalog table behind ``table`` with extra computed columns and, optionally, a
+ different watermark.
+
+ Flink has no way to add columns to an existing table at read time, so this builds a nameless
+ copy of the table definition with the new schema and reads from that instead. Everything else
+ is copied over unchanged: options, partition keys, distribution, snapshot, connection and
+ comment. The connector sees the same table it always did, only with more columns. The real
+ catalog table is not touched.
+
+ This is the same thing ``TableEnvironment.from(TableDescriptor)`` does in Java. We build the
+ ``CatalogTable`` ourselves because ``TableDescriptor`` cannot take a distribution or snapshot
+ object directly.
+
+ Tables whose catalog supplies the connector, such as Paimon or Hive, cannot be extended this
+ way: the copy has no catalog to ask, so it would not know which connector to use. That is why
+ the ``connector`` option is required.
+ """
+ jvm = get_gateway().jvm
+ catalog = jvm.org.apache.flink.table.catalog
+
+ source = table._j_table.getQueryOperation().getContextResolvedTable()
+ identifier = source.getIdentifier().asSummaryString()
+ source_table = source.getTable()
+ table_kind = source_table.getTableKind()
+ if table_kind != catalog.CatalogBaseTable.TableKind.TABLE:
+ raise ValueError(
+ f"{identifier} is a {table_kind.name().lower()}; computed columns and watermarks can "
+ f"only be added to tables"
+ )
+ if not source_table.getOptions().get("connector"):
Review Comment:
Sorry for the long message, but I want to add some context 😄
The way this is implemented, Flink needs to find a connector for the table we read, because the connector is what actually reads the data. Instead of reading the original table directly, we build a new table definition with the extra columns or watermark, and Flink has to work out which connector serves it. Most tables make that easy with a connector option, like 'connector' = 'kafka', which Flink uses to find the matching connector on the classpath. Catalog-native tables like Paimon or Fluss don't have that option, because the catalog itself is the connector. Flink asks the catalog for its connector through Catalog.getFactory(). The catalog also knows things the table's own options don't include, such as where the warehouse lives or how to reach the cluster.
The catch is that Flink only asks the catalog when the table being read is stored in that catalog. Our new table definition isn't stored anywhere, so Flink falls back to the connector option, finds nothing, and the read fails. Setting the option by hand wouldn't fix it in general either, since the connector often still needs those catalog-level settings.
Fixing this properly means changing the Java side of the planner. The new table definition would need to remember which catalog it came from, so the planner can still ask that catalog for its connector. That touches how the planner picks a connector for every table it reads. It also touches how compiled plans are saved and restored, because a restored plan would lose that catalog link unless we store it. I think those are outside the scope of this PR, so a separate ticket for it makes sense.
That said, computed_columns on its own could work for these tables today. We'd read the table as it is and add the columns as a projection on top, which doesn't need a new table definition at all. The watermark is the only part that has to be declared in the schema. The downside is that the two arguments would then behave differently on catalog-native tables: computed_columns would work and watermark would still be rejected. I think it makes sense to do both in the follow-up ticket.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40427][python] Add catalog management and catalog table I/O to DataFrame API [flink]
Posted by "dianfu (via GitHub)" <gi...@apache.org>.
dianfu commented on code in PR #29262:
URL: https://github.com/apache/flink/pull/29262#discussion_r4069972382
##########
flink-python/pyflink/dataframe/io.py:
##########
@@ -189,4 +192,45 @@ def read_generic(
source_schema = _build_source_schema(schema, computed_columns, watermark)
descriptor = _build_generic_descriptor(connector, options, source_schema)
table_environment = get_or_create_table_environment()
- return DataFrame(table_environment.from_descriptor(descriptor))
+ try:
+ table = table_environment.from_descriptor(descriptor)
+ except Exception as error:
+ _raise_as_value_error(error)
+ return DataFrame(table)
+
+
+@PublicEvolving()
+def read_catalog_table(path: str) -> DataFrame:
Review Comment:
Could we make the `read_catalog_table` API also accepts `computed_columns` and `watermark`?
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40427][python] Add catalog management and catalog table I/O to DataFrame API [flink]
Posted by "flinkbot (via GitHub)" <gi...@apache.org>.
flinkbot commented on PR #29262:
URL: https://github.com/apache/flink/pull/29262#issuecomment-5758416382
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "8d32b0a92091d2aeaaf87484d4da3bfa1d1e0533",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "8d32b0a92091d2aeaaf87484d4da3bfa1d1e0533",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 8d32b0a92091d2aeaaf87484d4da3bfa1d1e0533 UNKNOWN
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run azure` re-run the last Azure build
</details>
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40427][python] Add catalog management and catalog table I/O to DataFrame API [flink]
Posted by "dianfu (via GitHub)" <gi...@apache.org>.
dianfu commented on PR #29262:
URL: https://github.com/apache/flink/pull/29262#issuecomment-5833687186
@fdolce There are test failures. Could you take a look?
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40427][python] Add catalog management and catalog table I/O to DataFrame API [flink]
Posted by "fdolce (via GitHub)" <gi...@apache.org>.
fdolce commented on code in PR #29262:
URL: https://github.com/apache/flink/pull/29262#discussion_r4070904044
##########
flink-python/pyflink/dataframe/catalog.py:
##########
@@ -0,0 +1,257 @@
+################################################################################
+# 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.
+################################################################################
+
+from typing import Dict, List, Optional
+
+from pyflink.common import Configuration
+from pyflink.dataframe.context import get_or_create_table_environment
+from pyflink.dataframe.errors import _raise_as_value_error
+from pyflink.table.catalog import Catalog, CatalogDescriptor
+from pyflink.util.api_stability_decorators import PublicEvolving
+
+__all__ = [
+ "create_catalog",
+ "get_catalog",
+ "use_catalog",
+ "get_current_catalog",
+ "list_catalogs",
+ "use_database",
+ "get_current_database",
+ "list_databases",
+]
+
+
+def _validate_name(name: str, what: str) -> None:
+ if not isinstance(name, str):
+ raise TypeError(f"{what} must be a string")
+ if not name:
+ raise ValueError(f"{what} must not be empty")
+
+
+def _validate_catalog_options(options: Dict[str, str]) -> None:
+ if not isinstance(options, dict):
+ raise TypeError("options must be a dict of string keys and values")
+ for key, value in options.items():
+ if not isinstance(key, str):
+ raise TypeError("option keys must be strings")
+ if not key:
+ raise ValueError("option keys must not be empty")
+ if not isinstance(value, str):
+ raise TypeError(f"option {key!r} must have a string value")
+
+
+@PublicEvolving()
+def create_catalog(name: str, options: Dict[str, str]) -> None:
+ """
+ Create a catalog in the environment used by DataFrame operations.
+
+ The ``type`` option selects the catalog factory, which must be available through Flink's
+ factory discovery mechanism. The remaining options are passed to that factory. This mirrors the
+ ``CREATE CATALOG`` SQL statement.
+
+ :param name: Name under which the catalog is created.
+ :param options: Catalog options, including the ``type`` option.
+ :raises TypeError: If ``name`` is not a string or ``options`` is not a dict of strings.
+ :raises ValueError: If ``name`` or an option key is empty, if a catalog named ``name`` already
+ exists, or if Flink cannot create a catalog from ``options``.
+ :raises ~pyflink.util.exceptions.CatalogException: If the catalog reports an error while
+ being created.
+
+ Example::
+
+ >>> import pyflink.dataframe as pf
+ >>> pf.create_catalog("my_catalog", {"type": "generic_in_memory"})
+ >>> pf.list_catalogs()
+ ['default_catalog', 'my_catalog']
+
+ .. versionadded:: 2.4.0
+ """
+ _validate_name(name, "name")
+ _validate_catalog_options(options)
+ table_environment = get_or_create_table_environment()
+ if name in table_environment.list_catalogs():
+ raise ValueError(f"a catalog named {name!r} already exists")
+
+ configuration = Configuration()
+ for key, value in options.items():
+ configuration.set_string(key, value)
+ descriptor = CatalogDescriptor.of(name, configuration)
+ try:
+ table_environment.create_catalog(name, descriptor)
+ except Exception as error:
+ _raise_as_value_error(error)
+
+
+@PublicEvolving()
+def get_catalog(name: str) -> Optional[Catalog]:
+ """
+ Return a registered catalog by name.
+
+ :param name: Name of the catalog.
+ :return: The :class:`~pyflink.table.catalog.Catalog`, or ``None`` if no catalog is registered
+ under ``name``.
+ :raises TypeError: If ``name`` is not a string.
+ :raises ValueError: If ``name`` is empty.
+
+ Example::
+
+ >>> import pyflink.dataframe as pf
+ >>> pf.create_catalog("my_catalog", {"type": "generic_in_memory"})
+ >>> pf.get_catalog("my_catalog").list_databases()
+ ['default']
+ >>> pf.get_catalog("missing") is None
+ True
+
+ .. versionadded:: 2.4.0
+ """
+ _validate_name(name, "name")
+ return get_or_create_table_environment().get_catalog(name)
+
+
+@PublicEvolving()
+def use_catalog(name: str) -> None:
+ """
+ Set the current catalog.
+
+ Table paths without a catalog part, such as ``my_table`` or ``my_database.my_table``, are
+ resolved against the current catalog. Switching the catalog also resets the current database to
+ the default database of the new catalog.
+
+ :param name: Name of a registered catalog.
+ :raises TypeError: If ``name`` is not a string.
+ :raises ValueError: If ``name`` is empty or no catalog named ``name`` exists.
+
+ Example::
+
+ >>> import pyflink.dataframe as pf
+ >>> pf.create_catalog("my_catalog", {"type": "generic_in_memory"})
+ >>> pf.use_catalog("my_catalog")
+ >>> pf.get_current_catalog()
+ 'my_catalog'
+
+ .. versionadded:: 2.4.0
+ """
+ _validate_name(name, "name")
+ table_environment = get_or_create_table_environment()
+ if name not in table_environment.list_catalogs():
+ raise ValueError(f"no catalog named {name!r} exists")
+ table_environment.use_catalog(name)
+
+
+@PublicEvolving()
+def get_current_catalog() -> str:
+ """
+ Return the name of the current catalog.
+
+ :return: The current catalog name.
+
+ Example::
+
+ >>> import pyflink.dataframe as pf
+ >>> pf.get_current_catalog()
+ 'default_catalog'
+
+ .. versionadded:: 2.4.0
+ """
+ return get_or_create_table_environment().get_current_catalog()
+
+
+@PublicEvolving()
+def list_catalogs() -> List[str]:
+ """
+ Return the names of all registered catalogs.
+
+ :return: Catalog names.
+
+ Example::
+
+ >>> import pyflink.dataframe as pf
+ >>> pf.list_catalogs()
+ ['default_catalog']
+
+ .. versionadded:: 2.4.0
+ """
+ return get_or_create_table_environment().list_catalogs()
+
+
+@PublicEvolving()
+def use_database(name: str) -> None:
+ """
+ Set the current database within the current catalog.
+
+ Table paths without a database part, such as ``my_table``, are resolved against the current
+ database.
+
+ :param name: Name of a database in the current catalog.
+ :raises TypeError: If ``name`` is not a string.
+ :raises ValueError: If ``name`` is empty or the current catalog has no database named
+ ``name``.
+
+ Example::
+
+ >>> import pyflink.dataframe as pf
+ >>> pf.use_database("default_database")
+ >>> pf.get_current_database()
+ 'default_database'
+
+ .. versionadded:: 2.4.0
+ """
+ _validate_name(name, "name")
+ table_environment = get_or_create_table_environment()
+ if name not in table_environment.list_databases():
Review Comment:
Sure, makes sense. I'll also check what error is raised in that case and try to wrap it in a useful exception if that's not already the case
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40427][python] Add catalog management and catalog table I/O to DataFrame API [flink]
Posted by "fdolce (via GitHub)" <gi...@apache.org>.
fdolce commented on PR #29262:
URL: https://github.com/apache/flink/pull/29262#issuecomment-5791815571
Pushed 3 commits.
- The first one to avoid doing the calls to list_databases and list_catalogs
- Second one adds the computed_columns and watermak kwargs. I did try a couple of ways to implement this, this is the one I liked the most, but let me know if you have other ideas
- Third one is just rewriting some comments and docstrings to make them more readable
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40427][python] Add catalog management and catalog table I/O to DataFrame API [flink]
Posted by "fdolce (via GitHub)" <gi...@apache.org>.
fdolce commented on code in PR #29262:
URL: https://github.com/apache/flink/pull/29262#discussion_r4070881396
##########
flink-python/pyflink/dataframe/io.py:
##########
@@ -189,4 +192,45 @@ def read_generic(
source_schema = _build_source_schema(schema, computed_columns, watermark)
descriptor = _build_generic_descriptor(connector, options, source_schema)
table_environment = get_or_create_table_environment()
- return DataFrame(table_environment.from_descriptor(descriptor))
+ try:
+ table = table_environment.from_descriptor(descriptor)
+ except Exception as error:
+ _raise_as_value_error(error)
+ return DataFrame(table)
+
+
+@PublicEvolving()
+def read_catalog_table(path: str) -> DataFrame:
Review Comment:
Oh, right, I forgot to mention this in the PR description. The change to add those is non trivial so I wanted to ask if this should be a separate PR, but I'll add it in a separate commit here so we can still review that part alone.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40427][python] Add catalog management and catalog table I/O to DataFrame API [flink]
Posted by "dianfu (via GitHub)" <gi...@apache.org>.
dianfu closed pull request #29262: [FLINK-40427][python] Add catalog management and catalog table I/O to DataFrame API
URL: https://github.com/apache/flink/pull/29262
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40427][python] Add catalog management and catalog table I/O to DataFrame API [flink]
Posted by "fdolce (via GitHub)" <gi...@apache.org>.
fdolce commented on PR #29262:
URL: https://github.com/apache/flink/pull/29262#issuecomment-5872285008
Fix pushed and rebased, do we have to manually retrigger CI?
@flinkbot run azure
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org