Status


Please keep the discussion on the mailing list rather than commenting on the wiki (wiki discussions get unwieldy fast).


Motivation

The TableEnvironment#connect API has been introduced in Flink 1.5.0 in order to instantiate and configure table sources and sinks. Since then, the SQL DDL has been actively developed and improved, and as a result is more powerful and many of these feature are inaccessible from #connect. Furthermore, this API has shown to contain several shortcomings:

  • Connectors have to implement corresponding descriptors (e.g. "new Kafka()"), which increases maintenance effort and duplicates information.
  • The underlying implementation for the SQL DDL and #connector are different, requiring the maintenance of different code paths.
  • There are many known issues about Descriptor API: FLINK-17548, FLINK-17186, FLINK-15801, FLINK-15943.

As a result, #connect has been deprecated sind Flink 1.11. In this FLIP, we want to propose a new API to programmatically define sources and sinks on the Table API without having to switch to SQL DDL.

Public Interfaces

InterfaceChangeComment
TableEnvironment
#connectRemoveDeprecated since Flink 1.11
#createTable(path, TableDescriptor)New
#createTemporaryTable(path, TableDescriptor)New
#from(TableDescriptor)New
Table
#executeInsert(TableDescriptor)New
StatementSet
#addInsert(TableDescriptor, Table)New
Other
ConnectTableDescriptorRemove
BatchTableDescriptorRemove
StreamTableDescriptorRemove
ConnectorDescriptorRemove
TableDescriptorRefactor
  • Removed in its current form
  • Name is re-used for the new API
RowtimeRemove


TableEnvironment#createTable & TableEnvironment#createTemporaryTable

In order for users to register sources and sinks via Table API, we introduce two new methods:

TableEnvironment
/**
  * Creates a new table from the given descriptor.
  *
  * The table is created in the catalog defined by the given path.
  */
void createTable(String path, TableDescriptor descriptor);

/**
  * Creates a new temporary table from the given descriptor.
  *
  * Temporary objects can shadow permanent ones. If a permanent object in a given path exists,
  * it will be inaccessible in the current session. To make the permanent object available again
  * one can drop the corresponding temporary object.
  */
void createTemporaryTable(String path, TableDescriptor descriptor);


The TableDescriptor interface is a (generic) representation of the structure used in the SQL DDL, or CatalogTable, respectively. It implements a fluent API to allow chaining and make it easy to use. Options are either specified by referring to an actual ConfigOption instance (preferred), or by string. The latter is necessary, in particular, for options which are not represented through ConfigOption instances, e.g. if they contain placeholders such as "field.#.min". The interface also offers quality-of-life methods for specifying formats such that prefixing format options is handled by the descriptor itself, which allows using ConfigOption instances for format options.

TableDescriptor
TableDescriptor {
  // Create a builder
  static TableDescriptorBuilder forConnector(String connector);
  
  Optional<Schema> getSchema();
  Map<String, String> getOptions();
  Optional<String> getComment();
  List<String> getPartitionKeys();
  Optional<TableLikeDescriptor> getLikeDescriptor();
}

TableDescriptorBuilder<SELF> {
  SELF schema(Schema schema);
  
  SELF comment(String comment);

  SELF option<T>(ConfigOption<T> configOption, T value);
  SELF option(String key, String value);

  SELF format(String format);
  SELF format(ConfigOption<?> formatOption, String format);  
  SELF format(FormatDescriptor formatDescriptor);
  SELF format(ConfigOption<?> formatOption, FormatDescriptor formatDescriptor);
  
  SELF partitionedBy(String... partitionKeys);
  
  SELF like(String tableName, LikeOption... likeOptions);
  
  TableDescriptor build();
}

TableLikeDescriptor {
  String getTableName();
  List<TableLikeOption> getLikeOptions();
}

FormatDescriptor {
  static FormatDescriptorBuilder forFormat(String format);
  
  String getFormat();
  Map<String, String> getOptions();
}

FormatDescriptorBuilder<SELF> {
  SELF option<T>(ConfigOption<T> configOption, T value);
  SELF option(String key, String value);
  FormatDescriptor build();
}

interface LikeOption {
	enum INCLUDING implements LikeOption {
		ALL,
		CONSTRAINTS,
		GENERATED,
		OPTIONS,
		PARTITIONS,
		WATERMARKS
	}

	enum EXCLUDING implements LikeOption {
		ALL,
		CONSTRAINTS,
		GENERATED,
		OPTIONS,
		PARTITIONS,
		WATERMARKS
	}

	enum OVERWRITING implements LikeOption {
		GENERATED,
		OPTIONS,
		WATERMARKS
	}
}


The following example demonstrates a simple example of how these APIs can be used:

tEnv.createTable(
  "cat.db.MyTable",

  TableDescriptor.forConnector("kafka")
    .comment("This is a comment")
    .schema(Schema.newBuilder()
      .column("f0", DataTypes.BIGINT())
      .columnByExpression("f1", "2 * f0")
      .columnByMetadata("f3", DataTypes.STRING())
      .column("t", DataTypes.TIMESTAMP(3))
      .watermark("t", "t - INTERVAL '1' MINUTE")
      .primaryKey("f0")
      .build())  
    .partitionedBy("f0")
    .option(KafkaOptions.TOPIC, topic)
    .option("properties.bootstrap.servers", "…")
    .format("json")
    .build()
);

tEnv.createTemporaryTable(
  "MyTemporaryTable",

  TableDescriptor.forConnector("kafka")
    // …
    .like("cat.db.MyTable")
);


TableEnvironment#from

We propose introducing TableEnvironment#from in order to create a Table from a given descriptor. This is in line with existing methods, e.g. from(String).

TableEnvironment
/**
  * Returns a {@link Table} backed by the given descriptor.
  */
Table from(TableDescriptor descriptor); 

Table#executeInsert

We propose introducing Table#executeInsert in order to write directly to a sink defined by a descriptor. This is in line with existing methods, e.g. executeInsert(String).

Table
/**
  * Declares that the pipeline defined by this table should be written to a table defined by the given descriptor.
  *
  * If no schema is defined in the descriptor, it will be inferred automatically.
  */
TableResult executeInsert(TableDescriptor descriptor);

StatementSet#addInsert

Similarly to Table#executeInsert, we propose extending StatementSet#addInsert to take a descriptor.

/**
  * Adds the given table as a sink defined by the descriptor.
  */
StatementSet addInsert(TableDescriptor descriptor, Table table);

Package Structure

The new descriptor API will reside in flink-table-api-java in the org.apache.flink.table.descriptors package.

In order to make discovery of ConfigOption instances easier, we propose to move *Options classes from all built-in connectors (e.g. KafkaOptions, …) into a common package. Then users can easily discover those classes for any connectors on their current classpath. As this involves declaring these classes to be public (evolving) API, minor refactorings will be necessary to ensure they do not contain any internals.

Compatibility, Deprecation, and Migration Plan

The proposed changes drop an existing API and replace it with a new, incompatible API. However, the old API has been deprecated since Flink 1.11 and is lacking support for many features, thus we are not expecting this to affect many users, as the current recommendation has been to switch to SQL DDL. For affected users, the migration requires relatively small changes and all existing features can be covered.

Rejected Alternatives

Keep and follow the original TableEnvironment#connect API

For example, a minor refactored TableEnvironment#connect:

tableEnv.connect(
        new Kafka() // can be replaced by new Connector("kafka-0.11")
            .version("0.11")
            .topic("myTopic")
            .property("bootstrap.servers", "localhost:9092")
            .property("group.id", "test-group")
            .scanStartupModeEarliest()
            .sinkPartitionerRoundRobin()
            .format(new Json().ignoreParseErrors(false))
    .schema(
        new Schema()
            .column("user_id", DataTypes.BIGINT())
            .column("user_name", DataTypes.STRING())
            .column("score", DataTypes.DECIMAL(10, 2))
            .column("log_ts", DataTypes.TIMESTAMP(3))
            .column("part_field_0", DataTypes.STRING())
            .column("part_field_1", DataTypes.INT())
            .column("proc", proctime())
            .column("my_ts", toTimestamp($("log_ts"))
            .watermarkFor("my_ts", $("my_ts").minus(lit(3).seconds())))
            .primaryKey("user_id")
    .partitionedBy("part_field_0", "part_field_1")
    .createTemporaryTable("MyTable");


However, we prefer "TableEnvironment#createTemporaryTable(path, descriptor)" instead of "TableEnvironment#connect", because

  1. It may confuse users that the "connect()" method invoking doesn't connect to external system, it's just a start point to connect to external system. It is connected after the invoking of "createTemporaryTable".
  2. The "connect()" method looks weired in the methods of TableEnvironment, because all the other methods are SQL compliant. Thus, we think "tEnv#createTemporaryTable(path, descriptor)" is a better entry point than "connect()".
  3. The "TableEnvironment#createTemporaryTable(path, descriptor)" decouples Descriptor and table registration. We can easily support more features, like "TableEnvironment#from(descriptor)" and "Table#executeInsert(descriptor)" with the same descriptor interfaces/classes.