Skip to content
Projects
Groups
Snippets
Help
This project
Loading...
Sign in / Register
Toggle navigation
D
dinky
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
wangpeng
dinky
Commits
9c315b5c
Commit
9c315b5c
authored
Nov 11, 2022
by
lcgg
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
[Feature][connector] query push down of jdbc
parent
2be2d6d4
Hide whitespace changes
Inline
Side-by-side
Showing
14 changed files
with
2938 additions
and
1 deletion
+2938
-1
JdbcDialect.java
.../org/apache/flink/connector/jdbc/dialect/JdbcDialect.java
+195
-0
JdbcLookupOptions.java
...nk/connector/jdbc/internal/options/JdbcLookupOptions.java
+109
-0
JdbcDynamicTableFactory.java
...e/flink/connector/jdbc/table/JdbcDynamicTableFactory.java
+380
-0
JdbcDynamicTableSource.java
...he/flink/connector/jdbc/table/JdbcDynamicTableSource.java
+190
-0
JdbcLookupFunction.java
...apache/flink/connector/jdbc/table/JdbcLookupFunction.java
+318
-0
JdbcRowDataLookupFunction.java
...flink/connector/jdbc/table/JdbcRowDataLookupFunction.java
+243
-0
JdbcDialect.java
.../org/apache/flink/connector/jdbc/dialect/JdbcDialect.java
+187
-0
JdbcLookupOptions.java
...nk/connector/jdbc/internal/options/JdbcLookupOptions.java
+109
-0
JdbcConnectorOptions.java
...ache/flink/connector/jdbc/table/JdbcConnectorOptions.java
+171
-0
JdbcDynamicTableFactory.java
...e/flink/connector/jdbc/table/JdbcDynamicTableFactory.java
+286
-0
JdbcDynamicTableSource.java
...he/flink/connector/jdbc/table/JdbcDynamicTableSource.java
+190
-0
JdbcLookupFunction.java
...apache/flink/connector/jdbc/table/JdbcLookupFunction.java
+318
-0
JdbcRowDataLookupFunction.java
...flink/connector/jdbc/table/JdbcRowDataLookupFunction.java
+241
-0
checkstyle.xml
style/checkstyle.xml
+1
-1
No files found.
dlink-connectors/dlink-connector-jdbc-1.13/src/main/java/org/apache/flink/connector/jdbc/dialect/JdbcDialect.java
0 → 100644
View file @
9c315b5c
/*
*
* 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.
*
*/
package
org
.
apache
.
flink
.
connector
.
jdbc
.
dialect
;
import
static
java
.
lang
.
String
.
format
;
import
org.apache.flink.annotation.Internal
;
import
org.apache.flink.connector.jdbc.internal.converter.JdbcRowConverter
;
import
org.apache.flink.table.api.TableSchema
;
import
org.apache.flink.table.api.ValidationException
;
import
org.apache.flink.table.types.logical.RowType
;
import
java.io.Serializable
;
import
java.util.Arrays
;
import
java.util.Optional
;
import
java.util.stream.Collectors
;
/**
* Handle the SQL dialect of jdbc driver.
*/
@Internal
public
interface
JdbcDialect
extends
Serializable
{
/**
* Get the name of jdbc dialect.
*
* @return the dialect name.
*/
String
dialectName
();
/**
* Check if this dialect instance can handle a certain jdbc url.
*
* @param url the jdbc url.
* @return True if the dialect can be applied on the given jdbc url.
*/
boolean
canHandle
(
String
url
);
/**
* Get converter that convert jdbc object and Flink internal object each other.
*
* @param rowType the given row type
* @return a row converter for the database
*/
JdbcRowConverter
getRowConverter
(
RowType
rowType
);
/**
* Get limit clause to limit the number of emitted row from the jdbc source.
*
* @param limit number of row to emit. The value of the parameter should be non-negative.
* @return the limit clause.
*/
String
getLimitClause
(
long
limit
);
/**
* Check if this dialect instance support a specific data type in table schema.
*
* @param schema the table schema.
* @throws ValidationException in case of the table schema contains unsupported type.
*/
default
void
validate
(
TableSchema
schema
)
throws
ValidationException
{
}
/**
* @return the default driver class name, if user not configure the driver class name, then will
* use this one.
*/
default
Optional
<
String
>
defaultDriverName
()
{
return
Optional
.
empty
();
}
/**
* Quotes the identifier. This is used to put quotes around the identifier in case the column
* name is a reserved keyword, or in case it contains characters that require quotes (e.g.
* space). Default using double quotes {@code "} to quote.
*/
default
String
quoteIdentifier
(
String
identifier
)
{
return
"\""
+
identifier
+
"\""
;
}
/**
* Get dialect upsert statement, the database has its own upsert syntax, such as Mysql using
* DUPLICATE KEY UPDATE, and PostgresSQL using ON CONFLICT... DO UPDATE SET..
*
* @return None if dialect does not support upsert statement, the writer will degrade to the use
* of select + update/insert, this performance is poor.
*/
default
Optional
<
String
>
getUpsertStatement
(
String
tableName
,
String
[]
fieldNames
,
String
[]
uniqueKeyFields
)
{
return
Optional
.
empty
();
}
/**
* Get row exists statement by condition fields. Default use SELECT.
*/
default
String
getRowExistsStatement
(
String
tableName
,
String
[]
conditionFields
)
{
String
fieldExpressions
=
Arrays
.
stream
(
conditionFields
)
.
map
(
f
->
format
(
"%s = :%s"
,
quoteIdentifier
(
f
),
f
))
.
collect
(
Collectors
.
joining
(
" AND "
));
return
"SELECT 1 FROM "
+
quoteIdentifier
(
tableName
)
+
" WHERE "
+
fieldExpressions
;
}
/**
* Get insert into statement.
*/
default
String
getInsertIntoStatement
(
String
tableName
,
String
[]
fieldNames
)
{
String
columns
=
Arrays
.
stream
(
fieldNames
)
.
map
(
this
::
quoteIdentifier
)
.
collect
(
Collectors
.
joining
(
", "
));
String
placeholders
=
Arrays
.
stream
(
fieldNames
).
map
(
f
->
":"
+
f
).
collect
(
Collectors
.
joining
(
", "
));
return
"INSERT INTO "
+
quoteIdentifier
(
tableName
)
+
"("
+
columns
+
")"
+
" VALUES ("
+
placeholders
+
")"
;
}
/**
* Get update one row statement by condition fields, default not use limit 1, because limit 1 is
* a sql dialect.
*/
default
String
getUpdateStatement
(
String
tableName
,
String
[]
fieldNames
,
String
[]
conditionFields
)
{
String
setClause
=
Arrays
.
stream
(
fieldNames
)
.
map
(
f
->
format
(
"%s = :%s"
,
quoteIdentifier
(
f
),
f
))
.
collect
(
Collectors
.
joining
(
", "
));
String
conditionClause
=
Arrays
.
stream
(
conditionFields
)
.
map
(
f
->
format
(
"%s = :%s"
,
quoteIdentifier
(
f
),
f
))
.
collect
(
Collectors
.
joining
(
" AND "
));
return
"UPDATE "
+
quoteIdentifier
(
tableName
)
+
" SET "
+
setClause
+
" WHERE "
+
conditionClause
;
}
/**
* Get delete one row statement by condition fields, default not use limit 1, because limit 1 is
* a sql dialect.
*/
default
String
getDeleteStatement
(
String
tableName
,
String
[]
conditionFields
)
{
String
conditionClause
=
Arrays
.
stream
(
conditionFields
)
.
map
(
f
->
format
(
"%s = :%s"
,
quoteIdentifier
(
f
),
f
))
.
collect
(
Collectors
.
joining
(
" AND "
));
return
"DELETE FROM "
+
quoteIdentifier
(
tableName
)
+
" WHERE "
+
conditionClause
;
}
/**
* Get select fields statement by condition fields. Default use SELECT.
*/
default
String
getSelectFromStatement
(
String
tableName
,
String
[]
selectFields
,
String
[]
conditionFields
)
{
String
selectExpressions
=
Arrays
.
stream
(
selectFields
)
.
map
(
this
::
quoteIdentifier
)
.
collect
(
Collectors
.
joining
(
", "
));
String
fieldExpressions
=
Arrays
.
stream
(
conditionFields
)
.
map
(
f
->
f
.
contains
(
" "
)
||
f
.
contains
(
">"
)
||
f
.
contains
(
"<"
)
||
f
.
contains
(
"="
)
?
f
:
format
(
"%s = :%s"
,
quoteIdentifier
(
f
),
f
))
.
collect
(
Collectors
.
joining
(
" AND "
));
return
"SELECT "
+
selectExpressions
+
" FROM "
+
quoteIdentifier
(
tableName
)
+
(
conditionFields
.
length
>
0
?
" WHERE "
+
fieldExpressions
:
""
);
}
}
dlink-connectors/dlink-connector-jdbc-1.13/src/main/java/org/apache/flink/connector/jdbc/internal/options/JdbcLookupOptions.java
0 → 100644
View file @
9c315b5c
/*
*
* 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.
*
*/
package
org
.
apache
.
flink
.
connector
.
jdbc
.
internal
.
options
;
import
org.apache.flink.connector.jdbc.JdbcExecutionOptions
;
import
java.io.Serializable
;
import
java.util.Objects
;
/** Options for the JDBC lookup. */
public
class
JdbcLookupOptions
implements
Serializable
{
private
final
long
cacheMaxSize
;
private
final
long
cacheExpireMs
;
private
final
int
maxRetryTimes
;
private
final
String
dataFilter
;
public
JdbcLookupOptions
(
long
cacheMaxSize
,
long
cacheExpireMs
,
int
maxRetryTimes
,
String
dataFilter
)
{
this
.
cacheMaxSize
=
cacheMaxSize
;
this
.
cacheExpireMs
=
cacheExpireMs
;
this
.
maxRetryTimes
=
maxRetryTimes
;
this
.
dataFilter
=
dataFilter
;
}
public
long
getCacheMaxSize
()
{
return
cacheMaxSize
;
}
public
long
getCacheExpireMs
()
{
return
cacheExpireMs
;
}
public
int
getMaxRetryTimes
()
{
return
maxRetryTimes
;
}
public
String
[]
getPreFilterCondition
()
{
if
(
dataFilter
==
null
||
dataFilter
.
isEmpty
())
{
return
new
String
[
0
];
}
String
[]
res
=
new
String
[
1
];
res
[
0
]
=
dataFilter
.
replace
(
"\""
,
"'"
);
return
res
;
}
public
static
Builder
builder
()
{
return
new
Builder
();
}
@Override
public
boolean
equals
(
Object
o
)
{
if
(
o
instanceof
JdbcLookupOptions
)
{
JdbcLookupOptions
options
=
(
JdbcLookupOptions
)
o
;
return
Objects
.
equals
(
cacheMaxSize
,
options
.
cacheMaxSize
)
&&
Objects
.
equals
(
cacheExpireMs
,
options
.
cacheExpireMs
)
&&
Objects
.
equals
(
maxRetryTimes
,
options
.
maxRetryTimes
);
}
else
{
return
false
;
}
}
/** Builder of {@link JdbcLookupOptions}. */
public
static
class
Builder
{
private
long
cacheMaxSize
=
-
1L
;
private
long
cacheExpireMs
=
-
1L
;
private
int
maxRetryTimes
=
JdbcExecutionOptions
.
DEFAULT_MAX_RETRY_TIMES
;
private
String
dataFilter
=
""
;
/** optional, lookup cache max size, over this value, the old data will be eliminated. */
public
Builder
setCacheMaxSize
(
long
cacheMaxSize
)
{
this
.
cacheMaxSize
=
cacheMaxSize
;
return
this
;
}
/** optional, lookup cache expire mills, over this time, the old data will expire. */
public
Builder
setCacheExpireMs
(
long
cacheExpireMs
)
{
this
.
cacheExpireMs
=
cacheExpireMs
;
return
this
;
}
/** optional, max retry times for jdbc connector. */
public
Builder
setMaxRetryTimes
(
int
maxRetryTimes
)
{
this
.
maxRetryTimes
=
maxRetryTimes
;
return
this
;
}
public
JdbcLookupOptions
build
()
{
return
new
JdbcLookupOptions
(
cacheMaxSize
,
cacheExpireMs
,
maxRetryTimes
,
dataFilter
);
}
}
}
dlink-connectors/dlink-connector-jdbc-1.13/src/main/java/org/apache/flink/connector/jdbc/table/JdbcDynamicTableFactory.java
0 → 100644
View file @
9c315b5c
/*
*
* 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.
*
*/
package
org
.
apache
.
flink
.
connector
.
jdbc
.
table
;
import
static
org
.
apache
.
flink
.
util
.
Preconditions
.
checkState
;
import
org.apache.flink.annotation.Internal
;
import
org.apache.flink.configuration.ConfigOption
;
import
org.apache.flink.configuration.ConfigOptions
;
import
org.apache.flink.configuration.ReadableConfig
;
import
org.apache.flink.connector.jdbc.JdbcExecutionOptions
;
import
org.apache.flink.connector.jdbc.dialect.JdbcDialect
;
import
org.apache.flink.connector.jdbc.dialect.JdbcDialects
;
import
org.apache.flink.connector.jdbc.internal.options.JdbcDmlOptions
;
import
org.apache.flink.connector.jdbc.internal.options.JdbcLookupOptions
;
import
org.apache.flink.connector.jdbc.internal.options.JdbcOptions
;
import
org.apache.flink.connector.jdbc.internal.options.JdbcReadOptions
;
import
org.apache.flink.table.api.TableSchema
;
import
org.apache.flink.table.connector.sink.DynamicTableSink
;
import
org.apache.flink.table.connector.source.DynamicTableSource
;
import
org.apache.flink.table.factories.DynamicTableSinkFactory
;
import
org.apache.flink.table.factories.DynamicTableSourceFactory
;
import
org.apache.flink.table.factories.FactoryUtil
;
import
org.apache.flink.table.utils.TableSchemaUtils
;
import
org.apache.flink.util.Preconditions
;
import
java.time.Duration
;
import
java.util.Arrays
;
import
java.util.HashSet
;
import
java.util.Optional
;
import
java.util.Set
;
/**
* Factory for creating configured instances of {@link JdbcDynamicTableSource} and {@link
* JdbcDynamicTableSink}.
*/
@Internal
public
class
JdbcDynamicTableFactory
implements
DynamicTableSourceFactory
,
DynamicTableSinkFactory
{
public
static
final
String
IDENTIFIER
=
"jdbc"
;
public
static
final
ConfigOption
<
String
>
URL
=
ConfigOptions
.
key
(
"url"
)
.
stringType
()
.
noDefaultValue
()
.
withDescription
(
"The JDBC database URL."
);
public
static
final
ConfigOption
<
String
>
TABLE_NAME
=
ConfigOptions
.
key
(
"table-name"
)
.
stringType
()
.
noDefaultValue
()
.
withDescription
(
"The JDBC table name."
);
public
static
final
ConfigOption
<
String
>
USERNAME
=
ConfigOptions
.
key
(
"username"
)
.
stringType
()
.
noDefaultValue
()
.
withDescription
(
"The JDBC user name."
);
public
static
final
ConfigOption
<
String
>
PASSWORD
=
ConfigOptions
.
key
(
"password"
)
.
stringType
()
.
noDefaultValue
()
.
withDescription
(
"The JDBC password."
);
private
static
final
ConfigOption
<
String
>
DRIVER
=
ConfigOptions
.
key
(
"driver"
)
.
stringType
()
.
noDefaultValue
()
.
withDescription
(
"The class name of the JDBC driver to use to connect to this URL. "
+
"If not set, it will automatically be derived from the URL."
);
public
static
final
ConfigOption
<
Duration
>
MAX_RETRY_TIMEOUT
=
ConfigOptions
.
key
(
"connection.max-retry-timeout"
)
.
durationType
()
.
defaultValue
(
Duration
.
ofSeconds
(
60
))
.
withDescription
(
"Maximum timeout between retries."
);
// read config options
private
static
final
ConfigOption
<
String
>
SCAN_PARTITION_COLUMN
=
ConfigOptions
.
key
(
"scan.partition.column"
)
.
stringType
()
.
noDefaultValue
()
.
withDescription
(
"The column name used for partitioning the input."
);
private
static
final
ConfigOption
<
Integer
>
SCAN_PARTITION_NUM
=
ConfigOptions
.
key
(
"scan.partition.num"
)
.
intType
()
.
noDefaultValue
()
.
withDescription
(
"The number of partitions."
);
private
static
final
ConfigOption
<
Long
>
SCAN_PARTITION_LOWER_BOUND
=
ConfigOptions
.
key
(
"scan.partition.lower-bound"
)
.
longType
()
.
noDefaultValue
()
.
withDescription
(
"The smallest value of the first partition."
);
private
static
final
ConfigOption
<
Long
>
SCAN_PARTITION_UPPER_BOUND
=
ConfigOptions
.
key
(
"scan.partition.upper-bound"
)
.
longType
()
.
noDefaultValue
()
.
withDescription
(
"The largest value of the last partition."
);
private
static
final
ConfigOption
<
Integer
>
SCAN_FETCH_SIZE
=
ConfigOptions
.
key
(
"scan.fetch-size"
)
.
intType
()
.
defaultValue
(
0
)
.
withDescription
(
"Gives the reader a hint as to the number of rows that should be fetched "
+
"from the database per round-trip when reading. "
+
"If the value is zero, this hint is ignored."
);
private
static
final
ConfigOption
<
Boolean
>
SCAN_AUTO_COMMIT
=
ConfigOptions
.
key
(
"scan.auto-commit"
)
.
booleanType
()
.
defaultValue
(
true
)
.
withDescription
(
"Sets whether the driver is in auto-commit mode."
);
// look up config options
private
static
final
ConfigOption
<
Long
>
LOOKUP_CACHE_MAX_ROWS
=
ConfigOptions
.
key
(
"lookup.cache.max-rows"
)
.
longType
()
.
defaultValue
(-
1L
)
.
withDescription
(
"The max number of rows of lookup cache, over this value, the oldest rows will "
+
"be eliminated. \"cache.max-rows\" and \"cache.ttl\" options must all be specified if any of them is "
+
"specified."
);
private
static
final
ConfigOption
<
Duration
>
LOOKUP_CACHE_TTL
=
ConfigOptions
.
key
(
"lookup.cache.ttl"
)
.
durationType
()
.
defaultValue
(
Duration
.
ofSeconds
(
10
))
.
withDescription
(
"The cache time to live."
);
private
static
final
ConfigOption
<
Integer
>
LOOKUP_MAX_RETRIES
=
ConfigOptions
.
key
(
"lookup.max-retries"
)
.
intType
()
.
defaultValue
(
3
)
.
withDescription
(
"The max retry times if lookup database failed."
);
// write config options
private
static
final
ConfigOption
<
Integer
>
SINK_BUFFER_FLUSH_MAX_ROWS
=
ConfigOptions
.
key
(
"sink.buffer-flush.max-rows"
)
.
intType
()
.
defaultValue
(
100
)
.
withDescription
(
"The flush max size (includes all append, upsert and delete records), over this number"
+
" of records, will flush data."
);
private
static
final
ConfigOption
<
Duration
>
SINK_BUFFER_FLUSH_INTERVAL
=
ConfigOptions
.
key
(
"sink.buffer-flush.interval"
)
.
durationType
()
.
defaultValue
(
Duration
.
ofSeconds
(
1
))
.
withDescription
(
"The flush interval mills, over this time, asynchronous threads will flush data."
);
private
static
final
ConfigOption
<
Integer
>
SINK_MAX_RETRIES
=
ConfigOptions
.
key
(
"sink.max-retries"
)
.
intType
()
.
defaultValue
(
3
)
.
withDescription
(
"The max retry times if writing records to database failed."
);
private
static
final
ConfigOption
<
String
>
DATA_FILTER
=
ConfigOptions
.
key
(
"data.filter"
)
.
stringType
()
.
noDefaultValue
()
.
withDescription
(
"the basic filter(lookup or scan), auto added after where."
);
@Override
public
DynamicTableSink
createDynamicTableSink
(
Context
context
)
{
final
FactoryUtil
.
TableFactoryHelper
helper
=
FactoryUtil
.
createTableFactoryHelper
(
this
,
context
);
final
ReadableConfig
config
=
helper
.
getOptions
();
helper
.
validate
();
validateConfigOptions
(
config
);
JdbcOptions
jdbcOptions
=
getJdbcOptions
(
config
);
TableSchema
physicalSchema
=
TableSchemaUtils
.
getPhysicalSchema
(
context
.
getCatalogTable
().
getSchema
());
return
new
JdbcDynamicTableSink
(
jdbcOptions
,
getJdbcExecutionOptions
(
config
),
getJdbcDmlOptions
(
jdbcOptions
,
physicalSchema
),
physicalSchema
);
}
@Override
public
DynamicTableSource
createDynamicTableSource
(
Context
context
)
{
final
FactoryUtil
.
TableFactoryHelper
helper
=
FactoryUtil
.
createTableFactoryHelper
(
this
,
context
);
final
ReadableConfig
config
=
helper
.
getOptions
();
helper
.
validate
();
validateConfigOptions
(
config
);
TableSchema
physicalSchema
=
TableSchemaUtils
.
getPhysicalSchema
(
context
.
getCatalogTable
().
getSchema
());
return
new
JdbcDynamicTableSource
(
getJdbcOptions
(
helper
.
getOptions
()),
getJdbcReadOptions
(
helper
.
getOptions
()),
getJdbcLookupOptions
(
helper
.
getOptions
()),
physicalSchema
);
}
private
JdbcOptions
getJdbcOptions
(
ReadableConfig
readableConfig
)
{
final
String
url
=
readableConfig
.
get
(
URL
);
final
JdbcOptions
.
Builder
builder
=
JdbcOptions
.
builder
()
.
setDBUrl
(
url
)
.
setTableName
(
readableConfig
.
get
(
TABLE_NAME
))
.
setDialect
(
JdbcDialects
.
get
(
url
).
get
())
.
setParallelism
(
readableConfig
.
getOptional
(
FactoryUtil
.
SINK_PARALLELISM
)
.
orElse
(
null
))
.
setConnectionCheckTimeoutSeconds
(
(
int
)
readableConfig
.
get
(
MAX_RETRY_TIMEOUT
).
getSeconds
());
readableConfig
.
getOptional
(
DRIVER
).
ifPresent
(
builder:
:
setDriverName
);
readableConfig
.
getOptional
(
USERNAME
).
ifPresent
(
builder:
:
setUsername
);
readableConfig
.
getOptional
(
PASSWORD
).
ifPresent
(
builder:
:
setPassword
);
return
builder
.
build
();
}
private
JdbcReadOptions
getJdbcReadOptions
(
ReadableConfig
readableConfig
)
{
final
Optional
<
String
>
partitionColumnName
=
readableConfig
.
getOptional
(
SCAN_PARTITION_COLUMN
);
final
JdbcReadOptions
.
Builder
builder
=
JdbcReadOptions
.
builder
();
if
(
partitionColumnName
.
isPresent
())
{
builder
.
setPartitionColumnName
(
partitionColumnName
.
get
());
builder
.
setPartitionLowerBound
(
readableConfig
.
get
(
SCAN_PARTITION_LOWER_BOUND
));
builder
.
setPartitionUpperBound
(
readableConfig
.
get
(
SCAN_PARTITION_UPPER_BOUND
));
builder
.
setNumPartitions
(
readableConfig
.
get
(
SCAN_PARTITION_NUM
));
}
readableConfig
.
getOptional
(
SCAN_FETCH_SIZE
).
ifPresent
(
builder:
:
setFetchSize
);
builder
.
setAutoCommit
(
readableConfig
.
get
(
SCAN_AUTO_COMMIT
));
return
builder
.
build
();
}
private
JdbcLookupOptions
getJdbcLookupOptions
(
ReadableConfig
readableConfig
)
{
return
new
JdbcLookupOptions
(
readableConfig
.
get
(
LOOKUP_CACHE_MAX_ROWS
),
readableConfig
.
get
(
LOOKUP_CACHE_TTL
).
toMillis
(),
readableConfig
.
get
(
LOOKUP_MAX_RETRIES
),
readableConfig
.
get
(
DATA_FILTER
));
}
private
JdbcExecutionOptions
getJdbcExecutionOptions
(
ReadableConfig
config
)
{
final
JdbcExecutionOptions
.
Builder
builder
=
new
JdbcExecutionOptions
.
Builder
();
builder
.
withBatchSize
(
config
.
get
(
SINK_BUFFER_FLUSH_MAX_ROWS
));
builder
.
withBatchIntervalMs
(
config
.
get
(
SINK_BUFFER_FLUSH_INTERVAL
).
toMillis
());
builder
.
withMaxRetries
(
config
.
get
(
SINK_MAX_RETRIES
));
return
builder
.
build
();
}
private
JdbcDmlOptions
getJdbcDmlOptions
(
JdbcOptions
jdbcOptions
,
TableSchema
schema
)
{
String
[]
keyFields
=
schema
.
getPrimaryKey
()
.
map
(
pk
->
pk
.
getColumns
().
toArray
(
new
String
[
0
]))
.
orElse
(
null
);
return
JdbcDmlOptions
.
builder
()
.
withTableName
(
jdbcOptions
.
getTableName
())
.
withDialect
(
jdbcOptions
.
getDialect
())
.
withFieldNames
(
schema
.
getFieldNames
())
.
withKeyFields
(
keyFields
)
.
build
();
}
@Override
public
String
factoryIdentifier
()
{
return
IDENTIFIER
;
}
@Override
public
Set
<
ConfigOption
<?>>
requiredOptions
()
{
Set
<
ConfigOption
<?>>
requiredOptions
=
new
HashSet
<>();
requiredOptions
.
add
(
URL
);
requiredOptions
.
add
(
TABLE_NAME
);
return
requiredOptions
;
}
@Override
public
Set
<
ConfigOption
<?>>
optionalOptions
()
{
Set
<
ConfigOption
<?>>
optionalOptions
=
new
HashSet
<>();
optionalOptions
.
add
(
DRIVER
);
optionalOptions
.
add
(
USERNAME
);
optionalOptions
.
add
(
PASSWORD
);
optionalOptions
.
add
(
SCAN_PARTITION_COLUMN
);
optionalOptions
.
add
(
SCAN_PARTITION_LOWER_BOUND
);
optionalOptions
.
add
(
SCAN_PARTITION_UPPER_BOUND
);
optionalOptions
.
add
(
SCAN_PARTITION_NUM
);
optionalOptions
.
add
(
SCAN_FETCH_SIZE
);
optionalOptions
.
add
(
SCAN_AUTO_COMMIT
);
optionalOptions
.
add
(
LOOKUP_CACHE_MAX_ROWS
);
optionalOptions
.
add
(
LOOKUP_CACHE_TTL
);
optionalOptions
.
add
(
LOOKUP_MAX_RETRIES
);
optionalOptions
.
add
(
SINK_BUFFER_FLUSH_MAX_ROWS
);
optionalOptions
.
add
(
SINK_BUFFER_FLUSH_INTERVAL
);
optionalOptions
.
add
(
SINK_MAX_RETRIES
);
optionalOptions
.
add
(
FactoryUtil
.
SINK_PARALLELISM
);
optionalOptions
.
add
(
MAX_RETRY_TIMEOUT
);
optionalOptions
.
add
(
DATA_FILTER
);
return
optionalOptions
;
}
private
void
validateConfigOptions
(
ReadableConfig
config
)
{
String
jdbcUrl
=
config
.
get
(
URL
);
final
Optional
<
JdbcDialect
>
dialect
=
JdbcDialects
.
get
(
jdbcUrl
);
checkState
(
dialect
.
isPresent
(),
"Cannot handle such jdbc url: "
+
jdbcUrl
);
checkAllOrNone
(
config
,
new
ConfigOption
[]{
USERNAME
,
PASSWORD
});
checkAllOrNone
(
config
,
new
ConfigOption
[]{
SCAN_PARTITION_COLUMN
,
SCAN_PARTITION_NUM
,
SCAN_PARTITION_LOWER_BOUND
,
SCAN_PARTITION_UPPER_BOUND
});
if
(
config
.
getOptional
(
SCAN_PARTITION_LOWER_BOUND
).
isPresent
()
&&
config
.
getOptional
(
SCAN_PARTITION_UPPER_BOUND
).
isPresent
())
{
long
lowerBound
=
config
.
get
(
SCAN_PARTITION_LOWER_BOUND
);
long
upperBound
=
config
.
get
(
SCAN_PARTITION_UPPER_BOUND
);
if
(
lowerBound
>
upperBound
)
{
throw
new
IllegalArgumentException
(
String
.
format
(
"'%s'='%s' must not be larger than '%s'='%s'."
,
SCAN_PARTITION_LOWER_BOUND
.
key
(),
lowerBound
,
SCAN_PARTITION_UPPER_BOUND
.
key
(),
upperBound
));
}
}
checkAllOrNone
(
config
,
new
ConfigOption
[]{
LOOKUP_CACHE_MAX_ROWS
,
LOOKUP_CACHE_TTL
});
if
(
config
.
get
(
LOOKUP_MAX_RETRIES
)
<
0
)
{
throw
new
IllegalArgumentException
(
String
.
format
(
"The value of '%s' option shouldn't be negative, but is %s."
,
LOOKUP_MAX_RETRIES
.
key
(),
config
.
get
(
LOOKUP_MAX_RETRIES
)));
}
if
(
config
.
get
(
SINK_MAX_RETRIES
)
<
0
)
{
throw
new
IllegalArgumentException
(
String
.
format
(
"The value of '%s' option shouldn't be negative, but is %s."
,
SINK_MAX_RETRIES
.
key
(),
config
.
get
(
SINK_MAX_RETRIES
)));
}
if
(
config
.
get
(
MAX_RETRY_TIMEOUT
).
getSeconds
()
<=
0
)
{
throw
new
IllegalArgumentException
(
String
.
format
(
"The value of '%s' option must be in second granularity and shouldn't be smaller than 1 second, but is %s."
,
MAX_RETRY_TIMEOUT
.
key
(),
config
.
get
(
ConfigOptions
.
key
(
MAX_RETRY_TIMEOUT
.
key
())
.
stringType
()
.
noDefaultValue
())));
}
}
private
void
checkAllOrNone
(
ReadableConfig
config
,
ConfigOption
<?>[]
configOptions
)
{
int
presentCount
=
0
;
for
(
ConfigOption
configOption
:
configOptions
)
{
if
(
config
.
getOptional
(
configOption
).
isPresent
())
{
presentCount
++;
}
}
String
[]
propertyNames
=
Arrays
.
stream
(
configOptions
).
map
(
ConfigOption:
:
key
).
toArray
(
String
[]::
new
);
Preconditions
.
checkArgument
(
configOptions
.
length
==
presentCount
||
presentCount
==
0
,
"Either all or none of the following options should be provided:\n"
+
String
.
join
(
"\n"
,
propertyNames
));
}
}
dlink-connectors/dlink-connector-jdbc-1.13/src/main/java/org/apache/flink/connector/jdbc/table/JdbcDynamicTableSource.java
0 → 100644
View file @
9c315b5c
/*
*
* 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.
*
*/
package
org
.
apache
.
flink
.
connector
.
jdbc
.
table
;
import
org.apache.flink.annotation.Internal
;
import
org.apache.flink.connector.jdbc.dialect.JdbcDialect
;
import
org.apache.flink.connector.jdbc.internal.options.JdbcLookupOptions
;
import
org.apache.flink.connector.jdbc.internal.options.JdbcOptions
;
import
org.apache.flink.connector.jdbc.internal.options.JdbcReadOptions
;
import
org.apache.flink.connector.jdbc.split.JdbcNumericBetweenParametersProvider
;
import
org.apache.flink.table.api.TableSchema
;
import
org.apache.flink.table.connector.ChangelogMode
;
import
org.apache.flink.table.connector.source.DynamicTableSource
;
import
org.apache.flink.table.connector.source.InputFormatProvider
;
import
org.apache.flink.table.connector.source.LookupTableSource
;
import
org.apache.flink.table.connector.source.ScanTableSource
;
import
org.apache.flink.table.connector.source.TableFunctionProvider
;
import
org.apache.flink.table.connector.source.abilities.SupportsLimitPushDown
;
import
org.apache.flink.table.connector.source.abilities.SupportsProjectionPushDown
;
import
org.apache.flink.table.types.logical.RowType
;
import
org.apache.flink.table.utils.TableSchemaUtils
;
import
org.apache.flink.util.Preconditions
;
import
java.util.Objects
;
/** A {@link DynamicTableSource} for JDBC. */
@Internal
public
class
JdbcDynamicTableSource
implements
ScanTableSource
,
LookupTableSource
,
SupportsProjectionPushDown
,
SupportsLimitPushDown
{
private
final
JdbcOptions
options
;
private
final
JdbcReadOptions
readOptions
;
private
final
JdbcLookupOptions
lookupOptions
;
private
TableSchema
physicalSchema
;
private
final
String
dialectName
;
private
long
limit
=
-
1
;
public
JdbcDynamicTableSource
(
JdbcOptions
options
,
JdbcReadOptions
readOptions
,
JdbcLookupOptions
lookupOptions
,
TableSchema
physicalSchema
)
{
this
.
options
=
options
;
this
.
readOptions
=
readOptions
;
this
.
lookupOptions
=
lookupOptions
;
this
.
physicalSchema
=
physicalSchema
;
this
.
dialectName
=
options
.
getDialect
().
dialectName
();
}
@Override
public
LookupRuntimeProvider
getLookupRuntimeProvider
(
LookupContext
context
)
{
// JDBC only support non-nested look up keys
String
[]
keyNames
=
new
String
[
context
.
getKeys
().
length
];
for
(
int
i
=
0
;
i
<
keyNames
.
length
;
i
++)
{
int
[]
innerKeyArr
=
context
.
getKeys
()[
i
];
Preconditions
.
checkArgument
(
innerKeyArr
.
length
==
1
,
"JDBC only support non-nested look up keys"
);
keyNames
[
i
]
=
physicalSchema
.
getFieldNames
()[
innerKeyArr
[
0
]];
}
final
RowType
rowType
=
(
RowType
)
physicalSchema
.
toRowDataType
().
getLogicalType
();
return
TableFunctionProvider
.
of
(
new
JdbcRowDataLookupFunction
(
options
,
lookupOptions
,
physicalSchema
.
getFieldNames
(),
physicalSchema
.
getFieldDataTypes
(),
keyNames
,
rowType
));
}
@Override
public
ScanRuntimeProvider
getScanRuntimeProvider
(
ScanContext
runtimeProviderContext
)
{
final
JdbcRowDataInputFormat
.
Builder
builder
=
JdbcRowDataInputFormat
.
builder
()
.
setDrivername
(
options
.
getDriverName
())
.
setDBUrl
(
options
.
getDbURL
())
.
setUsername
(
options
.
getUsername
().
orElse
(
null
))
.
setPassword
(
options
.
getPassword
().
orElse
(
null
))
.
setAutoCommit
(
readOptions
.
getAutoCommit
());
if
(
readOptions
.
getFetchSize
()
!=
0
)
{
builder
.
setFetchSize
(
readOptions
.
getFetchSize
());
}
final
JdbcDialect
dialect
=
options
.
getDialect
();
String
query
=
dialect
.
getSelectFromStatement
(
options
.
getTableName
(),
physicalSchema
.
getFieldNames
(),
lookupOptions
.
getPreFilterCondition
());
if
(
readOptions
.
getPartitionColumnName
().
isPresent
())
{
long
lowerBound
=
readOptions
.
getPartitionLowerBound
().
get
();
long
upperBound
=
readOptions
.
getPartitionUpperBound
().
get
();
int
numPartitions
=
readOptions
.
getNumPartitions
().
get
();
builder
.
setParametersProvider
(
new
JdbcNumericBetweenParametersProvider
(
lowerBound
,
upperBound
)
.
ofBatchNum
(
numPartitions
));
if
(
lookupOptions
.
getPreFilterCondition
().
length
>
0
)
{
query
+=
" AND "
;
}
else
{
query
+=
" WHERE "
;
}
query
+=
dialect
.
quoteIdentifier
(
readOptions
.
getPartitionColumnName
().
get
())
+
" BETWEEN ? AND ?"
;
}
if
(
limit
>=
0
)
{
query
=
String
.
format
(
"%s %s"
,
query
,
dialect
.
getLimitClause
(
limit
));
}
builder
.
setQuery
(
query
);
final
RowType
rowType
=
(
RowType
)
physicalSchema
.
toRowDataType
().
getLogicalType
();
builder
.
setRowConverter
(
dialect
.
getRowConverter
(
rowType
));
builder
.
setRowDataTypeInfo
(
runtimeProviderContext
.
createTypeInformation
(
physicalSchema
.
toRowDataType
()));
return
InputFormatProvider
.
of
(
builder
.
build
());
}
@Override
public
ChangelogMode
getChangelogMode
()
{
return
ChangelogMode
.
insertOnly
();
}
@Override
public
boolean
supportsNestedProjection
()
{
// JDBC doesn't support nested projection
return
false
;
}
@Override
public
void
applyProjection
(
int
[][]
projectedFields
)
{
this
.
physicalSchema
=
TableSchemaUtils
.
projectSchema
(
physicalSchema
,
projectedFields
);
}
@Override
public
DynamicTableSource
copy
()
{
return
new
JdbcDynamicTableSource
(
options
,
readOptions
,
lookupOptions
,
physicalSchema
);
}
@Override
public
String
asSummaryString
()
{
return
"JDBC:"
+
dialectName
;
}
@Override
public
boolean
equals
(
Object
o
)
{
if
(
this
==
o
)
{
return
true
;
}
if
(!(
o
instanceof
JdbcDynamicTableSource
))
{
return
false
;
}
JdbcDynamicTableSource
that
=
(
JdbcDynamicTableSource
)
o
;
return
Objects
.
equals
(
options
,
that
.
options
)
&&
Objects
.
equals
(
readOptions
,
that
.
readOptions
)
&&
Objects
.
equals
(
lookupOptions
,
that
.
lookupOptions
)
&&
Objects
.
equals
(
physicalSchema
,
that
.
physicalSchema
)
&&
Objects
.
equals
(
dialectName
,
that
.
dialectName
)
&&
Objects
.
equals
(
limit
,
that
.
limit
);
}
@Override
public
int
hashCode
()
{
return
Objects
.
hash
(
options
,
readOptions
,
lookupOptions
,
physicalSchema
,
dialectName
,
limit
);
}
@Override
public
void
applyLimit
(
long
limit
)
{
this
.
limit
=
limit
;
}
}
dlink-connectors/dlink-connector-jdbc-1.13/src/main/java/org/apache/flink/connector/jdbc/table/JdbcLookupFunction.java
0 → 100644
View file @
9c315b5c
/*
*
* 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.
*
*/
package
org
.
apache
.
flink
.
connector
.
jdbc
.
table
;
import
static
org
.
apache
.
flink
.
connector
.
jdbc
.
utils
.
JdbcUtils
.
getFieldFromResultSet
;
import
static
org
.
apache
.
flink
.
util
.
Preconditions
.
checkArgument
;
import
static
org
.
apache
.
flink
.
util
.
Preconditions
.
checkNotNull
;
import
org.apache.flink.annotation.VisibleForTesting
;
import
org.apache.flink.api.common.typeinfo.TypeInformation
;
import
org.apache.flink.api.java.typeutils.RowTypeInfo
;
import
org.apache.flink.connector.jdbc.internal.connection.JdbcConnectionProvider
;
import
org.apache.flink.connector.jdbc.internal.connection.SimpleJdbcConnectionProvider
;
import
org.apache.flink.connector.jdbc.internal.options.JdbcLookupOptions
;
import
org.apache.flink.connector.jdbc.internal.options.JdbcOptions
;
import
org.apache.flink.connector.jdbc.statement.FieldNamedPreparedStatementImpl
;
import
org.apache.flink.connector.jdbc.utils.JdbcTypeUtil
;
import
org.apache.flink.connector.jdbc.utils.JdbcUtils
;
import
org.apache.flink.shaded.guava18.com.google.common.cache.Cache
;
import
org.apache.flink.shaded.guava18.com.google.common.cache.CacheBuilder
;
import
org.apache.flink.table.functions.FunctionContext
;
import
org.apache.flink.table.functions.TableFunction
;
import
org.apache.flink.types.Row
;
import
java.io.IOException
;
import
java.sql.Connection
;
import
java.sql.PreparedStatement
;
import
java.sql.ResultSet
;
import
java.sql.SQLException
;
import
java.util.ArrayList
;
import
java.util.Arrays
;
import
java.util.HashMap
;
import
java.util.List
;
import
java.util.concurrent.TimeUnit
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
/**
* A {@link TableFunction} to query fields from JDBC by keys. The query template like:
*
* <PRE>
* SELECT c, d, e, f from T where a = ? and b = ?
* </PRE>
*
* <p>Support cache the result to avoid frequent accessing to remote databases. 1.The cacheMaxSize
* is -1 means not use cache. 2.For real-time data, you need to set the TTL of cache.
*/
public
class
JdbcLookupFunction
extends
TableFunction
<
Row
>
{
private
static
final
Logger
LOG
=
LoggerFactory
.
getLogger
(
JdbcLookupFunction
.
class
);
private
static
final
long
serialVersionUID
=
2L
;
private
final
String
query
;
private
final
JdbcConnectionProvider
connectionProvider
;
private
final
TypeInformation
[]
keyTypes
;
private
final
int
[]
keySqlTypes
;
private
final
String
[]
fieldNames
;
private
final
String
[]
keyNames
;
private
final
TypeInformation
[]
fieldTypes
;
private
final
int
[]
outputSqlTypes
;
private
final
long
cacheMaxSize
;
private
final
long
cacheExpireMs
;
private
final
int
maxRetryTimes
;
private
transient
PreparedStatement
statement
;
private
transient
Cache
<
Row
,
List
<
Row
>>
cache
;
public
JdbcLookupFunction
(
JdbcOptions
options
,
JdbcLookupOptions
lookupOptions
,
String
[]
fieldNames
,
TypeInformation
[]
fieldTypes
,
String
[]
keyNames
)
{
this
.
connectionProvider
=
new
SimpleJdbcConnectionProvider
(
options
);
this
.
fieldNames
=
fieldNames
;
this
.
fieldTypes
=
fieldTypes
;
this
.
keyNames
=
keyNames
;
List
<
String
>
nameList
=
Arrays
.
asList
(
fieldNames
);
this
.
keyTypes
=
Arrays
.
stream
(
keyNames
)
.
map
(
s
->
{
checkArgument
(
nameList
.
contains
(
s
),
"keyName %s can't find in fieldNames %s."
,
s
,
nameList
);
return
fieldTypes
[
nameList
.
indexOf
(
s
)];
})
.
toArray
(
TypeInformation
[]::
new
);
this
.
cacheMaxSize
=
lookupOptions
.
getCacheMaxSize
();
this
.
cacheExpireMs
=
lookupOptions
.
getCacheExpireMs
();
this
.
maxRetryTimes
=
lookupOptions
.
getMaxRetryTimes
();
this
.
keySqlTypes
=
Arrays
.
stream
(
keyTypes
).
mapToInt
(
JdbcTypeUtil:
:
typeInformationToSqlType
).
toArray
();
this
.
outputSqlTypes
=
Arrays
.
stream
(
fieldTypes
)
.
mapToInt
(
JdbcTypeUtil:
:
typeInformationToSqlType
)
.
toArray
();
String
[]
preFilterCondition
=
lookupOptions
.
getPreFilterCondition
();
String
[]
finalKeyNames
=
new
String
[
keyNames
.
length
+
preFilterCondition
.
length
];
System
.
arraycopy
(
keyNames
,
0
,
finalKeyNames
,
0
,
keyNames
.
length
);
System
.
arraycopy
(
preFilterCondition
,
0
,
finalKeyNames
,
keyNames
.
length
,
preFilterCondition
.
length
);
this
.
query
=
FieldNamedPreparedStatementImpl
.
parseNamedStatement
(
options
.
getDialect
()
.
getSelectFromStatement
(
options
.
getTableName
(),
fieldNames
,
finalKeyNames
),
new
HashMap
<>());
}
public
static
Builder
builder
()
{
return
new
Builder
();
}
@Override
public
void
open
(
FunctionContext
context
)
throws
Exception
{
try
{
establishConnectionAndStatement
();
this
.
cache
=
cacheMaxSize
==
-
1
||
cacheExpireMs
==
-
1
?
null
:
CacheBuilder
.
newBuilder
()
.
expireAfterWrite
(
cacheExpireMs
,
TimeUnit
.
MILLISECONDS
)
.
maximumSize
(
cacheMaxSize
)
.
build
();
}
catch
(
SQLException
sqe
)
{
throw
new
IllegalArgumentException
(
"open() failed."
,
sqe
);
}
catch
(
ClassNotFoundException
cnfe
)
{
throw
new
IllegalArgumentException
(
"JDBC driver class not found."
,
cnfe
);
}
}
public
void
eval
(
Object
...
keys
)
{
Row
keyRow
=
Row
.
of
(
keys
);
if
(
cache
!=
null
)
{
List
<
Row
>
cachedRows
=
cache
.
getIfPresent
(
keyRow
);
if
(
cachedRows
!=
null
)
{
for
(
Row
cachedRow
:
cachedRows
)
{
collect
(
cachedRow
);
}
return
;
}
}
for
(
int
retry
=
0
;
retry
<=
maxRetryTimes
;
retry
++)
{
try
{
statement
.
clearParameters
();
for
(
int
i
=
0
;
i
<
keys
.
length
;
i
++)
{
JdbcUtils
.
setField
(
statement
,
keySqlTypes
[
i
],
keys
[
i
],
i
);
}
try
(
ResultSet
resultSet
=
statement
.
executeQuery
())
{
if
(
cache
==
null
)
{
while
(
resultSet
.
next
())
{
collect
(
convertToRowFromResultSet
(
resultSet
));
}
}
else
{
ArrayList
<
Row
>
rows
=
new
ArrayList
<>();
while
(
resultSet
.
next
())
{
Row
row
=
convertToRowFromResultSet
(
resultSet
);
rows
.
add
(
row
);
collect
(
row
);
}
rows
.
trimToSize
();
cache
.
put
(
keyRow
,
rows
);
}
}
break
;
}
catch
(
SQLException
e
)
{
LOG
.
error
(
String
.
format
(
"JDBC executeBatch error, retry times = %d"
,
retry
),
e
);
if
(
retry
>=
maxRetryTimes
)
{
throw
new
RuntimeException
(
"Execution of JDBC statement failed."
,
e
);
}
try
{
if
(!
connectionProvider
.
isConnectionValid
())
{
statement
.
close
();
connectionProvider
.
closeConnection
();
establishConnectionAndStatement
();
}
}
catch
(
SQLException
|
ClassNotFoundException
excpetion
)
{
LOG
.
error
(
"JDBC connection is not valid, and reestablish connection failed"
,
excpetion
);
throw
new
RuntimeException
(
"Reestablish JDBC connection failed"
,
excpetion
);
}
try
{
Thread
.
sleep
(
1000
*
retry
);
}
catch
(
InterruptedException
e1
)
{
throw
new
RuntimeException
(
e1
);
}
}
}
}
private
Row
convertToRowFromResultSet
(
ResultSet
resultSet
)
throws
SQLException
{
Row
row
=
new
Row
(
outputSqlTypes
.
length
);
for
(
int
i
=
0
;
i
<
outputSqlTypes
.
length
;
i
++)
{
row
.
setField
(
i
,
getFieldFromResultSet
(
i
,
outputSqlTypes
[
i
],
resultSet
));
}
return
row
;
}
private
void
establishConnectionAndStatement
()
throws
SQLException
,
ClassNotFoundException
{
Connection
dbConn
=
connectionProvider
.
getOrEstablishConnection
();
statement
=
dbConn
.
prepareStatement
(
query
);
}
@Override
public
void
close
()
throws
IOException
{
if
(
cache
!=
null
)
{
cache
.
cleanUp
();
cache
=
null
;
}
if
(
statement
!=
null
)
{
try
{
statement
.
close
();
}
catch
(
SQLException
e
)
{
LOG
.
info
(
"JDBC statement could not be closed: "
+
e
.
getMessage
());
}
finally
{
statement
=
null
;
}
}
connectionProvider
.
closeConnection
();
}
@VisibleForTesting
public
Connection
getDbConnection
()
{
return
connectionProvider
.
getConnection
();
}
@Override
public
TypeInformation
<
Row
>
getResultType
()
{
return
new
RowTypeInfo
(
fieldTypes
,
fieldNames
);
}
@Override
public
TypeInformation
<?>[]
getParameterTypes
(
Class
<?>[]
signature
)
{
return
keyTypes
;
}
/** Builder for a {@link JdbcLookupFunction}. */
public
static
class
Builder
{
private
JdbcOptions
options
;
private
JdbcLookupOptions
lookupOptions
;
protected
String
[]
fieldNames
;
protected
TypeInformation
[]
fieldTypes
;
protected
String
[]
keyNames
;
/** required, jdbc options. */
public
Builder
setOptions
(
JdbcOptions
options
)
{
this
.
options
=
options
;
return
this
;
}
/** optional, lookup related options. */
public
Builder
setLookupOptions
(
JdbcLookupOptions
lookupOptions
)
{
this
.
lookupOptions
=
lookupOptions
;
return
this
;
}
/** required, field names of this jdbc table. */
public
Builder
setFieldNames
(
String
[]
fieldNames
)
{
this
.
fieldNames
=
fieldNames
;
return
this
;
}
/** required, field types of this jdbc table. */
public
Builder
setFieldTypes
(
TypeInformation
[]
fieldTypes
)
{
this
.
fieldTypes
=
fieldTypes
;
return
this
;
}
/** required, key names to query this jdbc table. */
public
Builder
setKeyNames
(
String
[]
keyNames
)
{
this
.
keyNames
=
keyNames
;
return
this
;
}
/**
* Finalizes the configuration and checks validity.
*
* @return Configured JdbcLookupFunction
*/
public
JdbcLookupFunction
build
()
{
checkNotNull
(
options
,
"No JdbcOptions supplied."
);
if
(
lookupOptions
==
null
)
{
lookupOptions
=
JdbcLookupOptions
.
builder
().
build
();
}
checkNotNull
(
fieldNames
,
"No fieldNames supplied."
);
checkNotNull
(
fieldTypes
,
"No fieldTypes supplied."
);
checkNotNull
(
keyNames
,
"No keyNames supplied."
);
return
new
JdbcLookupFunction
(
options
,
lookupOptions
,
fieldNames
,
fieldTypes
,
keyNames
);
}
}
}
dlink-connectors/dlink-connector-jdbc-1.13/src/main/java/org/apache/flink/connector/jdbc/table/JdbcRowDataLookupFunction.java
0 → 100644
View file @
9c315b5c
/*
*
* 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.
*
*/
package
org
.
apache
.
flink
.
connector
.
jdbc
.
table
;
import
org.apache.flink.annotation.Internal
;
import
org.apache.flink.annotation.VisibleForTesting
;
import
org.apache.flink.connector.jdbc.dialect.JdbcDialect
;
import
org.apache.flink.connector.jdbc.dialect.JdbcDialects
;
import
org.apache.flink.connector.jdbc.internal.connection.JdbcConnectionProvider
;
import
org.apache.flink.connector.jdbc.internal.connection.SimpleJdbcConnectionProvider
;
import
org.apache.flink.connector.jdbc.internal.converter.JdbcRowConverter
;
import
org.apache.flink.connector.jdbc.internal.options.JdbcLookupOptions
;
import
org.apache.flink.connector.jdbc.internal.options.JdbcOptions
;
import
org.apache.flink.connector.jdbc.statement.FieldNamedPreparedStatement
;
import
org.apache.flink.shaded.guava18.com.google.common.cache.Cache
;
import
org.apache.flink.shaded.guava18.com.google.common.cache.CacheBuilder
;
import
org.apache.flink.table.data.GenericRowData
;
import
org.apache.flink.table.data.RowData
;
import
org.apache.flink.table.functions.FunctionContext
;
import
org.apache.flink.table.functions.TableFunction
;
import
org.apache.flink.table.types.DataType
;
import
org.apache.flink.table.types.logical.LogicalType
;
import
org.apache.flink.table.types.logical.RowType
;
import
org.apache.flink.util.Preconditions
;
import
java.io.IOException
;
import
java.sql.Connection
;
import
java.sql.ResultSet
;
import
java.sql.SQLException
;
import
java.util.ArrayList
;
import
java.util.Arrays
;
import
java.util.Iterator
;
import
java.util.List
;
import
java.util.concurrent.TimeUnit
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
@Internal
public
class
JdbcRowDataLookupFunction
extends
TableFunction
<
RowData
>
{
private
static
final
Logger
LOG
=
LoggerFactory
.
getLogger
(
JdbcRowDataLookupFunction
.
class
);
private
static
final
long
serialVersionUID
=
2L
;
private
final
String
query
;
private
final
JdbcConnectionProvider
connectionProvider
;
private
final
DataType
[]
keyTypes
;
private
final
String
[]
keyNames
;
private
final
long
cacheMaxSize
;
private
final
long
cacheExpireMs
;
private
final
int
maxRetryTimes
;
private
final
JdbcDialect
jdbcDialect
;
private
final
JdbcRowConverter
jdbcRowConverter
;
private
final
JdbcRowConverter
lookupKeyRowConverter
;
private
transient
FieldNamedPreparedStatement
statement
;
private
transient
Cache
<
RowData
,
List
<
RowData
>>
cache
;
public
JdbcRowDataLookupFunction
(
JdbcOptions
options
,
JdbcLookupOptions
lookupOptions
,
String
[]
fieldNames
,
DataType
[]
fieldTypes
,
String
[]
keyNames
,
RowType
rowType
)
{
Preconditions
.
checkNotNull
(
options
,
"No JdbcOptions supplied."
);
Preconditions
.
checkNotNull
(
fieldNames
,
"No fieldNames supplied."
);
Preconditions
.
checkNotNull
(
fieldTypes
,
"No fieldTypes supplied."
);
Preconditions
.
checkNotNull
(
keyNames
,
"No keyNames supplied."
);
this
.
connectionProvider
=
new
SimpleJdbcConnectionProvider
(
options
);
this
.
keyNames
=
keyNames
;
List
<
String
>
nameList
=
Arrays
.
asList
(
fieldNames
);
this
.
keyTypes
=
(
DataType
[])
Arrays
.
stream
(
keyNames
).
map
((
s
)
->
{
Preconditions
.
checkArgument
(
nameList
.
contains
(
s
),
"keyName %s can't find in fieldNames %s."
,
new
Object
[]{
s
,
nameList
});
return
fieldTypes
[
nameList
.
indexOf
(
s
)];
}).
toArray
((
x
$
0
)
->
{
return
new
DataType
[
x
$
0
];
});
this
.
cacheMaxSize
=
lookupOptions
.
getCacheMaxSize
();
this
.
cacheExpireMs
=
lookupOptions
.
getCacheExpireMs
();
this
.
maxRetryTimes
=
lookupOptions
.
getMaxRetryTimes
();
String
[]
preFilterCondition
=
lookupOptions
.
getPreFilterCondition
();
String
[]
finalKeyNames
=
new
String
[
keyNames
.
length
+
preFilterCondition
.
length
];
System
.
arraycopy
(
keyNames
,
0
,
finalKeyNames
,
0
,
keyNames
.
length
);
System
.
arraycopy
(
preFilterCondition
,
0
,
finalKeyNames
,
keyNames
.
length
,
preFilterCondition
.
length
);
this
.
query
=
options
.
getDialect
().
getSelectFromStatement
(
options
.
getTableName
(),
fieldNames
,
finalKeyNames
);
String
dbURL
=
options
.
getDbURL
();
this
.
jdbcDialect
=
(
JdbcDialect
)
JdbcDialects
.
get
(
dbURL
).
orElseThrow
(()
->
{
return
new
UnsupportedOperationException
(
String
.
format
(
"Unknown dbUrl:%s"
,
dbURL
));
});
this
.
jdbcRowConverter
=
this
.
jdbcDialect
.
getRowConverter
(
rowType
);
this
.
lookupKeyRowConverter
=
this
.
jdbcDialect
.
getRowConverter
(
RowType
.
of
((
LogicalType
[])
Arrays
.
stream
(
this
.
keyTypes
).
map
(
DataType:
:
getLogicalType
).
toArray
((
x
$
0
)
->
{
return
new
LogicalType
[
x
$
0
];
})));
}
public
void
open
(
FunctionContext
context
)
throws
Exception
{
try
{
this
.
establishConnectionAndStatement
();
this
.
cache
=
this
.
cacheMaxSize
!=
-
1L
&&
this
.
cacheExpireMs
!=
-
1L
?
CacheBuilder
.
newBuilder
().
expireAfterWrite
(
this
.
cacheExpireMs
,
TimeUnit
.
MILLISECONDS
)
.
maximumSize
(
this
.
cacheMaxSize
).
build
()
:
null
;
}
catch
(
SQLException
var3
)
{
throw
new
IllegalArgumentException
(
"open() failed."
,
var3
);
}
catch
(
ClassNotFoundException
var4
)
{
throw
new
IllegalArgumentException
(
"JDBC driver class not found."
,
var4
);
}
}
public
void
eval
(
Object
...
keys
)
{
RowData
keyRow
=
GenericRowData
.
of
(
keys
);
if
(
this
.
cache
!=
null
)
{
List
<
RowData
>
cachedRows
=
(
List
)
this
.
cache
.
getIfPresent
(
keyRow
);
if
(
cachedRows
!=
null
)
{
Iterator
var24
=
cachedRows
.
iterator
();
while
(
var24
.
hasNext
())
{
RowData
cachedRow
=
(
RowData
)
var24
.
next
();
this
.
collect
(
cachedRow
);
}
return
;
}
}
int
retry
=
0
;
while
(
retry
<=
this
.
maxRetryTimes
)
{
try
{
this
.
statement
.
clearParameters
();
this
.
statement
=
this
.
lookupKeyRowConverter
.
toExternal
(
keyRow
,
this
.
statement
);
ResultSet
resultSet
=
this
.
statement
.
executeQuery
();
Throwable
var5
=
null
;
try
{
if
(
this
.
cache
==
null
)
{
while
(
resultSet
.
next
())
{
this
.
collect
(
this
.
jdbcRowConverter
.
toInternal
(
resultSet
));
}
return
;
}
ArrayList
rows
=
new
ArrayList
();
while
(
resultSet
.
next
())
{
RowData
row
=
this
.
jdbcRowConverter
.
toInternal
(
resultSet
);
rows
.
add
(
row
);
this
.
collect
(
row
);
}
rows
.
trimToSize
();
this
.
cache
.
put
(
keyRow
,
rows
);
break
;
}
catch
(
Throwable
var20
)
{
var5
=
var20
;
throw
var20
;
}
finally
{
if
(
resultSet
!=
null
)
{
if
(
var5
!=
null
)
{
try
{
resultSet
.
close
();
}
catch
(
Throwable
var18
)
{
var5
.
addSuppressed
(
var18
);
}
}
else
{
resultSet
.
close
();
}
}
}
}
catch
(
SQLException
var22
)
{
LOG
.
error
(
String
.
format
(
"JDBC executeBatch error, retry times = %d"
,
retry
),
var22
);
if
(
retry
>=
this
.
maxRetryTimes
)
{
throw
new
RuntimeException
(
"Execution of JDBC statement failed."
,
var22
);
}
try
{
if
(!
this
.
connectionProvider
.
isConnectionValid
())
{
this
.
statement
.
close
();
this
.
connectionProvider
.
closeConnection
();
this
.
establishConnectionAndStatement
();
}
}
catch
(
ClassNotFoundException
|
SQLException
var19
)
{
LOG
.
error
(
"JDBC connection is not valid, and reestablish connection failed"
,
var19
);
throw
new
RuntimeException
(
"Reestablish JDBC connection failed"
,
var19
);
}
try
{
Thread
.
sleep
((
long
)
(
1000
*
retry
));
}
catch
(
InterruptedException
var17
)
{
throw
new
RuntimeException
(
var17
);
}
++
retry
;
}
}
}
private
void
establishConnectionAndStatement
()
throws
SQLException
,
ClassNotFoundException
{
Connection
dbConn
=
this
.
connectionProvider
.
getOrEstablishConnection
();
this
.
statement
=
FieldNamedPreparedStatement
.
prepareStatement
(
dbConn
,
this
.
query
,
this
.
keyNames
);
}
public
void
close
()
throws
IOException
{
if
(
this
.
cache
!=
null
)
{
this
.
cache
.
cleanUp
();
this
.
cache
=
null
;
}
if
(
this
.
statement
!=
null
)
{
try
{
this
.
statement
.
close
();
}
catch
(
SQLException
var5
)
{
LOG
.
info
(
"JDBC statement could not be closed: "
+
var5
.
getMessage
());
}
finally
{
this
.
statement
=
null
;
}
}
this
.
connectionProvider
.
closeConnection
();
}
@VisibleForTesting
public
Connection
getDbConnection
()
{
return
this
.
connectionProvider
.
getConnection
();
}
}
dlink-connectors/dlink-connector-jdbc-1.14/src/main/java/org/apache/flink/connector/jdbc/dialect/JdbcDialect.java
0 → 100644
View file @
9c315b5c
/*
*
* 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.
*
*/
package
org
.
apache
.
flink
.
connector
.
jdbc
.
dialect
;
import
static
java
.
lang
.
String
.
format
;
import
org.apache.flink.annotation.Internal
;
import
org.apache.flink.connector.jdbc.internal.converter.JdbcRowConverter
;
import
org.apache.flink.table.api.TableSchema
;
import
org.apache.flink.table.api.ValidationException
;
import
org.apache.flink.table.types.logical.RowType
;
import
java.io.Serializable
;
import
java.util.Arrays
;
import
java.util.Optional
;
import
java.util.stream.Collectors
;
/** Handle the SQL dialect of jdbc driver. */
@Internal
public
interface
JdbcDialect
extends
Serializable
{
/**
* Get the name of jdbc dialect.
*
* @return the dialect name.
*/
String
dialectName
();
/**
* Check if this dialect instance can handle a certain jdbc url.
*
* @param url the jdbc url.
* @return True if the dialect can be applied on the given jdbc url.
*/
boolean
canHandle
(
String
url
);
/**
* Get converter that convert jdbc object and Flink internal object each other.
*
* @param rowType the given row type
* @return a row converter for the database
*/
JdbcRowConverter
getRowConverter
(
RowType
rowType
);
/**
* Get limit clause to limit the number of emitted row from the jdbc source.
*
* @param limit number of row to emit. The value of the parameter should be non-negative.
* @return the limit clause.
*/
String
getLimitClause
(
long
limit
);
/**
* Check if this dialect instance support a specific data type in table schema.
*
* @param schema the table schema.
* @exception ValidationException in case of the table schema contains unsupported type.
*/
default
void
validate
(
TableSchema
schema
)
throws
ValidationException
{
}
/**
* @return the default driver class name, if user not configure the driver class name, then will
* use this one.
*/
default
Optional
<
String
>
defaultDriverName
()
{
return
Optional
.
empty
();
}
/**
* Quotes the identifier. This is used to put quotes around the identifier in case the column
* name is a reserved keyword, or in case it contains characters that require quotes (e.g.
* space). Default using double quotes {@code "} to quote.
*/
default
String
quoteIdentifier
(
String
identifier
)
{
return
"\""
+
identifier
+
"\""
;
}
/**
* Get dialect upsert statement, the database has its own upsert syntax, such as Mysql using
* DUPLICATE KEY UPDATE, and PostgresSQL using ON CONFLICT... DO UPDATE SET..
*
* @return None if dialect does not support upsert statement, the writer will degrade to the use
* of select + update/insert, this performance is poor.
*/
default
Optional
<
String
>
getUpsertStatement
(
String
tableName
,
String
[]
fieldNames
,
String
[]
uniqueKeyFields
)
{
return
Optional
.
empty
();
}
/** Get row exists statement by condition fields. Default use SELECT. */
default
String
getRowExistsStatement
(
String
tableName
,
String
[]
conditionFields
)
{
String
fieldExpressions
=
Arrays
.
stream
(
conditionFields
)
.
map
(
f
->
format
(
"%s = :%s"
,
quoteIdentifier
(
f
),
f
))
.
collect
(
Collectors
.
joining
(
" AND "
));
return
"SELECT 1 FROM "
+
quoteIdentifier
(
tableName
)
+
" WHERE "
+
fieldExpressions
;
}
/** Get insert into statement. */
default
String
getInsertIntoStatement
(
String
tableName
,
String
[]
fieldNames
)
{
String
columns
=
Arrays
.
stream
(
fieldNames
)
.
map
(
this
::
quoteIdentifier
)
.
collect
(
Collectors
.
joining
(
", "
));
String
placeholders
=
Arrays
.
stream
(
fieldNames
).
map
(
f
->
":"
+
f
).
collect
(
Collectors
.
joining
(
", "
));
return
"INSERT INTO "
+
quoteIdentifier
(
tableName
)
+
"("
+
columns
+
")"
+
" VALUES ("
+
placeholders
+
")"
;
}
/**
* Get update one row statement by condition fields, default not use limit 1, because limit 1 is
* a sql dialect.
*/
default
String
getUpdateStatement
(
String
tableName
,
String
[]
fieldNames
,
String
[]
conditionFields
)
{
String
setClause
=
Arrays
.
stream
(
fieldNames
)
.
map
(
f
->
format
(
"%s = :%s"
,
quoteIdentifier
(
f
),
f
))
.
collect
(
Collectors
.
joining
(
", "
));
String
conditionClause
=
Arrays
.
stream
(
conditionFields
)
.
map
(
f
->
format
(
"%s = :%s"
,
quoteIdentifier
(
f
),
f
))
.
collect
(
Collectors
.
joining
(
" AND "
));
return
"UPDATE "
+
quoteIdentifier
(
tableName
)
+
" SET "
+
setClause
+
" WHERE "
+
conditionClause
;
}
/**
* Get delete one row statement by condition fields, default not use limit 1, because limit 1 is
* a sql dialect.
*/
default
String
getDeleteStatement
(
String
tableName
,
String
[]
conditionFields
)
{
String
conditionClause
=
Arrays
.
stream
(
conditionFields
)
.
map
(
f
->
format
(
"%s = :%s"
,
quoteIdentifier
(
f
),
f
))
.
collect
(
Collectors
.
joining
(
" AND "
));
return
"DELETE FROM "
+
quoteIdentifier
(
tableName
)
+
" WHERE "
+
conditionClause
;
}
/** Get select fields statement by condition fields. Default use SELECT. */
default
String
getSelectFromStatement
(
String
tableName
,
String
[]
selectFields
,
String
[]
conditionFields
)
{
String
selectExpressions
=
Arrays
.
stream
(
selectFields
)
.
map
(
this
::
quoteIdentifier
)
.
collect
(
Collectors
.
joining
(
", "
));
String
fieldExpressions
=
Arrays
.
stream
(
conditionFields
)
.
map
(
f
->
f
.
contains
(
" "
)
||
f
.
contains
(
">"
)
||
f
.
contains
(
"<"
)
||
f
.
contains
(
"="
)
?
f
:
format
(
"%s = :%s"
,
quoteIdentifier
(
f
),
f
))
.
collect
(
Collectors
.
joining
(
" AND "
));
return
"SELECT "
+
selectExpressions
+
" FROM "
+
quoteIdentifier
(
tableName
)
+
(
conditionFields
.
length
>
0
?
" WHERE "
+
fieldExpressions
:
""
);
}
}
dlink-connectors/dlink-connector-jdbc-1.14/src/main/java/org/apache/flink/connector/jdbc/internal/options/JdbcLookupOptions.java
0 → 100644
View file @
9c315b5c
/*
*
* 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.
*
*/
package
org
.
apache
.
flink
.
connector
.
jdbc
.
internal
.
options
;
import
org.apache.flink.connector.jdbc.JdbcExecutionOptions
;
import
java.io.Serializable
;
import
java.util.Objects
;
/** Options for the JDBC lookup. */
public
class
JdbcLookupOptions
implements
Serializable
{
private
final
long
cacheMaxSize
;
private
final
long
cacheExpireMs
;
private
final
int
maxRetryTimes
;
private
final
String
dataFilter
;
public
JdbcLookupOptions
(
long
cacheMaxSize
,
long
cacheExpireMs
,
int
maxRetryTimes
,
String
dataFilter
)
{
this
.
cacheMaxSize
=
cacheMaxSize
;
this
.
cacheExpireMs
=
cacheExpireMs
;
this
.
maxRetryTimes
=
maxRetryTimes
;
this
.
dataFilter
=
dataFilter
;
}
public
long
getCacheMaxSize
()
{
return
cacheMaxSize
;
}
public
long
getCacheExpireMs
()
{
return
cacheExpireMs
;
}
public
int
getMaxRetryTimes
()
{
return
maxRetryTimes
;
}
public
static
Builder
builder
()
{
return
new
Builder
();
}
public
String
[]
getPreFilterCondition
()
{
if
(
dataFilter
==
null
||
dataFilter
.
isEmpty
())
{
return
new
String
[
0
];
}
String
[]
res
=
new
String
[
1
];
res
[
0
]
=
dataFilter
.
replace
(
"\""
,
"'"
);
return
res
;
}
@Override
public
boolean
equals
(
Object
o
)
{
if
(
o
instanceof
JdbcLookupOptions
)
{
JdbcLookupOptions
options
=
(
JdbcLookupOptions
)
o
;
return
Objects
.
equals
(
cacheMaxSize
,
options
.
cacheMaxSize
)
&&
Objects
.
equals
(
cacheExpireMs
,
options
.
cacheExpireMs
)
&&
Objects
.
equals
(
maxRetryTimes
,
options
.
maxRetryTimes
);
}
else
{
return
false
;
}
}
/** Builder of {@link JdbcLookupOptions}. */
public
static
class
Builder
{
private
long
cacheMaxSize
=
-
1L
;
private
long
cacheExpireMs
=
-
1L
;
private
int
maxRetryTimes
=
JdbcExecutionOptions
.
DEFAULT_MAX_RETRY_TIMES
;
private
String
dataFilter
=
""
;
/** optional, lookup cache max size, over this value, the old data will be eliminated. */
public
Builder
setCacheMaxSize
(
long
cacheMaxSize
)
{
this
.
cacheMaxSize
=
cacheMaxSize
;
return
this
;
}
/** optional, lookup cache expire mills, over this time, the old data will expire. */
public
Builder
setCacheExpireMs
(
long
cacheExpireMs
)
{
this
.
cacheExpireMs
=
cacheExpireMs
;
return
this
;
}
/** optional, max retry times for jdbc connector. */
public
Builder
setMaxRetryTimes
(
int
maxRetryTimes
)
{
this
.
maxRetryTimes
=
maxRetryTimes
;
return
this
;
}
public
JdbcLookupOptions
build
()
{
return
new
JdbcLookupOptions
(
cacheMaxSize
,
cacheExpireMs
,
maxRetryTimes
,
dataFilter
);
}
}
}
dlink-connectors/dlink-connector-jdbc-1.14/src/main/java/org/apache/flink/connector/jdbc/table/JdbcConnectorOptions.java
0 → 100644
View file @
9c315b5c
/*
*
* 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.
*
*/
package
org
.
apache
.
flink
.
connector
.
jdbc
.
table
;
import
org.apache.flink.annotation.PublicEvolving
;
import
org.apache.flink.configuration.ConfigOption
;
import
org.apache.flink.configuration.ConfigOptions
;
import
org.apache.flink.table.factories.FactoryUtil
;
import
java.time.Duration
;
/** Options for the JDBC connector. */
@PublicEvolving
public
class
JdbcConnectorOptions
{
public
static
final
ConfigOption
<
String
>
URL
=
ConfigOptions
.
key
(
"url"
)
.
stringType
()
.
noDefaultValue
()
.
withDescription
(
"The JDBC database URL."
);
public
static
final
ConfigOption
<
String
>
TABLE_NAME
=
ConfigOptions
.
key
(
"table-name"
)
.
stringType
()
.
noDefaultValue
()
.
withDescription
(
"The JDBC table name."
);
public
static
final
ConfigOption
<
String
>
USERNAME
=
ConfigOptions
.
key
(
"username"
)
.
stringType
()
.
noDefaultValue
()
.
withDescription
(
"The JDBC user name."
);
public
static
final
ConfigOption
<
String
>
PASSWORD
=
ConfigOptions
.
key
(
"password"
)
.
stringType
()
.
noDefaultValue
()
.
withDescription
(
"The JDBC password."
);
public
static
final
ConfigOption
<
String
>
DRIVER
=
ConfigOptions
.
key
(
"driver"
)
.
stringType
()
.
noDefaultValue
()
.
withDescription
(
"The class name of the JDBC driver to use to connect to this URL. "
+
"If not set, it will automatically be derived from the URL."
);
public
static
final
ConfigOption
<
Duration
>
MAX_RETRY_TIMEOUT
=
ConfigOptions
.
key
(
"connection.max-retry-timeout"
)
.
durationType
()
.
defaultValue
(
Duration
.
ofSeconds
(
60
))
.
withDescription
(
"Maximum timeout between retries."
);
public
static
final
ConfigOption
<
Integer
>
SINK_PARALLELISM
=
FactoryUtil
.
SINK_PARALLELISM
;
// -----------------------------------------------------------------------------------------
// Scan options
// -----------------------------------------------------------------------------------------
public
static
final
ConfigOption
<
String
>
SCAN_PARTITION_COLUMN
=
ConfigOptions
.
key
(
"scan.partition.column"
)
.
stringType
()
.
noDefaultValue
()
.
withDescription
(
"The column name used for partitioning the input."
);
public
static
final
ConfigOption
<
Integer
>
SCAN_PARTITION_NUM
=
ConfigOptions
.
key
(
"scan.partition.num"
)
.
intType
()
.
noDefaultValue
()
.
withDescription
(
"The number of partitions."
);
public
static
final
ConfigOption
<
Long
>
SCAN_PARTITION_LOWER_BOUND
=
ConfigOptions
.
key
(
"scan.partition.lower-bound"
)
.
longType
()
.
noDefaultValue
()
.
withDescription
(
"The smallest value of the first partition."
);
public
static
final
ConfigOption
<
Long
>
SCAN_PARTITION_UPPER_BOUND
=
ConfigOptions
.
key
(
"scan.partition.upper-bound"
)
.
longType
()
.
noDefaultValue
()
.
withDescription
(
"The largest value of the last partition."
);
public
static
final
ConfigOption
<
Integer
>
SCAN_FETCH_SIZE
=
ConfigOptions
.
key
(
"scan.fetch-size"
)
.
intType
()
.
defaultValue
(
0
)
.
withDescription
(
"Gives the reader a hint as to the number of rows that should be fetched "
+
"from the database per round-trip when reading. "
+
"If the value is zero, this hint is ignored."
);
public
static
final
ConfigOption
<
Boolean
>
SCAN_AUTO_COMMIT
=
ConfigOptions
.
key
(
"scan.auto-commit"
)
.
booleanType
()
.
defaultValue
(
true
)
.
withDescription
(
"Sets whether the driver is in auto-commit mode."
);
// -----------------------------------------------------------------------------------------
// Lookup options
// -----------------------------------------------------------------------------------------
public
static
final
ConfigOption
<
Long
>
LOOKUP_CACHE_MAX_ROWS
=
ConfigOptions
.
key
(
"lookup.cache.max-rows"
)
.
longType
()
.
defaultValue
(-
1L
)
.
withDescription
(
"The max number of rows of lookup cache, over this value, the oldest rows will "
+
"be eliminated. \"cache.max-rows\" and \"cache.ttl\" options must all be specified if any of them is "
+
"specified."
);
public
static
final
ConfigOption
<
Duration
>
LOOKUP_CACHE_TTL
=
ConfigOptions
.
key
(
"lookup.cache.ttl"
)
.
durationType
()
.
defaultValue
(
Duration
.
ofSeconds
(
10
))
.
withDescription
(
"The cache time to live."
);
public
static
final
ConfigOption
<
Integer
>
LOOKUP_MAX_RETRIES
=
ConfigOptions
.
key
(
"lookup.max-retries"
)
.
intType
()
.
defaultValue
(
3
)
.
withDescription
(
"The max retry times if lookup database failed."
);
// write config options
public
static
final
ConfigOption
<
Integer
>
SINK_BUFFER_FLUSH_MAX_ROWS
=
ConfigOptions
.
key
(
"sink.buffer-flush.max-rows"
)
.
intType
()
.
defaultValue
(
100
)
.
withDescription
(
"The flush max size (includes all append, upsert and delete records), over this number"
+
" of records, will flush data."
);
public
static
final
ConfigOption
<
Duration
>
SINK_BUFFER_FLUSH_INTERVAL
=
ConfigOptions
.
key
(
"sink.buffer-flush.interval"
)
.
durationType
()
.
defaultValue
(
Duration
.
ofSeconds
(
1
))
.
withDescription
(
"The flush interval mills, over this time, asynchronous threads will flush data."
);
public
static
final
ConfigOption
<
Integer
>
SINK_MAX_RETRIES
=
ConfigOptions
.
key
(
"sink.max-retries"
)
.
intType
()
.
defaultValue
(
3
)
.
withDescription
(
"The max retry times if writing records to database failed."
);
public
static
final
ConfigOption
<
String
>
DATA_FILTER
=
ConfigOptions
.
key
(
"data.filter"
)
.
stringType
()
.
noDefaultValue
()
.
withDescription
(
"the basic filter(lookup or scan), auto added after where."
);
private
JdbcConnectorOptions
()
{
}
}
dlink-connectors/dlink-connector-jdbc-1.14/src/main/java/org/apache/flink/connector/jdbc/table/JdbcDynamicTableFactory.java
0 → 100644
View file @
9c315b5c
/*
*
* 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.
*
*/
package
org
.
apache
.
flink
.
connector
.
jdbc
.
table
;
import
static
org
.
apache
.
flink
.
connector
.
jdbc
.
table
.
JdbcConnectorOptions
.
DATA_FILTER
;
import
static
org
.
apache
.
flink
.
connector
.
jdbc
.
table
.
JdbcConnectorOptions
.
DRIVER
;
import
static
org
.
apache
.
flink
.
connector
.
jdbc
.
table
.
JdbcConnectorOptions
.
LOOKUP_CACHE_MAX_ROWS
;
import
static
org
.
apache
.
flink
.
connector
.
jdbc
.
table
.
JdbcConnectorOptions
.
LOOKUP_CACHE_TTL
;
import
static
org
.
apache
.
flink
.
connector
.
jdbc
.
table
.
JdbcConnectorOptions
.
LOOKUP_MAX_RETRIES
;
import
static
org
.
apache
.
flink
.
connector
.
jdbc
.
table
.
JdbcConnectorOptions
.
MAX_RETRY_TIMEOUT
;
import
static
org
.
apache
.
flink
.
connector
.
jdbc
.
table
.
JdbcConnectorOptions
.
PASSWORD
;
import
static
org
.
apache
.
flink
.
connector
.
jdbc
.
table
.
JdbcConnectorOptions
.
SCAN_AUTO_COMMIT
;
import
static
org
.
apache
.
flink
.
connector
.
jdbc
.
table
.
JdbcConnectorOptions
.
SCAN_FETCH_SIZE
;
import
static
org
.
apache
.
flink
.
connector
.
jdbc
.
table
.
JdbcConnectorOptions
.
SCAN_PARTITION_COLUMN
;
import
static
org
.
apache
.
flink
.
connector
.
jdbc
.
table
.
JdbcConnectorOptions
.
SCAN_PARTITION_LOWER_BOUND
;
import
static
org
.
apache
.
flink
.
connector
.
jdbc
.
table
.
JdbcConnectorOptions
.
SCAN_PARTITION_NUM
;
import
static
org
.
apache
.
flink
.
connector
.
jdbc
.
table
.
JdbcConnectorOptions
.
SCAN_PARTITION_UPPER_BOUND
;
import
static
org
.
apache
.
flink
.
connector
.
jdbc
.
table
.
JdbcConnectorOptions
.
SINK_BUFFER_FLUSH_INTERVAL
;
import
static
org
.
apache
.
flink
.
connector
.
jdbc
.
table
.
JdbcConnectorOptions
.
SINK_BUFFER_FLUSH_MAX_ROWS
;
import
static
org
.
apache
.
flink
.
connector
.
jdbc
.
table
.
JdbcConnectorOptions
.
SINK_MAX_RETRIES
;
import
static
org
.
apache
.
flink
.
connector
.
jdbc
.
table
.
JdbcConnectorOptions
.
SINK_PARALLELISM
;
import
static
org
.
apache
.
flink
.
connector
.
jdbc
.
table
.
JdbcConnectorOptions
.
TABLE_NAME
;
import
static
org
.
apache
.
flink
.
connector
.
jdbc
.
table
.
JdbcConnectorOptions
.
URL
;
import
static
org
.
apache
.
flink
.
connector
.
jdbc
.
table
.
JdbcConnectorOptions
.
USERNAME
;
import
static
org
.
apache
.
flink
.
util
.
Preconditions
.
checkState
;
import
org.apache.flink.annotation.Internal
;
import
org.apache.flink.configuration.ConfigOption
;
import
org.apache.flink.configuration.ConfigOptions
;
import
org.apache.flink.configuration.ReadableConfig
;
import
org.apache.flink.connector.jdbc.JdbcExecutionOptions
;
import
org.apache.flink.connector.jdbc.dialect.JdbcDialect
;
import
org.apache.flink.connector.jdbc.dialect.JdbcDialects
;
import
org.apache.flink.connector.jdbc.internal.options.JdbcConnectorOptions
;
import
org.apache.flink.connector.jdbc.internal.options.JdbcDmlOptions
;
import
org.apache.flink.connector.jdbc.internal.options.JdbcLookupOptions
;
import
org.apache.flink.connector.jdbc.internal.options.JdbcReadOptions
;
import
org.apache.flink.table.api.TableSchema
;
import
org.apache.flink.table.connector.sink.DynamicTableSink
;
import
org.apache.flink.table.connector.source.DynamicTableSource
;
import
org.apache.flink.table.factories.DynamicTableSinkFactory
;
import
org.apache.flink.table.factories.DynamicTableSourceFactory
;
import
org.apache.flink.table.factories.FactoryUtil
;
import
org.apache.flink.table.utils.TableSchemaUtils
;
import
org.apache.flink.util.Preconditions
;
import
java.util.Arrays
;
import
java.util.HashSet
;
import
java.util.Optional
;
import
java.util.Set
;
/**
* Factory for creating configured instances of {@link JdbcDynamicTableSource} and {@link
* JdbcDynamicTableSink}.
*/
@Internal
public
class
JdbcDynamicTableFactory
implements
DynamicTableSourceFactory
,
DynamicTableSinkFactory
{
public
static
final
String
IDENTIFIER
=
"jdbc"
;
@Override
public
DynamicTableSink
createDynamicTableSink
(
Context
context
)
{
final
FactoryUtil
.
TableFactoryHelper
helper
=
FactoryUtil
.
createTableFactoryHelper
(
this
,
context
);
final
ReadableConfig
config
=
helper
.
getOptions
();
helper
.
validate
();
validateConfigOptions
(
config
);
JdbcConnectorOptions
jdbcOptions
=
getJdbcOptions
(
config
);
TableSchema
physicalSchema
=
TableSchemaUtils
.
getPhysicalSchema
(
context
.
getCatalogTable
().
getSchema
());
return
new
JdbcDynamicTableSink
(
jdbcOptions
,
getJdbcExecutionOptions
(
config
),
getJdbcDmlOptions
(
jdbcOptions
,
physicalSchema
),
physicalSchema
);
}
@Override
public
DynamicTableSource
createDynamicTableSource
(
Context
context
)
{
final
FactoryUtil
.
TableFactoryHelper
helper
=
FactoryUtil
.
createTableFactoryHelper
(
this
,
context
);
final
ReadableConfig
config
=
helper
.
getOptions
();
helper
.
validate
();
validateConfigOptions
(
config
);
TableSchema
physicalSchema
=
TableSchemaUtils
.
getPhysicalSchema
(
context
.
getCatalogTable
().
getSchema
());
return
new
JdbcDynamicTableSource
(
getJdbcOptions
(
helper
.
getOptions
()),
getJdbcReadOptions
(
helper
.
getOptions
()),
getJdbcLookupOptions
(
helper
.
getOptions
()),
physicalSchema
);
}
private
JdbcConnectorOptions
getJdbcOptions
(
ReadableConfig
readableConfig
)
{
final
String
url
=
readableConfig
.
get
(
URL
);
final
JdbcConnectorOptions
.
Builder
builder
=
JdbcConnectorOptions
.
builder
()
.
setDBUrl
(
url
)
.
setTableName
(
readableConfig
.
get
(
TABLE_NAME
))
.
setDialect
(
JdbcDialects
.
get
(
url
).
get
())
.
setParallelism
(
readableConfig
.
getOptional
(
SINK_PARALLELISM
).
orElse
(
null
))
.
setConnectionCheckTimeoutSeconds
(
(
int
)
readableConfig
.
get
(
MAX_RETRY_TIMEOUT
).
getSeconds
());
readableConfig
.
getOptional
(
DRIVER
).
ifPresent
(
builder:
:
setDriverName
);
readableConfig
.
getOptional
(
USERNAME
).
ifPresent
(
builder:
:
setUsername
);
readableConfig
.
getOptional
(
PASSWORD
).
ifPresent
(
builder:
:
setPassword
);
return
builder
.
build
();
}
private
JdbcReadOptions
getJdbcReadOptions
(
ReadableConfig
readableConfig
)
{
final
Optional
<
String
>
partitionColumnName
=
readableConfig
.
getOptional
(
SCAN_PARTITION_COLUMN
);
final
JdbcReadOptions
.
Builder
builder
=
JdbcReadOptions
.
builder
();
if
(
partitionColumnName
.
isPresent
())
{
builder
.
setPartitionColumnName
(
partitionColumnName
.
get
());
builder
.
setPartitionLowerBound
(
readableConfig
.
get
(
SCAN_PARTITION_LOWER_BOUND
));
builder
.
setPartitionUpperBound
(
readableConfig
.
get
(
SCAN_PARTITION_UPPER_BOUND
));
builder
.
setNumPartitions
(
readableConfig
.
get
(
SCAN_PARTITION_NUM
));
}
readableConfig
.
getOptional
(
SCAN_FETCH_SIZE
).
ifPresent
(
builder:
:
setFetchSize
);
builder
.
setAutoCommit
(
readableConfig
.
get
(
SCAN_AUTO_COMMIT
));
return
builder
.
build
();
}
private
JdbcLookupOptions
getJdbcLookupOptions
(
ReadableConfig
readableConfig
)
{
return
new
JdbcLookupOptions
(
readableConfig
.
get
(
LOOKUP_CACHE_MAX_ROWS
),
readableConfig
.
get
(
LOOKUP_CACHE_TTL
).
toMillis
(),
readableConfig
.
get
(
LOOKUP_MAX_RETRIES
),
readableConfig
.
get
(
DATA_FILTER
));
}
private
JdbcExecutionOptions
getJdbcExecutionOptions
(
ReadableConfig
config
)
{
final
JdbcExecutionOptions
.
Builder
builder
=
new
JdbcExecutionOptions
.
Builder
();
builder
.
withBatchSize
(
config
.
get
(
SINK_BUFFER_FLUSH_MAX_ROWS
));
builder
.
withBatchIntervalMs
(
config
.
get
(
SINK_BUFFER_FLUSH_INTERVAL
).
toMillis
());
builder
.
withMaxRetries
(
config
.
get
(
SINK_MAX_RETRIES
));
return
builder
.
build
();
}
private
JdbcDmlOptions
getJdbcDmlOptions
(
JdbcConnectorOptions
jdbcOptions
,
TableSchema
schema
)
{
String
[]
keyFields
=
schema
.
getPrimaryKey
()
.
map
(
pk
->
pk
.
getColumns
().
toArray
(
new
String
[
0
]))
.
orElse
(
null
);
return
JdbcDmlOptions
.
builder
()
.
withTableName
(
jdbcOptions
.
getTableName
())
.
withDialect
(
jdbcOptions
.
getDialect
())
.
withFieldNames
(
schema
.
getFieldNames
())
.
withKeyFields
(
keyFields
)
.
build
();
}
@Override
public
String
factoryIdentifier
()
{
return
IDENTIFIER
;
}
@Override
public
Set
<
ConfigOption
<?>>
requiredOptions
()
{
Set
<
ConfigOption
<?>>
requiredOptions
=
new
HashSet
<>();
requiredOptions
.
add
(
URL
);
requiredOptions
.
add
(
TABLE_NAME
);
return
requiredOptions
;
}
@Override
public
Set
<
ConfigOption
<?>>
optionalOptions
()
{
Set
<
ConfigOption
<?>>
optionalOptions
=
new
HashSet
<>();
optionalOptions
.
add
(
DRIVER
);
optionalOptions
.
add
(
USERNAME
);
optionalOptions
.
add
(
PASSWORD
);
optionalOptions
.
add
(
SCAN_PARTITION_COLUMN
);
optionalOptions
.
add
(
SCAN_PARTITION_LOWER_BOUND
);
optionalOptions
.
add
(
SCAN_PARTITION_UPPER_BOUND
);
optionalOptions
.
add
(
SCAN_PARTITION_NUM
);
optionalOptions
.
add
(
SCAN_FETCH_SIZE
);
optionalOptions
.
add
(
SCAN_AUTO_COMMIT
);
optionalOptions
.
add
(
LOOKUP_CACHE_MAX_ROWS
);
optionalOptions
.
add
(
LOOKUP_CACHE_TTL
);
optionalOptions
.
add
(
LOOKUP_MAX_RETRIES
);
optionalOptions
.
add
(
SINK_BUFFER_FLUSH_MAX_ROWS
);
optionalOptions
.
add
(
SINK_BUFFER_FLUSH_INTERVAL
);
optionalOptions
.
add
(
SINK_MAX_RETRIES
);
optionalOptions
.
add
(
SINK_PARALLELISM
);
optionalOptions
.
add
(
MAX_RETRY_TIMEOUT
);
optionalOptions
.
add
(
DATA_FILTER
);
return
optionalOptions
;
}
private
void
validateConfigOptions
(
ReadableConfig
config
)
{
String
jdbcUrl
=
config
.
get
(
URL
);
final
Optional
<
JdbcDialect
>
dialect
=
JdbcDialects
.
get
(
jdbcUrl
);
checkState
(
dialect
.
isPresent
(),
"Cannot handle such jdbc url: "
+
jdbcUrl
);
checkAllOrNone
(
config
,
new
ConfigOption
[]{
USERNAME
,
PASSWORD
});
checkAllOrNone
(
config
,
new
ConfigOption
[]{
SCAN_PARTITION_COLUMN
,
SCAN_PARTITION_NUM
,
SCAN_PARTITION_LOWER_BOUND
,
SCAN_PARTITION_UPPER_BOUND
});
if
(
config
.
getOptional
(
SCAN_PARTITION_LOWER_BOUND
).
isPresent
()
&&
config
.
getOptional
(
SCAN_PARTITION_UPPER_BOUND
).
isPresent
())
{
long
lowerBound
=
config
.
get
(
SCAN_PARTITION_LOWER_BOUND
);
long
upperBound
=
config
.
get
(
SCAN_PARTITION_UPPER_BOUND
);
if
(
lowerBound
>
upperBound
)
{
throw
new
IllegalArgumentException
(
String
.
format
(
"'%s'='%s' must not be larger than '%s'='%s'."
,
SCAN_PARTITION_LOWER_BOUND
.
key
(),
lowerBound
,
SCAN_PARTITION_UPPER_BOUND
.
key
(),
upperBound
));
}
}
checkAllOrNone
(
config
,
new
ConfigOption
[]{
LOOKUP_CACHE_MAX_ROWS
,
LOOKUP_CACHE_TTL
});
if
(
config
.
get
(
LOOKUP_MAX_RETRIES
)
<
0
)
{
throw
new
IllegalArgumentException
(
String
.
format
(
"The value of '%s' option shouldn't be negative, but is %s."
,
LOOKUP_MAX_RETRIES
.
key
(),
config
.
get
(
LOOKUP_MAX_RETRIES
)));
}
if
(
config
.
get
(
SINK_MAX_RETRIES
)
<
0
)
{
throw
new
IllegalArgumentException
(
String
.
format
(
"The value of '%s' option shouldn't be negative, but is %s."
,
SINK_MAX_RETRIES
.
key
(),
config
.
get
(
SINK_MAX_RETRIES
)));
}
if
(
config
.
get
(
MAX_RETRY_TIMEOUT
).
getSeconds
()
<=
0
)
{
throw
new
IllegalArgumentException
(
String
.
format
(
"The value of '%s' option must be in second granularity and shouldn't be smaller than 1 second, but is %s."
,
MAX_RETRY_TIMEOUT
.
key
(),
config
.
get
(
ConfigOptions
.
key
(
MAX_RETRY_TIMEOUT
.
key
())
.
stringType
()
.
noDefaultValue
())));
}
}
private
void
checkAllOrNone
(
ReadableConfig
config
,
ConfigOption
<?>[]
configOptions
)
{
int
presentCount
=
0
;
for
(
ConfigOption
configOption
:
configOptions
)
{
if
(
config
.
getOptional
(
configOption
).
isPresent
())
{
presentCount
++;
}
}
String
[]
propertyNames
=
Arrays
.
stream
(
configOptions
).
map
(
ConfigOption:
:
key
).
toArray
(
String
[]::
new
);
Preconditions
.
checkArgument
(
configOptions
.
length
==
presentCount
||
presentCount
==
0
,
"Either all or none of the following options should be provided:\n"
+
String
.
join
(
"\n"
,
propertyNames
));
}
}
dlink-connectors/dlink-connector-jdbc-1.14/src/main/java/org/apache/flink/connector/jdbc/table/JdbcDynamicTableSource.java
0 → 100644
View file @
9c315b5c
/*
*
* 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.
*
*/
package
org
.
apache
.
flink
.
connector
.
jdbc
.
table
;
import
org.apache.flink.annotation.Internal
;
import
org.apache.flink.connector.jdbc.dialect.JdbcDialect
;
import
org.apache.flink.connector.jdbc.internal.options.JdbcConnectorOptions
;
import
org.apache.flink.connector.jdbc.internal.options.JdbcLookupOptions
;
import
org.apache.flink.connector.jdbc.internal.options.JdbcReadOptions
;
import
org.apache.flink.connector.jdbc.split.JdbcNumericBetweenParametersProvider
;
import
org.apache.flink.table.api.TableSchema
;
import
org.apache.flink.table.connector.ChangelogMode
;
import
org.apache.flink.table.connector.source.DynamicTableSource
;
import
org.apache.flink.table.connector.source.InputFormatProvider
;
import
org.apache.flink.table.connector.source.LookupTableSource
;
import
org.apache.flink.table.connector.source.ScanTableSource
;
import
org.apache.flink.table.connector.source.TableFunctionProvider
;
import
org.apache.flink.table.connector.source.abilities.SupportsLimitPushDown
;
import
org.apache.flink.table.connector.source.abilities.SupportsProjectionPushDown
;
import
org.apache.flink.table.types.logical.RowType
;
import
org.apache.flink.table.utils.TableSchemaUtils
;
import
org.apache.flink.util.Preconditions
;
import
java.util.Objects
;
/** A {@link DynamicTableSource} for JDBC. */
@Internal
public
class
JdbcDynamicTableSource
implements
ScanTableSource
,
LookupTableSource
,
SupportsProjectionPushDown
,
SupportsLimitPushDown
{
private
final
JdbcConnectorOptions
options
;
private
final
JdbcReadOptions
readOptions
;
private
final
JdbcLookupOptions
lookupOptions
;
private
TableSchema
physicalSchema
;
private
final
String
dialectName
;
private
long
limit
=
-
1
;
public
JdbcDynamicTableSource
(
JdbcConnectorOptions
options
,
JdbcReadOptions
readOptions
,
JdbcLookupOptions
lookupOptions
,
TableSchema
physicalSchema
)
{
this
.
options
=
options
;
this
.
readOptions
=
readOptions
;
this
.
lookupOptions
=
lookupOptions
;
this
.
physicalSchema
=
physicalSchema
;
this
.
dialectName
=
options
.
getDialect
().
dialectName
();
}
@Override
public
LookupRuntimeProvider
getLookupRuntimeProvider
(
LookupContext
context
)
{
// JDBC only support non-nested look up keys
String
[]
keyNames
=
new
String
[
context
.
getKeys
().
length
];
for
(
int
i
=
0
;
i
<
keyNames
.
length
;
i
++)
{
int
[]
innerKeyArr
=
context
.
getKeys
()[
i
];
Preconditions
.
checkArgument
(
innerKeyArr
.
length
==
1
,
"JDBC only support non-nested look up keys"
);
keyNames
[
i
]
=
physicalSchema
.
getFieldNames
()[
innerKeyArr
[
0
]];
}
final
RowType
rowType
=
(
RowType
)
physicalSchema
.
toRowDataType
().
getLogicalType
();
return
TableFunctionProvider
.
of
(
new
JdbcRowDataLookupFunction
(
options
,
lookupOptions
,
physicalSchema
.
getFieldNames
(),
physicalSchema
.
getFieldDataTypes
(),
keyNames
,
rowType
));
}
@Override
public
ScanRuntimeProvider
getScanRuntimeProvider
(
ScanContext
runtimeProviderContext
)
{
final
JdbcRowDataInputFormat
.
Builder
builder
=
JdbcRowDataInputFormat
.
builder
()
.
setDrivername
(
options
.
getDriverName
())
.
setDBUrl
(
options
.
getDbURL
())
.
setUsername
(
options
.
getUsername
().
orElse
(
null
))
.
setPassword
(
options
.
getPassword
().
orElse
(
null
))
.
setAutoCommit
(
readOptions
.
getAutoCommit
());
if
(
readOptions
.
getFetchSize
()
!=
0
)
{
builder
.
setFetchSize
(
readOptions
.
getFetchSize
());
}
final
JdbcDialect
dialect
=
options
.
getDialect
();
String
query
=
dialect
.
getSelectFromStatement
(
options
.
getTableName
(),
physicalSchema
.
getFieldNames
(),
lookupOptions
.
getPreFilterCondition
());
if
(
readOptions
.
getPartitionColumnName
().
isPresent
())
{
long
lowerBound
=
readOptions
.
getPartitionLowerBound
().
get
();
long
upperBound
=
readOptions
.
getPartitionUpperBound
().
get
();
int
numPartitions
=
readOptions
.
getNumPartitions
().
get
();
builder
.
setParametersProvider
(
new
JdbcNumericBetweenParametersProvider
(
lowerBound
,
upperBound
)
.
ofBatchNum
(
numPartitions
));
if
(
lookupOptions
.
getPreFilterCondition
().
length
>
0
)
{
query
+=
" AND "
;
}
else
{
query
+=
" WHERE "
;
}
query
+=
dialect
.
quoteIdentifier
(
readOptions
.
getPartitionColumnName
().
get
())
+
" BETWEEN ? AND ?"
;
}
if
(
limit
>=
0
)
{
query
=
String
.
format
(
"%s %s"
,
query
,
dialect
.
getLimitClause
(
limit
));
}
builder
.
setQuery
(
query
);
final
RowType
rowType
=
(
RowType
)
physicalSchema
.
toRowDataType
().
getLogicalType
();
builder
.
setRowConverter
(
dialect
.
getRowConverter
(
rowType
));
builder
.
setRowDataTypeInfo
(
runtimeProviderContext
.
createTypeInformation
(
physicalSchema
.
toRowDataType
()));
return
InputFormatProvider
.
of
(
builder
.
build
());
}
@Override
public
ChangelogMode
getChangelogMode
()
{
return
ChangelogMode
.
insertOnly
();
}
@Override
public
boolean
supportsNestedProjection
()
{
// JDBC doesn't support nested projection
return
false
;
}
@Override
public
void
applyProjection
(
int
[][]
projectedFields
)
{
this
.
physicalSchema
=
TableSchemaUtils
.
projectSchema
(
physicalSchema
,
projectedFields
);
}
@Override
public
DynamicTableSource
copy
()
{
return
new
JdbcDynamicTableSource
(
options
,
readOptions
,
lookupOptions
,
physicalSchema
);
}
@Override
public
String
asSummaryString
()
{
return
"JDBC:"
+
dialectName
;
}
@Override
public
boolean
equals
(
Object
o
)
{
if
(
this
==
o
)
{
return
true
;
}
if
(!(
o
instanceof
JdbcDynamicTableSource
))
{
return
false
;
}
JdbcDynamicTableSource
that
=
(
JdbcDynamicTableSource
)
o
;
return
Objects
.
equals
(
options
,
that
.
options
)
&&
Objects
.
equals
(
readOptions
,
that
.
readOptions
)
&&
Objects
.
equals
(
lookupOptions
,
that
.
lookupOptions
)
&&
Objects
.
equals
(
physicalSchema
,
that
.
physicalSchema
)
&&
Objects
.
equals
(
dialectName
,
that
.
dialectName
)
&&
Objects
.
equals
(
limit
,
that
.
limit
);
}
@Override
public
int
hashCode
()
{
return
Objects
.
hash
(
options
,
readOptions
,
lookupOptions
,
physicalSchema
,
dialectName
,
limit
);
}
@Override
public
void
applyLimit
(
long
limit
)
{
this
.
limit
=
limit
;
}
}
dlink-connectors/dlink-connector-jdbc-1.14/src/main/java/org/apache/flink/connector/jdbc/table/JdbcLookupFunction.java
0 → 100644
View file @
9c315b5c
/*
*
* 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.
*
*/
package
org
.
apache
.
flink
.
connector
.
jdbc
.
table
;
import
static
org
.
apache
.
flink
.
connector
.
jdbc
.
utils
.
JdbcUtils
.
getFieldFromResultSet
;
import
static
org
.
apache
.
flink
.
util
.
Preconditions
.
checkArgument
;
import
static
org
.
apache
.
flink
.
util
.
Preconditions
.
checkNotNull
;
import
org.apache.flink.annotation.VisibleForTesting
;
import
org.apache.flink.api.common.typeinfo.TypeInformation
;
import
org.apache.flink.api.java.typeutils.RowTypeInfo
;
import
org.apache.flink.connector.jdbc.internal.connection.JdbcConnectionProvider
;
import
org.apache.flink.connector.jdbc.internal.connection.SimpleJdbcConnectionProvider
;
import
org.apache.flink.connector.jdbc.internal.options.JdbcConnectorOptions
;
import
org.apache.flink.connector.jdbc.internal.options.JdbcLookupOptions
;
import
org.apache.flink.connector.jdbc.statement.FieldNamedPreparedStatementImpl
;
import
org.apache.flink.connector.jdbc.utils.JdbcTypeUtil
;
import
org.apache.flink.connector.jdbc.utils.JdbcUtils
;
import
org.apache.flink.shaded.guava30.com.google.common.cache.Cache
;
import
org.apache.flink.shaded.guava30.com.google.common.cache.CacheBuilder
;
import
org.apache.flink.table.functions.FunctionContext
;
import
org.apache.flink.table.functions.TableFunction
;
import
org.apache.flink.types.Row
;
import
java.io.IOException
;
import
java.sql.Connection
;
import
java.sql.PreparedStatement
;
import
java.sql.ResultSet
;
import
java.sql.SQLException
;
import
java.util.ArrayList
;
import
java.util.Arrays
;
import
java.util.HashMap
;
import
java.util.List
;
import
java.util.concurrent.TimeUnit
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
/**
* A {@link TableFunction} to query fields from JDBC by keys. The query template like:
*
* <PRE>
* SELECT c, d, e, f from T where a = ? and b = ?
* </PRE>
*
* <p>Support cache the result to avoid frequent accessing to remote databases. 1.The cacheMaxSize
* is -1 means not use cache. 2.For real-time data, you need to set the TTL of cache.
*/
public
class
JdbcLookupFunction
extends
TableFunction
<
Row
>
{
private
static
final
Logger
LOG
=
LoggerFactory
.
getLogger
(
JdbcLookupFunction
.
class
);
private
static
final
long
serialVersionUID
=
2L
;
private
final
String
query
;
private
final
JdbcConnectionProvider
connectionProvider
;
private
final
TypeInformation
[]
keyTypes
;
private
final
int
[]
keySqlTypes
;
private
final
String
[]
fieldNames
;
private
final
String
[]
keyNames
;
private
final
TypeInformation
[]
fieldTypes
;
private
final
int
[]
outputSqlTypes
;
private
final
long
cacheMaxSize
;
private
final
long
cacheExpireMs
;
private
final
int
maxRetryTimes
;
private
transient
PreparedStatement
statement
;
private
transient
Cache
<
Row
,
List
<
Row
>>
cache
;
public
JdbcLookupFunction
(
JdbcConnectorOptions
options
,
JdbcLookupOptions
lookupOptions
,
String
[]
fieldNames
,
TypeInformation
[]
fieldTypes
,
String
[]
keyNames
)
{
this
.
connectionProvider
=
new
SimpleJdbcConnectionProvider
(
options
);
this
.
fieldNames
=
fieldNames
;
this
.
fieldTypes
=
fieldTypes
;
this
.
keyNames
=
keyNames
;
List
<
String
>
nameList
=
Arrays
.
asList
(
fieldNames
);
this
.
keyTypes
=
Arrays
.
stream
(
keyNames
)
.
map
(
s
->
{
checkArgument
(
nameList
.
contains
(
s
),
"keyName %s can't find in fieldNames %s."
,
s
,
nameList
);
return
fieldTypes
[
nameList
.
indexOf
(
s
)];
})
.
toArray
(
TypeInformation
[]::
new
);
this
.
cacheMaxSize
=
lookupOptions
.
getCacheMaxSize
();
this
.
cacheExpireMs
=
lookupOptions
.
getCacheExpireMs
();
this
.
maxRetryTimes
=
lookupOptions
.
getMaxRetryTimes
();
this
.
keySqlTypes
=
Arrays
.
stream
(
keyTypes
).
mapToInt
(
JdbcTypeUtil:
:
typeInformationToSqlType
).
toArray
();
this
.
outputSqlTypes
=
Arrays
.
stream
(
fieldTypes
)
.
mapToInt
(
JdbcTypeUtil:
:
typeInformationToSqlType
)
.
toArray
();
String
[]
preFilterCondition
=
lookupOptions
.
getPreFilterCondition
();
String
[]
finalKeyNames
=
new
String
[
keyNames
.
length
+
preFilterCondition
.
length
];
System
.
arraycopy
(
keyNames
,
0
,
finalKeyNames
,
0
,
keyNames
.
length
);
System
.
arraycopy
(
preFilterCondition
,
0
,
finalKeyNames
,
keyNames
.
length
,
preFilterCondition
.
length
);
this
.
query
=
FieldNamedPreparedStatementImpl
.
parseNamedStatement
(
options
.
getDialect
()
.
getSelectFromStatement
(
options
.
getTableName
(),
fieldNames
,
finalKeyNames
),
new
HashMap
<>());
}
public
static
Builder
builder
()
{
return
new
Builder
();
}
@Override
public
void
open
(
FunctionContext
context
)
throws
Exception
{
try
{
establishConnectionAndStatement
();
this
.
cache
=
cacheMaxSize
==
-
1
||
cacheExpireMs
==
-
1
?
null
:
CacheBuilder
.
newBuilder
()
.
expireAfterWrite
(
cacheExpireMs
,
TimeUnit
.
MILLISECONDS
)
.
maximumSize
(
cacheMaxSize
)
.
build
();
}
catch
(
SQLException
sqe
)
{
throw
new
IllegalArgumentException
(
"open() failed."
,
sqe
);
}
catch
(
ClassNotFoundException
cnfe
)
{
throw
new
IllegalArgumentException
(
"JDBC driver class not found."
,
cnfe
);
}
}
public
void
eval
(
Object
...
keys
)
{
Row
keyRow
=
Row
.
of
(
keys
);
if
(
cache
!=
null
)
{
List
<
Row
>
cachedRows
=
cache
.
getIfPresent
(
keyRow
);
if
(
cachedRows
!=
null
)
{
for
(
Row
cachedRow
:
cachedRows
)
{
collect
(
cachedRow
);
}
return
;
}
}
for
(
int
retry
=
0
;
retry
<=
maxRetryTimes
;
retry
++)
{
try
{
statement
.
clearParameters
();
for
(
int
i
=
0
;
i
<
keys
.
length
;
i
++)
{
JdbcUtils
.
setField
(
statement
,
keySqlTypes
[
i
],
keys
[
i
],
i
);
}
try
(
ResultSet
resultSet
=
statement
.
executeQuery
())
{
if
(
cache
==
null
)
{
while
(
resultSet
.
next
())
{
collect
(
convertToRowFromResultSet
(
resultSet
));
}
}
else
{
ArrayList
<
Row
>
rows
=
new
ArrayList
<>();
while
(
resultSet
.
next
())
{
Row
row
=
convertToRowFromResultSet
(
resultSet
);
rows
.
add
(
row
);
collect
(
row
);
}
rows
.
trimToSize
();
cache
.
put
(
keyRow
,
rows
);
}
}
break
;
}
catch
(
SQLException
e
)
{
LOG
.
error
(
String
.
format
(
"JDBC executeBatch error, retry times = %d"
,
retry
),
e
);
if
(
retry
>=
maxRetryTimes
)
{
throw
new
RuntimeException
(
"Execution of JDBC statement failed."
,
e
);
}
try
{
if
(!
connectionProvider
.
isConnectionValid
())
{
statement
.
close
();
connectionProvider
.
closeConnection
();
establishConnectionAndStatement
();
}
}
catch
(
SQLException
|
ClassNotFoundException
excpetion
)
{
LOG
.
error
(
"JDBC connection is not valid, and reestablish connection failed"
,
excpetion
);
throw
new
RuntimeException
(
"Reestablish JDBC connection failed"
,
excpetion
);
}
try
{
Thread
.
sleep
(
1000
*
retry
);
}
catch
(
InterruptedException
e1
)
{
throw
new
RuntimeException
(
e1
);
}
}
}
}
private
Row
convertToRowFromResultSet
(
ResultSet
resultSet
)
throws
SQLException
{
Row
row
=
new
Row
(
outputSqlTypes
.
length
);
for
(
int
i
=
0
;
i
<
outputSqlTypes
.
length
;
i
++)
{
row
.
setField
(
i
,
getFieldFromResultSet
(
i
,
outputSqlTypes
[
i
],
resultSet
));
}
return
row
;
}
private
void
establishConnectionAndStatement
()
throws
SQLException
,
ClassNotFoundException
{
Connection
dbConn
=
connectionProvider
.
getOrEstablishConnection
();
statement
=
dbConn
.
prepareStatement
(
query
);
}
@Override
public
void
close
()
throws
IOException
{
if
(
cache
!=
null
)
{
cache
.
cleanUp
();
cache
=
null
;
}
if
(
statement
!=
null
)
{
try
{
statement
.
close
();
}
catch
(
SQLException
e
)
{
LOG
.
info
(
"JDBC statement could not be closed: "
+
e
.
getMessage
());
}
finally
{
statement
=
null
;
}
}
connectionProvider
.
closeConnection
();
}
@VisibleForTesting
public
Connection
getDbConnection
()
{
return
connectionProvider
.
getConnection
();
}
@Override
public
TypeInformation
<
Row
>
getResultType
()
{
return
new
RowTypeInfo
(
fieldTypes
,
fieldNames
);
}
@Override
public
TypeInformation
<?>[]
getParameterTypes
(
Class
<?>[]
signature
)
{
return
keyTypes
;
}
/** Builder for a {@link JdbcLookupFunction}. */
public
static
class
Builder
{
private
JdbcConnectorOptions
options
;
private
JdbcLookupOptions
lookupOptions
;
protected
String
[]
fieldNames
;
protected
TypeInformation
[]
fieldTypes
;
protected
String
[]
keyNames
;
/** required, jdbc options. */
public
Builder
setOptions
(
JdbcConnectorOptions
options
)
{
this
.
options
=
options
;
return
this
;
}
/** optional, lookup related options. */
public
Builder
setLookupOptions
(
JdbcLookupOptions
lookupOptions
)
{
this
.
lookupOptions
=
lookupOptions
;
return
this
;
}
/** required, field names of this jdbc table. */
public
Builder
setFieldNames
(
String
[]
fieldNames
)
{
this
.
fieldNames
=
fieldNames
;
return
this
;
}
/** required, field types of this jdbc table. */
public
Builder
setFieldTypes
(
TypeInformation
[]
fieldTypes
)
{
this
.
fieldTypes
=
fieldTypes
;
return
this
;
}
/** required, key names to query this jdbc table. */
public
Builder
setKeyNames
(
String
[]
keyNames
)
{
this
.
keyNames
=
keyNames
;
return
this
;
}
/**
* Finalizes the configuration and checks validity.
*
* @return Configured JdbcLookupFunction
*/
public
JdbcLookupFunction
build
()
{
checkNotNull
(
options
,
"No JdbcOptions supplied."
);
if
(
lookupOptions
==
null
)
{
lookupOptions
=
JdbcLookupOptions
.
builder
().
build
();
}
checkNotNull
(
fieldNames
,
"No fieldNames supplied."
);
checkNotNull
(
fieldTypes
,
"No fieldTypes supplied."
);
checkNotNull
(
keyNames
,
"No keyNames supplied."
);
return
new
JdbcLookupFunction
(
options
,
lookupOptions
,
fieldNames
,
fieldTypes
,
keyNames
);
}
}
}
dlink-connectors/dlink-connector-jdbc-1.14/src/main/java/org/apache/flink/connector/jdbc/table/JdbcRowDataLookupFunction.java
0 → 100644
View file @
9c315b5c
/*
*
* 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.
*
*/
package
org
.
apache
.
flink
.
connector
.
jdbc
.
table
;
import
static
org
.
apache
.
flink
.
util
.
Preconditions
.
checkArgument
;
import
static
org
.
apache
.
flink
.
util
.
Preconditions
.
checkNotNull
;
import
org.apache.flink.annotation.Internal
;
import
org.apache.flink.annotation.VisibleForTesting
;
import
org.apache.flink.connector.jdbc.dialect.JdbcDialect
;
import
org.apache.flink.connector.jdbc.dialect.JdbcDialects
;
import
org.apache.flink.connector.jdbc.internal.connection.JdbcConnectionProvider
;
import
org.apache.flink.connector.jdbc.internal.connection.SimpleJdbcConnectionProvider
;
import
org.apache.flink.connector.jdbc.internal.converter.JdbcRowConverter
;
import
org.apache.flink.connector.jdbc.internal.options.JdbcConnectorOptions
;
import
org.apache.flink.connector.jdbc.internal.options.JdbcLookupOptions
;
import
org.apache.flink.connector.jdbc.statement.FieldNamedPreparedStatement
;
import
org.apache.flink.shaded.guava30.com.google.common.cache.Cache
;
import
org.apache.flink.shaded.guava30.com.google.common.cache.CacheBuilder
;
import
org.apache.flink.table.data.GenericRowData
;
import
org.apache.flink.table.data.RowData
;
import
org.apache.flink.table.functions.FunctionContext
;
import
org.apache.flink.table.functions.TableFunction
;
import
org.apache.flink.table.types.DataType
;
import
org.apache.flink.table.types.logical.LogicalType
;
import
org.apache.flink.table.types.logical.RowType
;
import
java.io.IOException
;
import
java.sql.Connection
;
import
java.sql.ResultSet
;
import
java.sql.SQLException
;
import
java.util.ArrayList
;
import
java.util.Arrays
;
import
java.util.List
;
import
java.util.concurrent.TimeUnit
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
/** A lookup function for {@link JdbcDynamicTableSource}. */
@Internal
public
class
JdbcRowDataLookupFunction
extends
TableFunction
<
RowData
>
{
private
static
final
Logger
LOG
=
LoggerFactory
.
getLogger
(
JdbcRowDataLookupFunction
.
class
);
private
static
final
long
serialVersionUID
=
2L
;
private
final
String
query
;
private
final
JdbcConnectionProvider
connectionProvider
;
private
final
DataType
[]
keyTypes
;
private
final
String
[]
keyNames
;
private
final
long
cacheMaxSize
;
private
final
long
cacheExpireMs
;
private
final
int
maxRetryTimes
;
private
final
JdbcDialect
jdbcDialect
;
private
final
JdbcRowConverter
jdbcRowConverter
;
private
final
JdbcRowConverter
lookupKeyRowConverter
;
private
transient
FieldNamedPreparedStatement
statement
;
private
transient
Cache
<
RowData
,
List
<
RowData
>>
cache
;
public
JdbcRowDataLookupFunction
(
JdbcConnectorOptions
options
,
JdbcLookupOptions
lookupOptions
,
String
[]
fieldNames
,
DataType
[]
fieldTypes
,
String
[]
keyNames
,
RowType
rowType
)
{
checkNotNull
(
options
,
"No JdbcOptions supplied."
);
checkNotNull
(
fieldNames
,
"No fieldNames supplied."
);
checkNotNull
(
fieldTypes
,
"No fieldTypes supplied."
);
checkNotNull
(
keyNames
,
"No keyNames supplied."
);
this
.
connectionProvider
=
new
SimpleJdbcConnectionProvider
(
options
);
this
.
keyNames
=
keyNames
;
List
<
String
>
nameList
=
Arrays
.
asList
(
fieldNames
);
this
.
keyTypes
=
Arrays
.
stream
(
keyNames
)
.
map
(
s
->
{
checkArgument
(
nameList
.
contains
(
s
),
"keyName %s can't find in fieldNames %s."
,
s
,
nameList
);
return
fieldTypes
[
nameList
.
indexOf
(
s
)];
})
.
toArray
(
DataType
[]::
new
);
this
.
cacheMaxSize
=
lookupOptions
.
getCacheMaxSize
();
this
.
cacheExpireMs
=
lookupOptions
.
getCacheExpireMs
();
this
.
maxRetryTimes
=
lookupOptions
.
getMaxRetryTimes
();
String
[]
preFilterCondition
=
lookupOptions
.
getPreFilterCondition
();
String
[]
finalKeyNames
=
new
String
[
keyNames
.
length
+
preFilterCondition
.
length
];
System
.
arraycopy
(
keyNames
,
0
,
finalKeyNames
,
0
,
keyNames
.
length
);
System
.
arraycopy
(
preFilterCondition
,
0
,
finalKeyNames
,
keyNames
.
length
,
preFilterCondition
.
length
);
this
.
query
=
options
.
getDialect
()
.
getSelectFromStatement
(
options
.
getTableName
(),
fieldNames
,
finalKeyNames
);
String
dbURL
=
options
.
getDbURL
();
this
.
jdbcDialect
=
JdbcDialects
.
get
(
dbURL
)
.
orElseThrow
(
()
->
new
UnsupportedOperationException
(
String
.
format
(
"Unknown dbUrl:%s"
,
dbURL
)));
this
.
jdbcRowConverter
=
jdbcDialect
.
getRowConverter
(
rowType
);
this
.
lookupKeyRowConverter
=
jdbcDialect
.
getRowConverter
(
RowType
.
of
(
Arrays
.
stream
(
keyTypes
)
.
map
(
DataType:
:
getLogicalType
)
.
toArray
(
LogicalType
[]::
new
)));
}
@Override
public
void
open
(
FunctionContext
context
)
throws
Exception
{
try
{
establishConnectionAndStatement
();
this
.
cache
=
cacheMaxSize
==
-
1
||
cacheExpireMs
==
-
1
?
null
:
CacheBuilder
.
newBuilder
()
.
expireAfterWrite
(
cacheExpireMs
,
TimeUnit
.
MILLISECONDS
)
.
maximumSize
(
cacheMaxSize
)
.
build
();
}
catch
(
SQLException
sqe
)
{
throw
new
IllegalArgumentException
(
"open() failed."
,
sqe
);
}
catch
(
ClassNotFoundException
cnfe
)
{
throw
new
IllegalArgumentException
(
"JDBC driver class not found."
,
cnfe
);
}
}
/**
* This is a lookup method which is called by Flink framework in runtime.
*
* @param keys lookup keys
*/
public
void
eval
(
Object
...
keys
)
{
RowData
keyRow
=
GenericRowData
.
of
(
keys
);
if
(
cache
!=
null
)
{
List
<
RowData
>
cachedRows
=
cache
.
getIfPresent
(
keyRow
);
if
(
cachedRows
!=
null
)
{
for
(
RowData
cachedRow
:
cachedRows
)
{
collect
(
cachedRow
);
}
return
;
}
}
for
(
int
retry
=
0
;
retry
<=
maxRetryTimes
;
retry
++)
{
try
{
statement
.
clearParameters
();
statement
=
lookupKeyRowConverter
.
toExternal
(
keyRow
,
statement
);
try
(
ResultSet
resultSet
=
statement
.
executeQuery
())
{
if
(
cache
==
null
)
{
while
(
resultSet
.
next
())
{
collect
(
jdbcRowConverter
.
toInternal
(
resultSet
));
}
}
else
{
ArrayList
<
RowData
>
rows
=
new
ArrayList
<>();
while
(
resultSet
.
next
())
{
RowData
row
=
jdbcRowConverter
.
toInternal
(
resultSet
);
rows
.
add
(
row
);
collect
(
row
);
}
rows
.
trimToSize
();
cache
.
put
(
keyRow
,
rows
);
}
}
break
;
}
catch
(
SQLException
e
)
{
LOG
.
error
(
String
.
format
(
"JDBC executeBatch error, retry times = %d"
,
retry
),
e
);
if
(
retry
>=
maxRetryTimes
)
{
throw
new
RuntimeException
(
"Execution of JDBC statement failed."
,
e
);
}
try
{
if
(!
connectionProvider
.
isConnectionValid
())
{
statement
.
close
();
connectionProvider
.
closeConnection
();
establishConnectionAndStatement
();
}
}
catch
(
SQLException
|
ClassNotFoundException
exception
)
{
LOG
.
error
(
"JDBC connection is not valid, and reestablish connection failed"
,
exception
);
throw
new
RuntimeException
(
"Reestablish JDBC connection failed"
,
exception
);
}
try
{
Thread
.
sleep
(
1000
*
retry
);
}
catch
(
InterruptedException
e1
)
{
throw
new
RuntimeException
(
e1
);
}
}
}
}
private
void
establishConnectionAndStatement
()
throws
SQLException
,
ClassNotFoundException
{
Connection
dbConn
=
connectionProvider
.
getOrEstablishConnection
();
statement
=
FieldNamedPreparedStatement
.
prepareStatement
(
dbConn
,
query
,
keyNames
);
}
@Override
public
void
close
()
throws
IOException
{
if
(
cache
!=
null
)
{
cache
.
cleanUp
();
cache
=
null
;
}
if
(
statement
!=
null
)
{
try
{
statement
.
close
();
}
catch
(
SQLException
e
)
{
LOG
.
info
(
"JDBC statement could not be closed: "
+
e
.
getMessage
());
}
finally
{
statement
=
null
;
}
}
connectionProvider
.
closeConnection
();
}
@VisibleForTesting
public
Connection
getDbConnection
()
{
return
connectionProvider
.
getConnection
();
}
}
style/checkstyle.xml
View file @
9c315b5c
...
...
@@ -190,7 +190,7 @@
<property
name=
"caseIndent"
value=
"4"
/>
<property
name=
"throwsIndent"
value=
"2"
/>
<property
name=
"lineWrappingIndentation"
value=
"4"
/>
<property
name=
"arrayInitIndent"
value=
"
4
"
/>
<property
name=
"arrayInitIndent"
value=
"
8
"
/>
</module>
<module
name=
"IllegalImport"
>
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment