id
int64
0
10.2k
text_id
stringlengths
17
67
repo_owner
stringclasses
232 values
repo_name
stringclasses
295 values
issue_url
stringlengths
39
89
pull_url
stringlengths
37
87
comment_url
stringlengths
37
94
links_count
int64
1
2
link_keyword
stringclasses
12 values
issue_title
stringlengths
7
197
issue_body
stringlengths
45
21.3k
base_sha
stringlengths
40
40
head_sha
stringlengths
40
40
diff_url
stringlengths
120
170
diff
stringlengths
478
132k
changed_files
stringlengths
47
2.6k
changed_files_exts
stringclasses
22 values
changed_files_count
int64
1
22
java_changed_files_count
int64
1
22
kt_changed_files_count
int64
0
0
py_changed_files_count
int64
0
0
code_changed_files_count
int64
1
22
repo_symbols_count
int64
32.6k
242M
repo_tokens_count
int64
6.59k
49.2M
repo_lines_count
int64
992
6.2M
repo_files_without_tests_count
int64
12
28.1k
changed_symbols_count
int64
0
36.1k
changed_tokens_count
int64
0
6.5k
changed_lines_count
int64
0
561
changed_files_without_tests_count
int64
1
17
issue_symbols_count
int64
45
21.3k
issue_words_count
int64
2
1.39k
issue_tokens_count
int64
13
4.47k
issue_lines_count
int64
1
325
issue_links_count
int64
0
19
issue_code_blocks_count
int64
0
31
pull_create_at
timestamp[s]
repo_stars
int64
10
44.3k
repo_language
stringclasses
8 values
repo_languages
stringclasses
296 values
repo_license
stringclasses
2 values
3,498
apache/shardingsphere/1944/1933
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1933
https://github.com/apache/shardingsphere/pull/1944
https://github.com/apache/shardingsphere/pull/1944
1
fixes
oracle getAllTableNames returns oracle build-in table
xml config: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:sharding="http://shardingsphere.io/schema/shardingsphere/sharding" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://shardingsphere.io/schema/shardingsphere/sharding http://shardingsphere.io/schema/shardingsphere/sharding/sharding.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <bean name="dataSource_0" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url_0}"/> <property name="username" value="${jdbc.username_0}"/> <property name="password" value="${jdbc.password_0}"/> <property name="driverClassName" value="${jdbc.driverClassName}" /> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="${jdbc.initialSize}"/> <property name="minIdle" value="${jdbc.minIdle}"/> <property name="maxActive" value="${jdbc.maxActive}"/> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="${jdbc.maxWait}"/> </bean> <bean name="dataSource_1" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url_1}"/> <property name="username" value="${jdbc.username_1}"/> <property name="password" value="${jdbc.password_1}"/> <property name="driverClassName" value="${jdbc.driverClassName}" /> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="${jdbc.initialSize}"/> <property name="minIdle" value="${jdbc.minIdle}"/> <property name="maxActive" value="${jdbc.maxActive}"/> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="${jdbc.maxWait}"/> </bean> <bean name="globalDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="driverClassName" value="${jdbc.driverClassName}" /> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="${jdbc.initialSize}"/> <property name="minIdle" value="${jdbc.minIdle}"/> <property name="maxActive" value="${jdbc.maxActive}"/> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="${jdbc.maxWait}"/> </bean> <bean id="preciseModuloDatabaseShardingAlgorithm" class="com.hundsun.ta.aop.DemoTableShardingAlgorithm" /> <bean id="preciseModuloTableShardingAlgorithm" class="com.hundsun.ta.aop.DemoDatabaseShardingAlgorithm" /> <!-- 分库策略 --> <sharding:standard-strategy id="databaseStrategy" sharding-column="user_id" precise-algorithm-ref="preciseModuloDatabaseShardingAlgorithm" /> <!-- 分表策略 --> <sharding:standard-strategy id="tableStrategy" sharding-column="user_id" precise-algorithm-ref="preciseModuloTableShardingAlgorithm" /> <sharding:data-source id="shardingDataSource"> <!-- configDataSource为不参数分库分表的全局表的默认数据源,比如系统参数 --> <sharding:sharding-rule data-source-names="dataSource_0,dataSource_1,globalDataSource" default-data-source-name="globalDataSource" default-database-strategy-ref="databaseStrategy" default-table-strategy-ref="tableStrategy"> <sharding:table-rules> <sharding:table-rule logic-table="t_order" actual-data-nodes="dataSource_$->{0..1}.t_order_$->{0..1}" /> <sharding:table-rule logic-table="t_order_item" actual-data-nodes="dataSource_$->{0..1}.t_order_item_$->{0..1}" /> <sharding:table-rule logic-table="t_user" actual-data-nodes="dataSource_$->{0..1}.t_user"/> </sharding:table-rules> <!-- 绑定表规则列表,表示分库分表的规则相同,这样万一涉及到多个分片的查询,sharding-jdbc就可以确定分库之间不需要不必要的二次关联,所有涉及表都应该如此维护 --> <sharding:binding-table-rules> <sharding:binding-table-rule logic-tables="t_order,t_order_item"/> </sharding:binding-table-rules> <sharding:broadcast-table-rules> <sharding:broadcast-table-rule table="t_dict" /> </sharding:broadcast-table-rules> </sharding:sharding-rule> </sharding:data-source> </beans> method io.shardingsphere.core.metadata.table.executor.TableMetaDataInitializer#getAllTableNames returns more table then current schema's table. ex. it returns table like SYS_IOT_OVER_84700。 version:sharding-sphere 3.1.0. the reason is getAllTableNames() method call getTables() pass null to schemaPattern in line 98. as follows: ResultSet resultSet = connection.getMetaData().getTables(catalog, null, null, new String[]{"TABLE"})) the result is app suspend after datasource init. the jstack is as follows: "main" #1 prio=5 os_prio=0 tid=0x00000000055ad800 nid=0x154c runnable [0x000000000559c000] java.lang.Thread.State: RUNNABLE at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.socketRead(SocketInputStream.java:116) at java.net.SocketInputStream.read(SocketInputStream.java:171) at java.net.SocketInputStream.read(SocketInputStream.java:141) at oracle.net.ns.Packet.receive(Packet.java:300) at oracle.net.ns.DataPacket.receive(DataPacket.java:106) at oracle.net.ns.NetInputStream.getNextPacket(NetInputStream.java:315) at oracle.net.ns.NetInputStream.read(NetInputStream.java:260) at oracle.net.ns.NetInputStream.read(NetInputStream.java:185) at oracle.net.ns.NetInputStream.read(NetInputStream.java:102) at oracle.jdbc.driver.T4CSocketInputStreamWrapper.readNextPacket(T4CSocketInputStreamWrapper.java:124) at oracle.jdbc.driver.T4CSocketInputStreamWrapper.read(T4CSocketInputStreamWrapper.java:80) at oracle.jdbc.driver.T4CMAREngine.unmarshalUB1(T4CMAREngine.java:1137) at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:290) at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:192) at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531) at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207) at oracle.jdbc.driver.T4CPreparedStatement.fetch(T4CPreparedStatement.java:1119) at oracle.jdbc.driver.OracleResultSetImpl.close_or_fetch_from_next(OracleResultSetImpl.java:373) - locked <0x0000000780aac2a0> (a oracle.jdbc.driver.T4CConnection) at oracle.jdbc.driver.OracleResultSetImpl.next(OracleResultSetImpl.java:277) - locked <0x0000000780aac2a0> (a oracle.jdbc.driver.T4CConnection) at io.shardingsphere.core.metadata.table.executor.TableMetaDataLoader.getColumnMetaDataList(TableMetaDataLoader.java:137) at io.shardingsphere.core.metadata.table.executor.TableMetaDataLoader.load(TableMetaDataLoader.java:96) at io.shardingsphere.core.metadata.table.executor.TableMetaDataLoader.access$100(TableMetaDataLoader.java:52) at io.shardingsphere.core.metadata.table.executor.TableMetaDataLoader$1.execute(TableMetaDataLoader.java:86) at io.shardingsphere.core.executor.ShardingExecuteEngine.syncGroupExecute(ShardingExecuteEngine.java:175) at io.shardingsphere.core.executor.ShardingExecuteEngine.groupExecute(ShardingExecuteEngine.java:152) at io.shardingsphere.core.executor.ShardingExecuteEngine.groupExecute(ShardingExecuteEngine.java:130) ### Expected behavior return only tables in current schema. ### Actual behavior return tables in other schema. all table with access privilege. ### how to resolve pass schemaName to getTables method in line 98, as follows: ResultSet resultSet = connection.getMetaData().getTables(catalog, dataSourceMetaData.getSchemeName(), null, new String[]{"TABLE"})) {
5fd9c9df9f2c8c249d018368ca3d940084411397
1bbe50547876766f5d2181149726a315c58aa73c
https://github.com/apache/shardingsphere/compare/5fd9c9df9f2c8c249d018368ca3d940084411397...1bbe50547876766f5d2181149726a315c58aa73c
diff --git a/sharding-core/src/main/java/org/apache/shardingsphere/core/metadata/table/executor/TableMetaDataInitializer.java b/sharding-core/src/main/java/org/apache/shardingsphere/core/metadata/table/executor/TableMetaDataInitializer.java index 2d594b99cfe..80f74f331f3 100644 --- a/sharding-core/src/main/java/org/apache/shardingsphere/core/metadata/table/executor/TableMetaDataInitializer.java +++ b/sharding-core/src/main/java/org/apache/shardingsphere/core/metadata/table/executor/TableMetaDataInitializer.java @@ -92,7 +92,7 @@ public final class TableMetaDataInitializer { DataSourceMetaData dataSourceMetaData = shardingDataSourceMetaData.getActualDataSourceMetaData(dataSourceName); String catalog = null == dataSourceMetaData ? null : dataSourceMetaData.getSchemaName(); try (Connection connection = connectionManager.getConnection(dataSourceName); - ResultSet resultSet = connection.getMetaData().getTables(catalog, null, null, new String[]{"TABLE"})) { + ResultSet resultSet = connection.getMetaData().getTables(catalog, connection.getSchema(), null, new String[]{"TABLE"})) { while (resultSet.next()) { String tableName = resultSet.getString("TABLE_NAME"); if (!tableName.contains("$") && !tableName.contains("/")) {
['sharding-core/src/main/java/org/apache/shardingsphere/core/metadata/table/executor/TableMetaDataInitializer.java']
{'.java': 1}
1
1
0
0
1
2,927,344
594,192
74,785
997
253
50
2
1
8,668
367
2,112
131
14
0
1970-01-01T00:25:51
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,534
apache/shardingsphere/963/962
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/962
https://github.com/apache/shardingsphere/pull/963
https://github.com/apache/shardingsphere/pull/963
1
fixes
Column types disordered when use prepared statement in Proxy
Please answer these questions before submitting your issue. Thanks! 开源不易,我们希望将精力放在完成新功能和解决有价值的问题上,为了让大家的配合更具有效率,请填写以下列出的全部问题 ### Which version of Sharding-Sphere do you using?(您使用的Sharding-Sphere版本为?) dev ### Expected behavior (您预期的结果是) correct prepared statement result ### Actual behavior (实际运行的结果是) a chance to triger wrong result ### Steps to reproduce the behavior (可重现问题的操作步骤) use prepared statement in Proxy ### Please provide the reproduce example codes (such as github link),otherwise we will label the issue as Invalid and close it.(为了节省复现问题的时间,请务必提供可重现的代码,否则我们会将issue直接标记为invalid并关闭) example Code should based on https://github.com/sharding-sphere/sharding-sphere-example (代码请基于 https://github.com/sharding-sphere/sharding-sphere-example)
e8e429ceda2f677e83b7a1f45a8389c0e67126fc
8b6f08696ec9fad30b47fbf3e780e4659173d5e3
https://github.com/apache/shardingsphere/compare/e8e429ceda2f677e83b7a1f45a8389c0e67126fc...8b6f08696ec9fad30b47fbf3e780e4659173d5e3
diff --git a/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/StatementExecuteBackendHandler.java b/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/StatementExecuteBackendHandler.java index e1468ce99a7..793a37e100a 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/StatementExecuteBackendHandler.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/StatementExecuteBackendHandler.java @@ -84,7 +84,7 @@ public final class StatementExecuteBackendHandler implements BackendHandler { private int columnCount; - private final List<ColumnType> columnTypes; + private List<ColumnType> columnTypes; private boolean isMerged; @@ -101,7 +101,6 @@ public final class StatementExecuteBackendHandler implements BackendHandler { connections = new CopyOnWriteArrayList<>(); resultSets = new CopyOnWriteArrayList<>(); resultLists = new CopyOnWriteArrayList<>(); - columnTypes = new CopyOnWriteArrayList<>(); isMerged = false; hasMoreResultValueFlag = true; this.databaseType = databaseType; diff --git a/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/StatementExecuteWorker.java b/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/StatementExecuteWorker.java index ad949d28e2e..c2f2dc1b53f 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/StatementExecuteWorker.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/StatementExecuteWorker.java @@ -190,13 +190,15 @@ public final class StatementExecuteWorker implements Callable<CommandResponsePac return result; } result.addPacket(new FieldCountPacket(++currentSequenceId, columnCount)); + List<ColumnType> columnTypes = new ArrayList<>(128); for (int i = 1; i <= columnCount; i++) { ColumnType columnType = ColumnType.valueOfJDBCType(resultSetMetaData.getColumnType(i)); ColumnDefinition41Packet columnDefinition41Packet = new ColumnDefinition41Packet(++currentSequenceId, resultSetMetaData.getSchemaName(i), resultSetMetaData.getTableName(i), resultSetMetaData.getTableName(i), resultSetMetaData.getColumnLabel(i), resultSetMetaData.getColumnName(i), resultSetMetaData.getColumnDisplaySize(i), columnType, 0); result.addPacket(columnDefinition41Packet); - statementExecuteBackendHandler.getColumnTypes().add(columnType); + columnTypes.add(columnType); } + statementExecuteBackendHandler.setColumnTypes(columnTypes); result.addPacket(new EofPacket(++currentSequenceId, 0, StatusFlag.SERVER_STATUS_AUTOCOMMIT.getValue())); return result; } @@ -211,20 +213,22 @@ public final class StatementExecuteWorker implements Callable<CommandResponsePac return result; } result.addPacket(new FieldCountPacket(++currentSequenceId, columnCount)); + List<ColumnType> columnTypes = new ArrayList<>(128); for (int i = 1; i <= columnCount; i++) { ColumnType columnType = ColumnType.valueOfJDBCType(resultSetMetaData.getColumnType(i)); ColumnDefinition41Packet columnDefinition41Packet = new ColumnDefinition41Packet(++currentSequenceId, resultSetMetaData.getSchemaName(i), resultSetMetaData.getTableName(i), resultSetMetaData.getTableName(i), resultSetMetaData.getColumnLabel(i), resultSetMetaData.getColumnName(i), resultSetMetaData.getColumnDisplaySize(i), columnType, 0); result.addPacket(columnDefinition41Packet); - statementExecuteBackendHandler.getColumnTypes().add(columnType); + columnTypes.add(columnType); } + statementExecuteBackendHandler.setColumnTypes(columnTypes); result.addPacket(new EofPacket(++currentSequenceId, 0, StatusFlag.SERVER_STATUS_AUTOCOMMIT.getValue())); while (resultSet.next()) { List<Object> data = new ArrayList<>(columnCount); for (int i = 1; i <= columnCount; i++) { data.add(resultSet.getObject(i)); } - result.addPacket(new BinaryResultSetRowPacket(++currentSequenceId, columnCount, data, statementExecuteBackendHandler.getColumnTypes())); + result.addPacket(new BinaryResultSetRowPacket(++currentSequenceId, columnCount, data, columnTypes)); } result.addPacket(new EofPacket(++currentSequenceId, 0, StatusFlag.SERVER_STATUS_AUTOCOMMIT.getValue())); return result;
['sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/StatementExecuteWorker.java', 'sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/StatementExecuteBackendHandler.java']
{'.java': 2}
2
2
0
0
2
2,047,200
425,775
57,656
707
909
161
13
2
776
78
251
21
2
0
1970-01-01T00:25:29
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,520
apache/shardingsphere/1309/1307
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1307
https://github.com/apache/shardingsphere/pull/1309
https://github.com/apache/shardingsphere/pull/1309
1
fixes
Sql-Server exception : The URL of JDBC is not supported.
spring-boot 1.5.6.RELEASE sharding-3.0.0.M3 sqlServer 2012 sqljdbc4 4.0 when I use sharding-3.0.0.M1,everything works fine my configuration is like this sharding.jdbc.datasource.ds_0.url=jdbc:sqlserver://dev.database.chinacloudapi.cn;database=sharding;loginTimeout=30;sendStringParametersAsUnicode=false but when I upgrade to M3, the connection fails. report this error : The URL of JDBC is not supported.
a502022308d0bc9258c8dc0e27d28565ccc7574b
78721892d6c5431317bd6f8fb1794d8bc1477bb7
https://github.com/apache/shardingsphere/compare/a502022308d0bc9258c8dc0e27d28565ccc7574b...78721892d6c5431317bd6f8fb1794d8bc1477bb7
diff --git a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/H2DataSourceMetaData.java b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/H2DataSourceMetaData.java index 38487251c2d..c3f0b37ad60 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/H2DataSourceMetaData.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/H2DataSourceMetaData.java @@ -40,7 +40,7 @@ public final class H2DataSourceMetaData implements DataSourceMetaData { private final String schemeName; - private final Pattern pattern = Pattern.compile("jdbc:h2:(mem|~)[:/]([\\\\w\\\\-]+);?\\\\w*"); + private final Pattern pattern = Pattern.compile("jdbc:h2:(mem|~)[:/]([\\\\w\\\\-]+);?\\\\w*", Pattern.CASE_INSENSITIVE); public H2DataSourceMetaData(final String url) { Matcher matcher = pattern.matcher(url); @@ -49,7 +49,7 @@ public final class H2DataSourceMetaData implements DataSourceMetaData { port = DEFAULT_PORT; schemeName = matcher.group(2); } else { - throw new ShardingException("The URL of JDBC is not supported."); + throw new ShardingException("The URL of JDBC is not supported. Please refer to this pattern: %s.", pattern.pattern()); } } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/MySQLDataSourceMetaData.java b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/MySQLDataSourceMetaData.java index 6f307335735..b8b0a121fb8 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/MySQLDataSourceMetaData.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/MySQLDataSourceMetaData.java @@ -41,7 +41,7 @@ public final class MySQLDataSourceMetaData implements DataSourceMetaData { private final String schemeName; - private final Pattern pattern = Pattern.compile("jdbc:mysql://([\\\\w\\\\-\\\\.]+):?([0-9]*)/([\\\\w\\\\-]+);?\\\\w*"); + private final Pattern pattern = Pattern.compile("jdbc:mysql://([\\\\w\\\\-\\\\.]+):?([0-9]*)/([\\\\w\\\\-]+);?\\\\w*", Pattern.CASE_INSENSITIVE); public MySQLDataSourceMetaData(final String url) { Matcher matcher = pattern.matcher(url); @@ -50,7 +50,7 @@ public final class MySQLDataSourceMetaData implements DataSourceMetaData { port = Strings.isNullOrEmpty(matcher.group(2)) ? DEFAULT_PORT : Integer.valueOf(matcher.group(2)); schemeName = matcher.group(3); } else { - throw new ShardingException("The URL of JDBC is not supported."); + throw new ShardingException("The URL of JDBC is not supported. Please refer to this pattern: %s.", pattern.pattern()); } } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/OracleDataSourceMetaData.java b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/OracleDataSourceMetaData.java index 544c79c3601..9cbaf1518ad 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/OracleDataSourceMetaData.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/OracleDataSourceMetaData.java @@ -41,7 +41,7 @@ public final class OracleDataSourceMetaData implements DataSourceMetaData { private final String schemeName; - private final Pattern pattern = Pattern.compile("jdbc:oracle:thin:@/{0,2}([\\\\w\\\\-\\\\.]+):?([0-9]*)[:/]([\\\\w\\\\-]+)"); + private final Pattern pattern = Pattern.compile("jdbc:oracle:thin:@/{0,2}([\\\\w\\\\-\\\\.]+):?([0-9]*)[:/]([\\\\w\\\\-]+)", Pattern.CASE_INSENSITIVE); public OracleDataSourceMetaData(final String url) { Matcher matcher = pattern.matcher(url); @@ -50,7 +50,7 @@ public final class OracleDataSourceMetaData implements DataSourceMetaData { port = Strings.isNullOrEmpty(matcher.group(2)) ? DEFAULT_PORT : Integer.valueOf(matcher.group(2)); schemeName = matcher.group(3); } else { - throw new ShardingException("The URL of JDBC is not supported."); + throw new ShardingException("The URL of JDBC is not supported. Please refer to this pattern: %s.", pattern.pattern()); } } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/PostgreSQLDataSourceMetaData.java b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/PostgreSQLDataSourceMetaData.java index 066897eeecc..8dd813f99fc 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/PostgreSQLDataSourceMetaData.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/PostgreSQLDataSourceMetaData.java @@ -41,7 +41,7 @@ public final class PostgreSQLDataSourceMetaData implements DataSourceMetaData { private final String schemeName; - private final Pattern pattern = Pattern.compile("jdbc:postgresql://([\\\\w\\\\-\\\\.]+):?([0-9]*)/([\\\\w\\\\-]+)"); + private final Pattern pattern = Pattern.compile("jdbc:postgresql://([\\\\w\\\\-\\\\.]+):?([0-9]*)/([\\\\w\\\\-]+)", Pattern.CASE_INSENSITIVE); public PostgreSQLDataSourceMetaData(final String url) { Matcher matcher = pattern.matcher(url); @@ -50,7 +50,7 @@ public final class PostgreSQLDataSourceMetaData implements DataSourceMetaData { port = Strings.isNullOrEmpty(matcher.group(2)) ? DEFAULT_PORT : Integer.valueOf(matcher.group(2)); schemeName = matcher.group(3); } else { - throw new ShardingException("The URL of JDBC is not supported."); + throw new ShardingException("The URL of JDBC is not supported. Please refer to this pattern: %s.", pattern.pattern()); } } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/SQLServerDataSourceMetaData.java b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/SQLServerDataSourceMetaData.java index 791faa9aeaa..8ec50d4048f 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/SQLServerDataSourceMetaData.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/SQLServerDataSourceMetaData.java @@ -41,16 +41,16 @@ public final class SQLServerDataSourceMetaData implements DataSourceMetaData { private final String schemeName; - private final Pattern pattern = Pattern.compile("jdbc:(microsoft:)?sqlserver://([\\\\w\\\\-\\\\.]+):?([0-9]*);DatabaseName=([\\\\w\\\\-]+)"); - + private final Pattern pattern = Pattern.compile("jdbc:(microsoft:)?sqlserver://([\\\\w\\\\-\\\\.]+):?([0-9]*);(DatabaseName|database)=([\\\\w\\\\-]+)", Pattern.CASE_INSENSITIVE); + public SQLServerDataSourceMetaData(final String url) { Matcher matcher = pattern.matcher(url); if (matcher.find()) { hostName = matcher.group(2); port = Strings.isNullOrEmpty(matcher.group(3)) ? DEFAULT_PORT : Integer.valueOf(matcher.group(3)); - schemeName = matcher.group(4); + schemeName = matcher.group(5); } else { - throw new ShardingException("The URL of JDBC is not supported."); + throw new ShardingException("The URL of JDBC is not supported. Please refer to this pattern: %s.", pattern.pattern()); } }
['sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/H2DataSourceMetaData.java', 'sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/PostgreSQLDataSourceMetaData.java', 'sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/OracleDataSourceMetaData.java', 'sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/SQLServerDataSourceMetaData.java', 'sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/MySQLDataSourceMetaData.java']
{'.java': 5}
5
5
0
0
5
2,226,582
464,377
62,439
793
2,441
645
24
5
417
39
123
10
0
0
1970-01-01T00:25:38
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,533
apache/shardingsphere/972/954
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/954
https://github.com/apache/shardingsphere/pull/972
https://github.com/apache/shardingsphere/pull/972
1
fixes
The tables with no configuration appear in the proxy.
The tables which are not configed in yaml can be used with show tables, select etc. It is not correct, i will fix it in next week.
1f507269d224ec774208e1d843c77dcbc84a2d05
ebad0412bdd4cf326733898cac72c69cbbae34db
https://github.com/apache/shardingsphere/compare/1f507269d224ec774208e1d843c77dcbc84a2d05...ebad0412bdd4cf326733898cac72c69cbbae34db
diff --git a/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/SQLPacketsBackendHandler.java b/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/SQLPacketsBackendHandler.java index 55e509112e9..9af8cce6b0a 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/SQLPacketsBackendHandler.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/SQLPacketsBackendHandler.java @@ -46,6 +46,7 @@ import io.shardingsphere.proxy.transport.mysql.packet.generic.ErrPacket; import io.shardingsphere.proxy.transport.mysql.packet.generic.OKPacket; import io.shardingsphere.proxy.util.MySQLResultCache; import io.shardingsphere.proxy.util.SynchronizedFuture; +import lombok.Getter; import lombok.extern.slf4j.Slf4j; import java.sql.SQLException; @@ -64,6 +65,7 @@ import java.util.concurrent.TimeoutException; * @author panjuan */ @Slf4j +@Getter public final class SQLPacketsBackendHandler implements BackendHandler { private static final int CONNECT_TIMEOUT = 30; diff --git a/sharding-proxy/src/main/java/io/shardingsphere/proxy/transport/mysql/packet/command/text/fieldlist/ComFieldListPacket.java b/sharding-proxy/src/main/java/io/shardingsphere/proxy/transport/mysql/packet/command/text/fieldlist/ComFieldListPacket.java index 88836c3a5a3..a0292a57dc5 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/proxy/transport/mysql/packet/command/text/fieldlist/ComFieldListPacket.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/proxy/transport/mysql/packet/command/text/fieldlist/ComFieldListPacket.java @@ -24,11 +24,18 @@ import io.shardingsphere.proxy.backend.common.SQLPacketsBackendHandler; import io.shardingsphere.proxy.config.RuleRegistry; import io.shardingsphere.proxy.transport.common.packet.CommandPacketRebuilder; import io.shardingsphere.proxy.transport.common.packet.DatabaseProtocolPacket; +import io.shardingsphere.proxy.transport.mysql.constant.ColumnType; +import io.shardingsphere.proxy.transport.mysql.constant.StatusFlag; import io.shardingsphere.proxy.transport.mysql.packet.MySQLPacketPayload; import io.shardingsphere.proxy.transport.mysql.packet.command.CommandPacket; import io.shardingsphere.proxy.transport.mysql.packet.command.CommandPacketType; import io.shardingsphere.proxy.transport.mysql.packet.command.CommandResponsePackets; +import io.shardingsphere.proxy.transport.mysql.packet.command.statement.close.DummyPacket; +import io.shardingsphere.proxy.transport.mysql.packet.command.text.query.ColumnDefinition41Packet; import io.shardingsphere.proxy.transport.mysql.packet.command.text.query.ComQueryPacket; +import io.shardingsphere.proxy.transport.mysql.packet.command.text.query.TextResultSetRowPacket; +import io.shardingsphere.proxy.transport.mysql.packet.generic.EofPacket; +import io.shardingsphere.proxy.transport.mysql.packet.generic.ErrPacket; import lombok.extern.slf4j.Slf4j; import java.sql.SQLException; @@ -49,6 +56,8 @@ public final class ComFieldListPacket extends CommandPacket implements CommandPa private final String fieldWildcard; + private int currentSequenceId; + private SQLExecuteBackendHandler sqlExecuteBackendHandler; private SQLPacketsBackendHandler sqlPacketsBackendHandler; @@ -82,10 +91,12 @@ public final class ComFieldListPacket extends CommandPacket implements CommandPa // TODO use common database type if (RuleRegistry.getInstance().isWithoutJdbc()) { sqlPacketsBackendHandler = new SQLPacketsBackendHandler(this, DatabaseType.MySQL, RuleRegistry.getInstance().isShowSQL()); - return sqlPacketsBackendHandler.execute(); + sqlPacketsBackendHandler.execute(); + return new CommandResponsePackets(new DummyPacket()); } else { sqlExecuteBackendHandler = new SQLExecuteBackendHandler(sql, DatabaseType.MySQL, RuleRegistry.getInstance().isShowSQL()); - return sqlExecuteBackendHandler.execute(); + sqlExecuteBackendHandler.execute(); + return new CommandResponsePackets(new DummyPacket()); } } @@ -104,10 +115,25 @@ public final class ComFieldListPacket extends CommandPacket implements CommandPa @Override public DatabaseProtocolPacket getResultValue() { + DatabaseProtocolPacket result; if (RuleRegistry.getInstance().isWithoutJdbc()) { - return sqlPacketsBackendHandler.getResultValue(); + result = sqlPacketsBackendHandler.getResultValue(); + if (!sqlPacketsBackendHandler.isHasMoreResultValueFlag()) { + return new EofPacket(++currentSequenceId, 0, StatusFlag.SERVER_STATUS_AUTOCOMMIT.getValue()); + } + } else { + result = sqlExecuteBackendHandler.getResultValue(); + if (!sqlExecuteBackendHandler.isHasMoreResultValueFlag()) { + return new EofPacket(++currentSequenceId, 0, StatusFlag.SERVER_STATUS_AUTOCOMMIT.getValue()); + } + } + if (result instanceof TextResultSetRowPacket) { + TextResultSetRowPacket fieldListResponse = (TextResultSetRowPacket) result; + String columnName = (String) fieldListResponse.getData().get(0); + return new ColumnDefinition41Packet(++currentSequenceId, ShardingConstant.LOGIC_SCHEMA_NAME, table, table, + columnName, columnName, 100, ColumnType.MYSQL_TYPE_VARCHAR, 0); } else { - return sqlExecuteBackendHandler.getResultValue(); + return new ErrPacket(1, 0, "", "", ""); } }
['sharding-proxy/src/main/java/io/shardingsphere/proxy/transport/mysql/packet/command/text/fieldlist/ComFieldListPacket.java', 'sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/SQLPacketsBackendHandler.java']
{'.java': 2}
2
2
0
0
2
2,048,571
426,039
57,700
707
2,227
446
36
2
131
27
32
2
0
0
1970-01-01T00:25:30
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,532
apache/shardingsphere/1018/962
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/962
https://github.com/apache/shardingsphere/pull/1018
https://github.com/apache/shardingsphere/pull/1018
1
fixes
Column types disordered when use prepared statement in Proxy
Please answer these questions before submitting your issue. Thanks! 开源不易,我们希望将精力放在完成新功能和解决有价值的问题上,为了让大家的配合更具有效率,请填写以下列出的全部问题 ### Which version of Sharding-Sphere do you using?(您使用的Sharding-Sphere版本为?) dev ### Expected behavior (您预期的结果是) correct prepared statement result ### Actual behavior (实际运行的结果是) a chance to triger wrong result ### Steps to reproduce the behavior (可重现问题的操作步骤) use prepared statement in Proxy ### Please provide the reproduce example codes (such as github link),otherwise we will label the issue as Invalid and close it.(为了节省复现问题的时间,请务必提供可重现的代码,否则我们会将issue直接标记为invalid并关闭) example Code should based on https://github.com/sharding-sphere/sharding-sphere-example (代码请基于 https://github.com/sharding-sphere/sharding-sphere-example)
2980776da2bd492d2dcf1eb93c39deb64cd134a7
0481d943a5f13381d98546ba08317a9cab9291bb
https://github.com/apache/shardingsphere/compare/2980776da2bd492d2dcf1eb93c39deb64cd134a7...0481d943a5f13381d98546ba08317a9cab9291bb
diff --git a/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/jdbc/JDBCExecuteWorker.java b/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/jdbc/JDBCExecuteWorker.java index 90358c3135f..b6bb34dd4e4 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/jdbc/JDBCExecuteWorker.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/jdbc/JDBCExecuteWorker.java @@ -35,6 +35,8 @@ import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; import java.util.concurrent.Callable; /** @@ -86,16 +88,18 @@ public abstract class JDBCExecuteWorker implements Callable<CommandResponsePacke return new CommandResponsePackets(new OKPacket(++currentSequenceId)); } CommandResponsePackets result = new CommandResponsePackets(new FieldCountPacket(++currentSequenceId, columnCount)); + List<ColumnType> columnTypes = new ArrayList<>(128); for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) { - setColumnType(ColumnType.valueOfJDBCType(resultSetMetaData.getColumnType(columnIndex))); + columnTypes.add(ColumnType.valueOfJDBCType(resultSetMetaData.getColumnType(columnIndex))); result.addPacket(new ColumnDefinition41Packet(++currentSequenceId, resultSetMetaData, columnIndex)); } + setColumnTypes(columnTypes); result.addPacket(new EofPacket(++currentSequenceId)); return result; } // TODO why only prepareStatement need this? - protected void setColumnType(final ColumnType columnType) { + protected void setColumnTypes(final List<ColumnType> columnTypes) { } private long getGeneratedKey() throws SQLException { diff --git a/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/jdbc/statement/JDBCStatementBackendHandler.java b/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/jdbc/statement/JDBCStatementBackendHandler.java index 68508d04c6c..3bcba985556 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/jdbc/statement/JDBCStatementBackendHandler.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/jdbc/statement/JDBCStatementBackendHandler.java @@ -28,7 +28,7 @@ import io.shardingsphere.proxy.transport.mysql.packet.command.CommandResponsePac import io.shardingsphere.proxy.transport.mysql.packet.command.statement.PreparedStatementRegistry; import io.shardingsphere.proxy.transport.mysql.packet.command.statement.execute.BinaryResultSetRowPacket; import io.shardingsphere.proxy.transport.mysql.packet.command.statement.execute.PreparedStatementParameter; -import lombok.Getter; +import lombok.Setter; import java.sql.Connection; import java.sql.PreparedStatement; @@ -37,7 +37,6 @@ import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; -import java.util.concurrent.CopyOnWriteArrayList; /** * Statement protocol backend handler via JDBC to connect databases. @@ -51,8 +50,8 @@ public final class JDBCStatementBackendHandler extends JDBCBackendHandler { private final DatabaseType databaseType; - @Getter - private final List<ColumnType> columnTypes; + @Setter + private List<ColumnType> columnTypes; private final RuleRegistry ruleRegistry; @@ -60,7 +59,6 @@ public final class JDBCStatementBackendHandler extends JDBCBackendHandler { super(PreparedStatementRegistry.getInstance().getSQL(statementId)); this.preparedStatementParameters = preparedStatementParameters; this.databaseType = databaseType; - columnTypes = new CopyOnWriteArrayList<>(); ruleRegistry = RuleRegistry.getInstance(); } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/jdbc/statement/JDBCStatementExecuteWorker.java b/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/jdbc/statement/JDBCStatementExecuteWorker.java index 9f2e212ebc0..3f7758e5082 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/jdbc/statement/JDBCStatementExecuteWorker.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/jdbc/statement/JDBCStatementExecuteWorker.java @@ -22,6 +22,7 @@ import io.shardingsphere.proxy.transport.mysql.constant.ColumnType; import java.sql.PreparedStatement; import java.sql.SQLException; +import java.util.List; /** * Statement execute worker. @@ -45,7 +46,7 @@ public final class JDBCStatementExecuteWorker extends JDBCExecuteWorker { } @Override - protected void setColumnType(final ColumnType columnType) { - ((JDBCStatementBackendHandler) getJdbcBackendHandler()).getColumnTypes().add(columnType); + protected void setColumnTypes(final List<ColumnType> columnTypes) { + ((JDBCStatementBackendHandler) getJdbcBackendHandler()).setColumnTypes(columnTypes); } }
['sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/jdbc/JDBCExecuteWorker.java', 'sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/jdbc/statement/JDBCStatementExecuteWorker.java', 'sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/jdbc/statement/JDBCStatementBackendHandler.java']
{'.java': 3}
3
3
0
0
3
2,139,876
445,975
60,518
762
1,117
217
21
3
776
78
251
21
2
0
1970-01-01T00:25:31
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,529
apache/shardingsphere/1050/372
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/372
https://github.com/apache/shardingsphere/pull/1050
https://github.com/apache/shardingsphere/pull/1050
1
fixes
Reuse PreparedStatement cause cache of route result do not clean
Please answer these questions before submitting your issue. Thanks! ### Which version of Sharding-Jdbc do you using? 1.5.3 ### Expected behavior 使用mybaits作为orm框架 开启spring事物支持时,在mybaits的settings中将defaultExecutorType设置为REUSE, 在同一个事物中查询时,即使路由不同的表查询正常 ### Actual behavior 开启事物 路由到同一张表是则查询正常,路由不同的表则异常 ### Steps to reproduce the behavior 1.启动项目 2Controller包下的的方法 3.点击控制台打印的路径 http://localhot:8081/select 若想不产生这个bug可以采取如下两种方法之一 1.关闭事物 2.开启事物则需将mybatisConfig.xml的defaultExecutorType设置为SIMPLE ### Please provide the reproduce example codes (such as github link) if possible. https://git.oschina.net/lxhs/com.study.demo.git
ae8966569b2c484d28fb55109a156124b6e5afb2
c811b6ffca57a0914a2f2d84acebaa2b4130d497
https://github.com/apache/shardingsphere/compare/ae8966569b2c484d28fb55109a156124b6e5afb2...c811b6ffca57a0914a2f2d84acebaa2b4130d497
diff --git a/sharding-jdbc/src/main/java/io/shardingsphere/core/jdbc/core/statement/ShardingPreparedStatement.java b/sharding-jdbc/src/main/java/io/shardingsphere/core/jdbc/core/statement/ShardingPreparedStatement.java index ea4e92a00b1..83d11abbf82 100644 --- a/sharding-jdbc/src/main/java/io/shardingsphere/core/jdbc/core/statement/ShardingPreparedStatement.java +++ b/sharding-jdbc/src/main/java/io/shardingsphere/core/jdbc/core/statement/ShardingPreparedStatement.java @@ -129,6 +129,7 @@ public final class ShardingPreparedStatement extends AbstractShardingPreparedSta @Override public ResultSet executeQuery() throws SQLException { + routedStatements.clear(); ResultSet result; try { Collection<PreparedStatementUnit> preparedStatementUnits = route(); @@ -150,6 +151,7 @@ public final class ShardingPreparedStatement extends AbstractShardingPreparedSta @Override public int executeUpdate() throws SQLException { + routedStatements.clear(); try { Collection<PreparedStatementUnit> preparedStatementUnits = route(); return new PreparedStatementExecutor( @@ -164,6 +166,7 @@ public final class ShardingPreparedStatement extends AbstractShardingPreparedSta @Override public boolean execute() throws SQLException { + routedStatements.clear(); try { Collection<PreparedStatementUnit> preparedStatementUnits = route(); return new PreparedStatementExecutor(
['sharding-jdbc/src/main/java/io/shardingsphere/core/jdbc/core/statement/ShardingPreparedStatement.java']
{'.java': 1}
1
1
0
0
1
2,179,464
453,615
61,420
772
104
15
3
1
636
56
243
21
2
0
1970-01-01T00:25:32
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,535
apache/shardingsphere/961/954
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/954
https://github.com/apache/shardingsphere/pull/961
https://github.com/apache/shardingsphere/pull/961
1
fixes
The tables with no configuration appear in the proxy.
The tables which are not configed in yaml can be used with show tables, select etc. It is not correct, i will fix it in next week.
6b4a4632b91b6e816b69264b7c3512a2aaa151b3
83be16ee4ba19fa2aed74e737578b7af4a1cbad4
https://github.com/apache/shardingsphere/compare/6b4a4632b91b6e816b69264b7c3512a2aaa151b3...83be16ee4ba19fa2aed74e737578b7af4a1cbad4
diff --git a/sharding-proxy/src/main/java/io/shardingsphere/proxy/transport/mysql/packet/command/text/fieldlist/ComFieldListPacket.java b/sharding-proxy/src/main/java/io/shardingsphere/proxy/transport/mysql/packet/command/text/fieldlist/ComFieldListPacket.java index 373a17bcf07..88836c3a5a3 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/proxy/transport/mysql/packet/command/text/fieldlist/ComFieldListPacket.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/proxy/transport/mysql/packet/command/text/fieldlist/ComFieldListPacket.java @@ -31,6 +31,8 @@ import io.shardingsphere.proxy.transport.mysql.packet.command.CommandResponsePac import io.shardingsphere.proxy.transport.mysql.packet.command.text.query.ComQueryPacket; import lombok.extern.slf4j.Slf4j; +import java.sql.SQLException; + /** * COM_FIELD_LIST command packet. * @@ -47,6 +49,10 @@ public final class ComFieldListPacket extends CommandPacket implements CommandPa private final String fieldWildcard; + private SQLExecuteBackendHandler sqlExecuteBackendHandler; + + private SQLPacketsBackendHandler sqlPacketsBackendHandler; + public ComFieldListPacket(final int sequenceId, final int connectionId, final MySQLPacketPayload mysqlPacketPayload) { super(sequenceId); this.connectionId = connectionId; @@ -75,20 +81,34 @@ public final class ComFieldListPacket extends CommandPacket implements CommandPa String sql = String.format("SHOW COLUMNS FROM %s FROM %s", table, ShardingConstant.LOGIC_SCHEMA_NAME); // TODO use common database type if (RuleRegistry.getInstance().isWithoutJdbc()) { - return new SQLPacketsBackendHandler(this, DatabaseType.MySQL, RuleRegistry.getInstance().isShowSQL()).execute(); + sqlPacketsBackendHandler = new SQLPacketsBackendHandler(this, DatabaseType.MySQL, RuleRegistry.getInstance().isShowSQL()); + return sqlPacketsBackendHandler.execute(); } else { - return new SQLExecuteBackendHandler(sql, DatabaseType.MySQL, RuleRegistry.getInstance().isShowSQL()).execute(); + sqlExecuteBackendHandler = new SQLExecuteBackendHandler(sql, DatabaseType.MySQL, RuleRegistry.getInstance().isShowSQL()); + return sqlExecuteBackendHandler.execute(); } } @Override public boolean hasMoreResultValue() { - return false; + try { + if (RuleRegistry.getInstance().isWithoutJdbc()) { + return sqlPacketsBackendHandler.hasMoreResultValue(); + } else { + return sqlExecuteBackendHandler.hasMoreResultValue(); + } + } catch (final SQLException ex) { + return false; + } } @Override public DatabaseProtocolPacket getResultValue() { - return null; + if (RuleRegistry.getInstance().isWithoutJdbc()) { + return sqlPacketsBackendHandler.getResultValue(); + } else { + return sqlExecuteBackendHandler.getResultValue(); + } } @Override
['sharding-proxy/src/main/java/io/shardingsphere/proxy/transport/mysql/packet/command/text/fieldlist/ComFieldListPacket.java']
{'.java': 1}
1
1
0
0
1
2,044,638
425,309
57,597
707
1,431
282
28
1
131
27
32
2
0
0
1970-01-01T00:25:29
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,542
apache/shardingsphere/564/559
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/559
https://github.com/apache/shardingsphere/pull/564
https://github.com/apache/shardingsphere/pull/564
1
fixes
Support parsing numbers beginning with minus and decimal (e.g. `-.12`)
**BUG** 当前最新分支上,io.shardingjdbc.core.parsing.lexer.Lexer中代码: ```java private boolean isNumberBegin() { return CharType.isDigital(getCurrentChar(0)) || ('.' == getCurrentChar(0) && CharType.isDigital(getCurrentChar(1)) && !isIdentifierBegin(getCurrentChar(-1)) || ('-' == getCurrentChar(0) && ('.' == getCurrentChar(0) || CharType.isDigital(getCurrentChar(1))))); } ``` 最后一个判断负数的逻辑,应该是 `('-' == getCurrentChar(0) && ('.' == getCurrentChar(1) || CharType.isDigital(getCurrentChar(1))))`,才能解析出 `-.12` 这种情况
d113495faa6d389875ea7e49098c3a249e183250
d2a84d5786f51d83c8a721daa493f75b577c90c3
https://github.com/apache/shardingsphere/compare/d113495faa6d389875ea7e49098c3a249e183250...d2a84d5786f51d83c8a721daa493f75b577c90c3
diff --git a/sharding-jdbc-core/src/main/java/io/shardingjdbc/core/parsing/lexer/Lexer.java b/sharding-jdbc-core/src/main/java/io/shardingjdbc/core/parsing/lexer/Lexer.java index 93c8e3e68fb..aaaac141f63 100755 --- a/sharding-jdbc-core/src/main/java/io/shardingjdbc/core/parsing/lexer/Lexer.java +++ b/sharding-jdbc-core/src/main/java/io/shardingjdbc/core/parsing/lexer/Lexer.java @@ -119,7 +119,7 @@ public class Lexer { private boolean isNumberBegin() { return CharType.isDigital(getCurrentChar(0)) || ('.' == getCurrentChar(0) && CharType.isDigital(getCurrentChar(1)) && !isIdentifierBegin(getCurrentChar(-1)) - || ('-' == getCurrentChar(0) && ('.' == getCurrentChar(0) || CharType.isDigital(getCurrentChar(1))))); + || ('-' == getCurrentChar(0) && ('.' == getCurrentChar(1) || CharType.isDigital(getCurrentChar(1))))); } private boolean isSymbolBegin() { diff --git a/sharding-jdbc-core/src/test/java/io/shardingjdbc/core/parsing/lexer/LexerTest.java b/sharding-jdbc-core/src/test/java/io/shardingjdbc/core/parsing/lexer/LexerTest.java index 708faf2381a..9bb1968c843 100644 --- a/sharding-jdbc-core/src/test/java/io/shardingjdbc/core/parsing/lexer/LexerTest.java +++ b/sharding-jdbc-core/src/test/java/io/shardingjdbc/core/parsing/lexer/LexerTest.java @@ -74,6 +74,7 @@ public final class LexerTest { assertNextTokenForNumber("0x-1e", Literals.HEX); assertNextTokenForNumber("123", Literals.INT); assertNextTokenForNumber("-123", Literals.INT); + assertNextTokenForNumber("-.123", Literals.FLOAT); assertNextTokenForNumber("123.0", Literals.FLOAT); assertNextTokenForNumber("123e4", Literals.FLOAT); assertNextTokenForNumber("123E4", Literals.FLOAT);
['sharding-jdbc-core/src/test/java/io/shardingjdbc/core/parsing/lexer/LexerTest.java', 'sharding-jdbc-core/src/main/java/io/shardingjdbc/core/parsing/lexer/Lexer.java']
{'.java': 2}
2
2
0
0
2
1,244,171
255,724
35,345
468
239
61
2
1
544
41
178
12
0
1
1970-01-01T00:25:16
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,536
apache/shardingsphere/960/954
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/954
https://github.com/apache/shardingsphere/pull/960
https://github.com/apache/shardingsphere/pull/960
1
fixes
The tables with no configuration appear in the proxy.
The tables which are not configed in yaml can be used with show tables, select etc. It is not correct, i will fix it in next week.
6b4a4632b91b6e816b69264b7c3512a2aaa151b3
1a103b4e87b651829049d6141b00ae037fe2bfca
https://github.com/apache/shardingsphere/compare/6b4a4632b91b6e816b69264b7c3512a2aaa151b3...1a103b4e87b651829049d6141b00ae037fe2bfca
diff --git a/sharding-core/src/main/java/io/shardingsphere/core/merger/MergeEngineFactory.java b/sharding-core/src/main/java/io/shardingsphere/core/merger/MergeEngineFactory.java index 368247b6be0..6a06589465c 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/merger/MergeEngineFactory.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/merger/MergeEngineFactory.java @@ -19,6 +19,7 @@ package io.shardingsphere.core.merger; import io.shardingsphere.core.merger.dal.DALMergeEngine; import io.shardingsphere.core.merger.dql.DQLMergeEngine; +import io.shardingsphere.core.metadata.ShardingMetaData; import io.shardingsphere.core.parsing.parser.sql.SQLStatement; import io.shardingsphere.core.parsing.parser.sql.dal.DALStatement; import io.shardingsphere.core.parsing.parser.sql.dql.select.SelectStatement; @@ -33,6 +34,7 @@ import java.util.List; * Result merge engine factory. * * @author zhangliang + * @author panjuan */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class MergeEngineFactory { @@ -43,15 +45,17 @@ public final class MergeEngineFactory { * @param shardingRule sharding rule * @param queryResults query results * @param sqlStatement SQL statement + * @param shardingMetaData sharding meta Data * @return merge engine instance * @throws SQLException SQL exception */ - public static MergeEngine newInstance(final ShardingRule shardingRule, final List<QueryResult> queryResults, final SQLStatement sqlStatement) throws SQLException { + public static MergeEngine newInstance(final ShardingRule shardingRule, final List<QueryResult> queryResults, + final SQLStatement sqlStatement, final ShardingMetaData shardingMetaData) throws SQLException { if (sqlStatement instanceof SelectStatement) { return new DQLMergeEngine(queryResults, (SelectStatement) sqlStatement); } if (sqlStatement instanceof DALStatement) { - return new DALMergeEngine(shardingRule, queryResults, (DALStatement) sqlStatement); + return new DALMergeEngine(shardingRule, queryResults, (DALStatement) sqlStatement, shardingMetaData); } throw new UnsupportedOperationException(String.format("Cannot support type '%s'", sqlStatement.getType())); } diff --git a/sharding-core/src/main/java/io/shardingsphere/core/merger/dal/DALMergeEngine.java b/sharding-core/src/main/java/io/shardingsphere/core/merger/dal/DALMergeEngine.java index b8884613dfe..4f8104f227c 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/merger/dal/DALMergeEngine.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/merger/dal/DALMergeEngine.java @@ -24,6 +24,7 @@ import io.shardingsphere.core.merger.dal.show.ShowCreateTableMergedResult; import io.shardingsphere.core.merger.dal.show.ShowDatabasesMergedResult; import io.shardingsphere.core.merger.dal.show.ShowOtherMergedResult; import io.shardingsphere.core.merger.dal.show.ShowTablesMergedResult; +import io.shardingsphere.core.metadata.ShardingMetaData; import io.shardingsphere.core.parsing.parser.dialect.mysql.statement.ShowCreateTableStatement; import io.shardingsphere.core.parsing.parser.dialect.mysql.statement.ShowDatabasesStatement; import io.shardingsphere.core.parsing.parser.dialect.mysql.statement.ShowTablesStatement; @@ -38,6 +39,7 @@ import java.util.List; * DAL result set merge engine. * * @author zhangliang + * @author panjuan */ @RequiredArgsConstructor public final class DALMergeEngine implements MergeEngine { @@ -48,13 +50,15 @@ public final class DALMergeEngine implements MergeEngine { private final DALStatement dalStatement; + private final ShardingMetaData shardingMetaData; + @Override public MergedResult merge() throws SQLException { if (dalStatement instanceof ShowDatabasesStatement) { return new ShowDatabasesMergedResult(); } if (dalStatement instanceof ShowTablesStatement) { - return new ShowTablesMergedResult(shardingRule, queryResults); + return new ShowTablesMergedResult(shardingRule, queryResults, shardingMetaData); } if (dalStatement instanceof ShowCreateTableStatement) { return new ShowCreateTableMergedResult(shardingRule, queryResults); diff --git a/sharding-core/src/main/java/io/shardingsphere/core/merger/dal/show/ShowTablesMergedResult.java b/sharding-core/src/main/java/io/shardingsphere/core/merger/dal/show/ShowTablesMergedResult.java index f49d373e053..4fa86199ee4 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/merger/dal/show/ShowTablesMergedResult.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/merger/dal/show/ShowTablesMergedResult.java @@ -22,6 +22,7 @@ import io.shardingsphere.core.constant.ShardingConstant; import io.shardingsphere.core.merger.QueryResult; import io.shardingsphere.core.merger.dql.common.MemoryMergedResult; import io.shardingsphere.core.merger.dql.common.MemoryQueryResultRow; +import io.shardingsphere.core.metadata.ShardingMetaData; import io.shardingsphere.core.rule.ShardingRule; import io.shardingsphere.core.rule.TableRule; @@ -38,6 +39,7 @@ import java.util.Set; * Merged result for show tables. * * @author zhangliang + * @author panjuan */ public final class ShowTablesMergedResult extends MemoryMergedResult { @@ -49,13 +51,16 @@ public final class ShowTablesMergedResult extends MemoryMergedResult { private final Set<String> tableNames = new HashSet<>(); + private final ShardingMetaData shardingMetaData; + static { LABEL_AND_INDEX_MAP.put("Tables_in_" + ShardingConstant.LOGIC_SCHEMA_NAME, 1); } - public ShowTablesMergedResult(final ShardingRule shardingRule, final List<QueryResult> queryResults) throws SQLException { + public ShowTablesMergedResult(final ShardingRule shardingRule, final List<QueryResult> queryResults, final ShardingMetaData shardingMetaData) throws SQLException { super(LABEL_AND_INDEX_MAP); this.shardingRule = shardingRule; + this.shardingMetaData = shardingMetaData; memoryResultSetRows = init(queryResults); } @@ -67,7 +72,11 @@ public final class ShowTablesMergedResult extends MemoryMergedResult { String actualTableName = memoryResultSetRow.getCell(1).toString(); Optional<TableRule> tableRule = shardingRule.tryFindTableRuleByActualTable(actualTableName); if (!tableRule.isPresent()) { - result.add(memoryResultSetRow); + if (shardingMetaData.getTableMetaDataMap().keySet().contains(actualTableName)) { + result.add(memoryResultSetRow); + } else if (!shardingMetaData.isSupportedDatabaseType()) { + result.add(memoryResultSetRow); + } } else if (tableNames.add(tableRule.get().getLogicTable())) { memoryResultSetRow.setCell(1, tableRule.get().getLogicTable()); result.add(memoryResultSetRow); diff --git a/sharding-core/src/main/java/io/shardingsphere/core/metadata/ShardingMetaData.java b/sharding-core/src/main/java/io/shardingsphere/core/metadata/ShardingMetaData.java index 5fbef7e72c4..13f20104f69 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/metadata/ShardingMetaData.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/metadata/ShardingMetaData.java @@ -168,4 +168,18 @@ public abstract class ShardingMetaData { return String.format("Cannot get uniformed table structure for %s. The different metadata of actual tables is as follows:\\n%s\\n%s.", logicTableName, oldTableMetaData.toString(), newTableMetaData.toString()); } + + /** + * Judge whether this databaseType is supported. + * + * @return supported or not + */ + public boolean isSupportedDatabaseType() { + for (TableMetaData each : tableMetaDataMap.values()) { + if (each.getColumnMetaData().isEmpty()) { + return false; + } + } + return true; + } } diff --git a/sharding-core/src/test/java/io/shardingsphere/core/merger/MergeEngineFactoryTest.java b/sharding-core/src/test/java/io/shardingsphere/core/merger/MergeEngineFactoryTest.java index 24af722058d..40128c9ec21 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/merger/MergeEngineFactoryTest.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/merger/MergeEngineFactoryTest.java @@ -58,18 +58,18 @@ public final class MergeEngineFactoryTest { @Test public void assertNewInstanceWithSelectStatement() throws SQLException { SQLStatement selectStatement = new SelectStatement(); - assertThat(MergeEngineFactory.newInstance(null, queryResults, selectStatement), instanceOf(DQLMergeEngine.class)); + assertThat(MergeEngineFactory.newInstance(null, queryResults, selectStatement, null), instanceOf(DQLMergeEngine.class)); } @Test public void assertNewInstanceWithDALStatement() throws SQLException { SQLStatement dalStatement = new DALStatement(); - assertThat(MergeEngineFactory.newInstance(null, queryResults, dalStatement), instanceOf(DALMergeEngine.class)); + assertThat(MergeEngineFactory.newInstance(null, queryResults, dalStatement, null), instanceOf(DALMergeEngine.class)); } @Test(expected = UnsupportedOperationException.class) public void assertNewInstanceWithOtherStatement() throws SQLException { SQLStatement insertStatement = new InsertStatement(); - MergeEngineFactory.newInstance(null, queryResults, insertStatement); + MergeEngineFactory.newInstance(null, queryResults, insertStatement, null); } } diff --git a/sharding-core/src/test/java/io/shardingsphere/core/merger/dal/DALMergeEngineTest.java b/sharding-core/src/test/java/io/shardingsphere/core/merger/dal/DALMergeEngineTest.java index 9d870960ad0..99f312519cb 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/merger/dal/DALMergeEngineTest.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/merger/dal/DALMergeEngineTest.java @@ -53,28 +53,28 @@ public final class DALMergeEngineTest { @Test public void assertMergeForShowDatabasesStatement() throws SQLException { DALStatement dalStatement = new ShowDatabasesStatement(); - DALMergeEngine dalMergeEngine = new DALMergeEngine(null, queryResults, dalStatement); + DALMergeEngine dalMergeEngine = new DALMergeEngine(null, queryResults, dalStatement, null); assertThat(dalMergeEngine.merge(), instanceOf(ShowDatabasesMergedResult.class)); } @Test public void assertMergeForShowShowTablesStatement() throws SQLException { DALStatement dalStatement = new ShowTablesStatement(); - DALMergeEngine dalMergeEngine = new DALMergeEngine(null, queryResults, dalStatement); + DALMergeEngine dalMergeEngine = new DALMergeEngine(null, queryResults, dalStatement, null); assertThat(dalMergeEngine.merge(), instanceOf(ShowTablesMergedResult.class)); } @Test public void assertMergeForShowCreateTableStatement() throws SQLException { DALStatement dalStatement = new ShowCreateTableStatement(); - DALMergeEngine dalMergeEngine = new DALMergeEngine(null, queryResults, dalStatement); + DALMergeEngine dalMergeEngine = new DALMergeEngine(null, queryResults, dalStatement, null); assertThat(dalMergeEngine.merge(), instanceOf(ShowCreateTableMergedResult.class)); } @Test public void assertMergeForShowOtherStatement() throws SQLException { DALStatement dalStatement = new ShowOtherStatement(); - DALMergeEngine dalMergeEngine = new DALMergeEngine(null, queryResults, dalStatement); + DALMergeEngine dalMergeEngine = new DALMergeEngine(null, queryResults, dalStatement, null); assertThat(dalMergeEngine.merge(), instanceOf(ShowOtherMergedResult.class)); } } diff --git a/sharding-core/src/test/java/io/shardingsphere/core/merger/dal/show/ShowTablesMergedResultTest.java b/sharding-core/src/test/java/io/shardingsphere/core/merger/dal/show/ShowTablesMergedResultTest.java index 0222ce7cadc..d90a12b6394 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/merger/dal/show/ShowTablesMergedResultTest.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/merger/dal/show/ShowTablesMergedResultTest.java @@ -24,6 +24,8 @@ import io.shardingsphere.core.api.config.TableRuleConfiguration; import io.shardingsphere.core.api.config.strategy.ComplexShardingStrategyConfiguration; import io.shardingsphere.core.merger.QueryResult; import io.shardingsphere.core.merger.fixture.TestQueryResult; +import io.shardingsphere.core.metadata.ShardingMetaData; +import io.shardingsphere.core.metadata.TableMetaData; import io.shardingsphere.core.rule.ShardingRule; import org.junit.Before; import org.junit.Test; @@ -32,10 +34,12 @@ import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -47,6 +51,8 @@ public final class ShowTablesMergedResultTest { private ResultSet resultSet; + private ShardingMetaData shardingMetaData; + @Before public void setUp() throws SQLException { TableRuleConfiguration tableRuleConfig = new TableRuleConfiguration(); @@ -56,6 +62,11 @@ public final class ShowTablesMergedResultTest { ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration(); shardingRuleConfig.getTableRuleConfigs().add(tableRuleConfig); shardingRule = new ShardingRule(shardingRuleConfig, Lists.newArrayList("ds")); + shardingMetaData = mock(ShardingMetaData.class); + Map<String, TableMetaData> tableMetaDataMap = new HashMap<>(); + tableMetaDataMap.put("table", new TableMetaData()); + when(shardingMetaData.getTableMetaDataMap()).thenReturn(tableMetaDataMap); +// when(shardingMetaData.getTableMetaDataMap().keySet()).thenReturn(new HashSet<String>(){{add("table");}}); resultSet = mock(ResultSet.class); ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class); @@ -73,21 +84,21 @@ public final class ShowTablesMergedResultTest { @Test public void assertNextForEmptyQueryResult() throws SQLException { - ShowTablesMergedResult showTablesMergedResult = new ShowTablesMergedResult(shardingRule, new ArrayList<QueryResult>()); + ShowTablesMergedResult showTablesMergedResult = new ShowTablesMergedResult(shardingRule, new ArrayList<QueryResult>(), shardingMetaData); assertFalse(showTablesMergedResult.next()); } @Test public void assertNextForActualTableNameInTableRule() throws SQLException { when(resultSet.getObject(1)).thenReturn("table_0"); - ShowTablesMergedResult showTablesMergedResult = new ShowTablesMergedResult(shardingRule, queryResults); + ShowTablesMergedResult showTablesMergedResult = new ShowTablesMergedResult(shardingRule, queryResults, shardingMetaData); assertTrue(showTablesMergedResult.next()); } @Test public void assertNextForActualTableNameNotInTableRule() throws SQLException { when(resultSet.getObject(1)).thenReturn("table_3"); - ShowTablesMergedResult showTablesMergedResult = new ShowTablesMergedResult(shardingRule, queryResults); + ShowTablesMergedResult showTablesMergedResult = new ShowTablesMergedResult(shardingRule, queryResults, shardingMetaData); assertTrue(showTablesMergedResult.next()); } } diff --git a/sharding-jdbc/src/main/java/io/shardingsphere/core/jdbc/core/statement/ShardingPreparedStatement.java b/sharding-jdbc/src/main/java/io/shardingsphere/core/jdbc/core/statement/ShardingPreparedStatement.java index 9c102091c54..a2368fdde14 100644 --- a/sharding-jdbc/src/main/java/io/shardingsphere/core/jdbc/core/statement/ShardingPreparedStatement.java +++ b/sharding-jdbc/src/main/java/io/shardingsphere/core/jdbc/core/statement/ShardingPreparedStatement.java @@ -137,7 +137,8 @@ public final class ShardingPreparedStatement extends AbstractShardingPreparedSta for (ResultSet each : resultSets) { queryResults.add(new JDBCQueryResult(each)); } - MergeEngine mergeEngine = MergeEngineFactory.newInstance(connection.getShardingContext().getShardingRule(), queryResults, routeResult.getSqlStatement()); + MergeEngine mergeEngine = MergeEngineFactory.newInstance(connection.getShardingContext().getShardingRule(), + queryResults, routeResult.getSqlStatement(), connection.getShardingContext().getShardingMetaData()); result = new ShardingResultSet(resultSets, merge(mergeEngine), this); } finally { clearBatch(); @@ -305,7 +306,8 @@ public final class ShardingPreparedStatement extends AbstractShardingPreparedSta queryResults.add(new JDBCQueryResult(resultSet)); } if (routeResult.getSqlStatement() instanceof SelectStatement || routeResult.getSqlStatement() instanceof DALStatement) { - MergeEngine mergeEngine = MergeEngineFactory.newInstance(connection.getShardingContext().getShardingRule(), queryResults, routeResult.getSqlStatement()); + MergeEngine mergeEngine = MergeEngineFactory.newInstance(connection.getShardingContext().getShardingRule(), queryResults, + routeResult.getSqlStatement(), connection.getShardingContext().getShardingMetaData()); currentResultSet = new ShardingResultSet(resultSets, merge(mergeEngine), this); } return currentResultSet; diff --git a/sharding-jdbc/src/main/java/io/shardingsphere/core/jdbc/core/statement/ShardingStatement.java b/sharding-jdbc/src/main/java/io/shardingsphere/core/jdbc/core/statement/ShardingStatement.java index d7f69f24fa3..f1ef5aa97e7 100644 --- a/sharding-jdbc/src/main/java/io/shardingsphere/core/jdbc/core/statement/ShardingStatement.java +++ b/sharding-jdbc/src/main/java/io/shardingsphere/core/jdbc/core/statement/ShardingStatement.java @@ -110,7 +110,8 @@ public class ShardingStatement extends AbstractStatementAdapter { for (ResultSet each : resultSets) { queryResults.add(new JDBCQueryResult(each)); } - MergeEngine mergeEngine = MergeEngineFactory.newInstance(connection.getShardingContext().getShardingRule(), queryResults, routeResult.getSqlStatement()); + MergeEngine mergeEngine = MergeEngineFactory.newInstance(connection.getShardingContext().getShardingRule(), queryResults, + routeResult.getSqlStatement(), connection.getShardingContext().getShardingMetaData()); result = new ShardingResultSet(resultSets, merge(mergeEngine), this); } finally { currentResultSet = null; @@ -283,7 +284,8 @@ public class ShardingStatement extends AbstractStatementAdapter { queryResults.add(new JDBCQueryResult(resultSet)); } if (routeResult.getSqlStatement() instanceof SelectStatement || routeResult.getSqlStatement() instanceof DALStatement) { - MergeEngine mergeEngine = MergeEngineFactory.newInstance(connection.getShardingContext().getShardingRule(), queryResults, routeResult.getSqlStatement()); + MergeEngine mergeEngine = MergeEngineFactory.newInstance(connection.getShardingContext().getShardingRule(), queryResults, + routeResult.getSqlStatement(), connection.getShardingContext().getShardingMetaData()); currentResultSet = new ShardingResultSet(resultSets, merge(mergeEngine), this); } return currentResultSet; diff --git a/sharding-opentracing/src/test/java/io/shardingsphere/opentracing/MergeEventListenerTest.java b/sharding-opentracing/src/test/java/io/shardingsphere/opentracing/MergeEventListenerTest.java index 02feaa7d813..44fa16c821b 100644 --- a/sharding-opentracing/src/test/java/io/shardingsphere/opentracing/MergeEventListenerTest.java +++ b/sharding-opentracing/src/test/java/io/shardingsphere/opentracing/MergeEventListenerTest.java @@ -82,7 +82,7 @@ public final class MergeEventListenerTest { dataSourceMap.put("ds_1", null); ShardingRule shardingRule = new ShardingRule(shardingRuleConfig, dataSourceMap.keySet()); shardingContext = new ShardingContext(dataSourceMap, shardingRule, DatabaseType.MySQL, null, null, true); - mergeEngine = new DALMergeEngine(null, null, new ShowDatabasesStatement()); + mergeEngine = new DALMergeEngine(null, null, new ShowDatabasesStatement(), null); } @Test @@ -107,7 +107,7 @@ public final class MergeEventListenerTest { @Test public void assertException() { try { - MergeEngine errorMergeEngine = new DALMergeEngine(null, null, new ShowColumnsStatement()); + MergeEngine errorMergeEngine = new DALMergeEngine(null, null, new ShowColumnsStatement(), null); ShardingStatement statement = new ShardingStatement(new ShardingConnection(shardingContext)); Method mergeMethod = ShardingStatement.class.getDeclaredMethod("merge", MergeEngine.class); mergeMethod.setAccessible(true); diff --git a/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/SQLExecuteBackendHandler.java b/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/SQLExecuteBackendHandler.java index 234ed51c4d8..5dd2b8f99fe 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/SQLExecuteBackendHandler.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/SQLExecuteBackendHandler.java @@ -17,17 +17,6 @@ package io.shardingsphere.proxy.backend.common; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - import io.shardingsphere.core.constant.DatabaseType; import io.shardingsphere.core.constant.SQLType; import io.shardingsphere.core.exception.ShardingException; @@ -55,6 +44,17 @@ import io.shardingsphere.proxy.transport.mysql.packet.generic.OKPacket; import lombok.Getter; import lombok.Setter; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; + /** * SQL execute backend handler. * @@ -198,7 +198,8 @@ public final class SQLExecuteBackendHandler implements BackendHandler { queryResults.add(mySQLPacketQueryResult); } try { - mergedResult = MergeEngineFactory.newInstance(RuleRegistry.getInstance().getShardingRule(), queryResults, sqlStatement).merge(); + mergedResult = MergeEngineFactory.newInstance(RuleRegistry.getInstance().getShardingRule(), queryResults, + sqlStatement, RuleRegistry.getInstance().getShardingMetaData()).merge(); isMerged = true; } catch (final SQLException ex) { return new CommandResponsePackets(new ErrPacket(1, ex.getErrorCode(), "", ex.getSQLState(), ex.getMessage())); diff --git a/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/SQLPacketsBackendHandler.java b/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/SQLPacketsBackendHandler.java index 3b02783cde4..55e509112e9 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/SQLPacketsBackendHandler.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/SQLPacketsBackendHandler.java @@ -17,16 +17,7 @@ package io.shardingsphere.proxy.backend.common; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - import com.google.common.collect.Lists; - import io.netty.channel.Channel; import io.netty.channel.pool.SimpleChannelPool; import io.shardingsphere.core.constant.DatabaseType; @@ -57,11 +48,20 @@ import io.shardingsphere.proxy.util.MySQLResultCache; import io.shardingsphere.proxy.util.SynchronizedFuture; import lombok.extern.slf4j.Slf4j; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + /** * SQL packets backend handler. * * @author wangkai * @author linjiaqi + * @author panjuan */ @Slf4j public final class SQLPacketsBackendHandler implements BackendHandler { @@ -208,7 +208,8 @@ public final class SQLPacketsBackendHandler implements BackendHandler { private CommandResponsePackets mergeDQLorDAL(final SQLStatement sqlStatement, final List<CommandResponsePackets> packets, final List<QueryResult> queryResults) { try { - mergedResult = MergeEngineFactory.newInstance(RuleRegistry.getInstance().getShardingRule(), queryResults, sqlStatement).merge(); + mergedResult = MergeEngineFactory.newInstance(RuleRegistry.getInstance().getShardingRule(), queryResults, + sqlStatement, RuleRegistry.getInstance().getShardingMetaData()).merge(); isMerged = true; } catch (final SQLException ex) { return new CommandResponsePackets(new ErrPacket(1, ex.getErrorCode(), "", ex.getSQLState(), ex.getMessage())); diff --git a/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/StatementExecuteBackendHandler.java b/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/StatementExecuteBackendHandler.java index 50a26c818e6..e1468ce99a7 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/StatementExecuteBackendHandler.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/StatementExecuteBackendHandler.java @@ -62,6 +62,7 @@ import java.util.concurrent.Future; * Statement execute backend handler. * * @author zhangyonglun + * @author panjuan */ @Getter @Setter @@ -214,7 +215,8 @@ public final class StatementExecuteBackendHandler implements BackendHandler { queryResults.add(mySQLPacketStatementExecuteQueryResult); } try { - mergedResult = MergeEngineFactory.newInstance(RuleRegistry.getInstance().getShardingRule(), queryResults, sqlStatement).merge(); + mergedResult = MergeEngineFactory.newInstance(RuleRegistry.getInstance().getShardingRule(), queryResults, + sqlStatement, RuleRegistry.getInstance().getShardingMetaData()).merge(); isMerged = true; } catch (final SQLException ex) { return new CommandResponsePackets(new ErrPacket(1, ex.getErrorCode(), "", ex.getSQLState(), ex.getMessage()));
['sharding-core/src/main/java/io/shardingsphere/core/merger/dal/DALMergeEngine.java', 'sharding-core/src/test/java/io/shardingsphere/core/merger/dal/DALMergeEngineTest.java', 'sharding-opentracing/src/test/java/io/shardingsphere/opentracing/MergeEventListenerTest.java', 'sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/SQLExecuteBackendHandler.java', 'sharding-jdbc/src/main/java/io/shardingsphere/core/jdbc/core/statement/ShardingStatement.java', 'sharding-core/src/main/java/io/shardingsphere/core/merger/dal/show/ShowTablesMergedResult.java', 'sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/SQLPacketsBackendHandler.java', 'sharding-core/src/test/java/io/shardingsphere/core/merger/dal/show/ShowTablesMergedResultTest.java', 'sharding-core/src/main/java/io/shardingsphere/core/metadata/ShardingMetaData.java', 'sharding-core/src/test/java/io/shardingsphere/core/merger/MergeEngineFactoryTest.java', 'sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/StatementExecuteBackendHandler.java', 'sharding-jdbc/src/main/java/io/shardingsphere/core/jdbc/core/statement/ShardingPreparedStatement.java', 'sharding-core/src/main/java/io/shardingsphere/core/merger/MergeEngineFactory.java']
{'.java': 13}
13
13
0
0
13
2,044,638
425,309
57,597
707
6,248
1,123
103
9
131
27
32
2
0
0
1970-01-01T00:25:29
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,537
apache/shardingsphere/863/858
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/858
https://github.com/apache/shardingsphere/pull/863
https://github.com/apache/shardingsphere/pull/863
1
fixes
sharding-proxy测试问题(中文乱码,应用死锁等)
Please answer these questions before submitting your issue. Thanks! 开源不易,我们希望将精力放在完成新功能和解决有价值的问题上,为了让大家的配合更具有效率,请填写以下列出的全部问题 ### Which version of Sharding-Sphere do you using?(您使用的Sharding-Sphere版本为?) windows 10 mysql5.5 sharding-proxy-3.0.0.M1 ### Expected behavior (您预期的结果是) 1、中文正常 2、能马上返回错误 3、shardingColumn大小写忽略 ### Actual behavior (实际运行的结果是) 1、中文乱码 2、应用死锁 3、shardingColumn需大小写一致 ### Steps to reproduce the behavior (可重现问题的操作步骤) 1、springboot配置了sharding-proxy的数据源,如下: spring.datasource.slave2.driver-class-name=com.mysql.jdbc.Driver spring.datasource.slave2.url=jdbc:mysql://127.0.0.1:3307/sharding_db?characterEncoding=utf8 spring.datasource.slave2.username=root spring.datasource.slave2.password=sa 在insert时,中文为乱码。(不用sharding-proxy正常) 不知道还需要在哪里配置? 2、insert插入时shardingColumn在config.yaml中无法获取到dataSources,应用死锁。 3、shardingColumn需要严格大小写一致,实际上有些数据库是不区分大小写。 ### Please provide the reproduce example codes (such as github link),otherwise we will label the issue as Invalid and close it.(为了节省复现问题的时间,请务必提供可重现的代码,否则我们会将issue直接标记为invalid并关闭) Code should based on https://github.com/sharding-sphere/sharding-sphere-example (代码请基于 https://github.com/sharding-sphere/sharding-sphere-example)
fced903fce40658b21237dad6e0ae82ed73e7430
d7464a4458805d782e1b80b917bf46008b91fb22
https://github.com/apache/shardingsphere/compare/fced903fce40658b21237dad6e0ae82ed73e7430...d7464a4458805d782e1b80b917bf46008b91fb22
diff --git a/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/SQLExecuteBackendHandler.java b/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/SQLExecuteBackendHandler.java index ade62d7cc16..8096c64f002 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/SQLExecuteBackendHandler.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/SQLExecuteBackendHandler.java @@ -106,7 +106,7 @@ public final class SQLExecuteBackendHandler implements BackendHandler { return executeForSharding(); } } catch (final Exception ex) { - return new CommandResponsePackets(new ErrPacket(1, 0, "", "", ex.getMessage())); + return new CommandResponsePackets(new ErrPacket(1, 0, "", "", "" + ex.getMessage())); } }
['sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/common/SQLExecuteBackendHandler.java']
{'.java': 1}
1
1
0
0
1
1,720,554
358,985
48,254
618
192
44
2
1
1,220
80
473
32
2
0
1970-01-01T00:25:27
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,538
apache/shardingsphere/756/750
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/750
https://github.com/apache/shardingsphere/pull/756
https://github.com/apache/shardingsphere/pull/756
1
fixes
Proxy raised an out of bound exception
Please answer these questions before submitting your issue. Thanks! 开源不易,我们希望将精力放在完成新功能和解决有价值的问题上,为了让大家的配合更具有效率,请填写以下列出的全部问题 ### Which version of Sharding-Jdbc do you using?(您使用的Sharding-Jdbc版本为?) dev ### Expected behavior (您预期的结果是) Read data correctly from the ByteBuf of sharding-proxy. ### Actual behavior (实际运行的结果是) [WARN ] 17:20:14.713 [nioEventLoopGroup-5-3] i.n.u.c.AbstractEventExecutor - A task raised an exception. Task: io.shardingjdbc.proxy.frontend.mysql.MySQLFrontendHandler$1@10d19d69 java.lang.IndexOutOfBoundsException: readerIndex(1040) + length(1) exceeds writerIndex(17): PooledUnsafeDirectByteBuf(ridx: 0, widx: 17, cap: 2048) at io.netty.buffer.AbstractByteBuf.checkReadableBytes0(AbstractByteBuf.java:1401) ~[netty-buffer-4.1.16.Final.jar:4.1.16.Final] at io.netty.buffer.AbstractByteBuf.readByte(AbstractByteBuf.java:707) ~[netty-buffer-4.1.16.Final.jar:4.1.16.Final] at io.shardingjdbc.proxy.transport.mysql.packet.MySQLPacketPayload.readInt1(MySQLPacketPayload.java:51) ~[classes/:na] at io.shardingjdbc.proxy.frontend.mysql.MySQLFrontendHandler$1.run(MySQLFrontendHandler.java:69) ~[classes/:na] at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163) ~[netty-common-4.1.16.Final.jar:4.1.16.Final] at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:403) [netty-common-4.1.16.Final.jar:4.1.16.Final] at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:463) [netty-transport-4.1.16.Final.jar:4.1.16.Final] at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858) [netty-common-4.1.16.Final.jar:4.1.16.Final] at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:138) [netty-common-4.1.16.Final.jar:4.1.16.Final] at java.lang.Thread.run(Thread.java:748) [na:1.8.0_162] ### Steps to reproduce the behavior (可重现问题的操作步骤) This Exception bust randomly, but not difficult to be reproduced by continuously send message to sharding-proxy for not a very long time. ### Please provide the reproduce example codes (such as github link),otherwise we will label the issue as Invalid and close it.(为了节省复现问题的时间,请务必提供可重现的代码,否则我们会将issue直接标记为invalid并关闭) https://github.com/shardingjdbc/sharding-proxy-example Code should based on https://github.com/shardingjdbc/sharding-jdbc-example (代码请基于 https://github.com/shardingjdbc/sharding-jdbc-example)
11f147fc98d1b47154de46127e26acf37f2566f0
f2434d32400826483f11f985fe072c1e583c93d2
https://github.com/apache/shardingsphere/compare/11f147fc98d1b47154de46127e26acf37f2566f0...f2434d32400826483f11f985fe072c1e583c93d2
diff --git a/sharding-proxy/src/main/java/io/shardingjdbc/proxy/backend/common/SQLExecuteBackendHandler.java b/sharding-proxy/src/main/java/io/shardingjdbc/proxy/backend/common/SQLExecuteBackendHandler.java index f146fbeb129..1bbbc95a67b 100644 --- a/sharding-proxy/src/main/java/io/shardingjdbc/proxy/backend/common/SQLExecuteBackendHandler.java +++ b/sharding-proxy/src/main/java/io/shardingjdbc/proxy/backend/common/SQLExecuteBackendHandler.java @@ -58,6 +58,8 @@ import java.util.List; */ public final class SQLExecuteBackendHandler implements BackendHandler { + private static final Integer FETCH_ONE_ROW_A_TIME = Integer.MIN_VALUE; + private final String sql; private final StatementRoutingEngine routingEngine; @@ -116,7 +118,7 @@ public final class SQLExecuteBackendHandler implements BackendHandler { Connection connection = dataSource.getConnection(); connections.add(connection); Statement statement = connection.createStatement(); - statement.setFetchSize(Integer.MIN_VALUE); + statement.setFetchSize(FETCH_ONE_ROW_A_TIME); resultSets.add(statement.executeQuery(sql)); return getQueryDatabaseProtocolPackets(); } catch (final SQLException ex) { @@ -226,7 +228,7 @@ public final class SQLExecuteBackendHandler implements BackendHandler { return mergeDML(headPackets); } if (SQLType.DQL == sqlStatement.getType()) { - return mergeDQLorDAL(sqlStatement, packets); + return mergeDQL(sqlStatement, packets); } return packets.get(0); } @@ -242,7 +244,7 @@ public final class SQLExecuteBackendHandler implements BackendHandler { return new CommandResponsePackets(new OKPacket(1, affectedRows, 0, StatusFlag.SERVER_STATUS_AUTOCOMMIT.getValue(), 0, "")); } - private CommandResponsePackets mergeDQLorDAL(final SQLStatement sqlStatement, final List<CommandResponsePackets> packets) { + private CommandResponsePackets mergeDQL(final SQLStatement sqlStatement, final List<CommandResponsePackets> packets) { List<QueryResult> queryResults = new ArrayList<>(packets.size()); for (int i = 0; i < packets.size(); i++) { // TODO replace to a common PacketQueryResult diff --git a/sharding-proxy/src/main/java/io/shardingjdbc/proxy/backend/common/StatementExecuteBackendHandler.java b/sharding-proxy/src/main/java/io/shardingjdbc/proxy/backend/common/StatementExecuteBackendHandler.java index a98defd416d..80fb98fe5be 100644 --- a/sharding-proxy/src/main/java/io/shardingjdbc/proxy/backend/common/StatementExecuteBackendHandler.java +++ b/sharding-proxy/src/main/java/io/shardingjdbc/proxy/backend/common/StatementExecuteBackendHandler.java @@ -61,6 +61,8 @@ import java.util.List; */ public final class StatementExecuteBackendHandler implements BackendHandler { + private static final Integer FETCH_ONE_ROW_A_TIME = Integer.MIN_VALUE; + private final List<PreparedStatementParameter> preparedStatementParameters; private final PreparedStatementRoutingEngine routingEngine; @@ -137,7 +139,7 @@ public final class StatementExecuteBackendHandler implements BackendHandler { Connection connection = dataSource.getConnection(); connections.add(connection); PreparedStatement preparedStatement = connection.prepareStatement(sql); - preparedStatement.setFetchSize(Integer.MIN_VALUE); + preparedStatement.setFetchSize(FETCH_ONE_ROW_A_TIME); setJDBCPreparedStatementParameters(preparedStatement); resultSets.add(preparedStatement.executeQuery()); return getQueryDatabaseProtocolPackets(); @@ -264,7 +266,7 @@ public final class StatementExecuteBackendHandler implements BackendHandler { return mergeDML(headPackets); } if (SQLType.DQL == sqlStatement.getType()) { - return mergeDQLorDAL(sqlStatement, packets); + return mergeDQL(sqlStatement, packets); } return packets.get(0); } @@ -280,7 +282,7 @@ public final class StatementExecuteBackendHandler implements BackendHandler { return new CommandResponsePackets(new OKPacket(1, affectedRows, 0, StatusFlag.SERVER_STATUS_AUTOCOMMIT.getValue(), 0, "")); } - private CommandResponsePackets mergeDQLorDAL(final SQLStatement sqlStatement, final List<CommandResponsePackets> packets) { + private CommandResponsePackets mergeDQL(final SQLStatement sqlStatement, final List<CommandResponsePackets> packets) { List<QueryResult> queryResults = new ArrayList<>(packets.size()); for (int i = 0; i < packets.size(); i++) { // TODO replace to a common PacketQueryResult diff --git a/sharding-proxy/src/main/java/io/shardingjdbc/proxy/transport/mysql/codec/MySQLPacketCodec.java b/sharding-proxy/src/main/java/io/shardingjdbc/proxy/transport/mysql/codec/MySQLPacketCodec.java index 7ef4c7f95b2..27b73ecf622 100644 --- a/sharding-proxy/src/main/java/io/shardingjdbc/proxy/transport/mysql/codec/MySQLPacketCodec.java +++ b/sharding-proxy/src/main/java/io/shardingjdbc/proxy/transport/mysql/codec/MySQLPacketCodec.java @@ -45,11 +45,7 @@ public final class MySQLPacketCodec extends PacketCodec<MySQLPacket> { in.resetReaderIndex(); return; } - if (readableBytes > realPacketLength) { - out.add(in.readRetainedSlice(payloadLength + MySQLPacket.SEQUENCE_LENGTH)); - return; - } - out.add(in); + out.add(in.readRetainedSlice(payloadLength + MySQLPacket.SEQUENCE_LENGTH)); } @Override
['sharding-proxy/src/main/java/io/shardingjdbc/proxy/backend/common/StatementExecuteBackendHandler.java', 'sharding-proxy/src/main/java/io/shardingjdbc/proxy/backend/common/SQLExecuteBackendHandler.java', 'sharding-proxy/src/main/java/io/shardingjdbc/proxy/transport/mysql/codec/MySQLPacketCodec.java']
{'.java': 3}
3
3
0
0
3
1,653,809
344,369
46,759
598
1,412
282
22
3
2,479
148
756
32
3
0
1970-01-01T00:25:24
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,540
apache/shardingsphere/649/648
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/648
https://github.com/apache/shardingsphere/pull/649
https://github.com/apache/shardingsphere/pull/649
1
fixes
SelectItem should be annotated by EqualsAndHashCode
I found that there are several subclasses implement `SelectItem`. They are used as container elements in `Set` collection(io.shardingjdbc.core.parsing.parser.sql.dql.select.SelectStatement#items), but I only see the `AggregationSelectItem` has `EqualsAndHashCode` annotation. the others are forgotten?
cb17dc3e406c2d2a7b8d83f2b825a625031e5eb0
4ae5879be1359a452b77b2cacb70b43486e4b148
https://github.com/apache/shardingsphere/compare/cb17dc3e406c2d2a7b8d83f2b825a625031e5eb0...4ae5879be1359a452b77b2cacb70b43486e4b148
diff --git a/sharding-jdbc-core/src/main/java/io/shardingjdbc/core/parsing/parser/context/selectitem/CommonSelectItem.java b/sharding-jdbc-core/src/main/java/io/shardingjdbc/core/parsing/parser/context/selectitem/CommonSelectItem.java index 0014848d29c..aafe561f10c 100644 --- a/sharding-jdbc-core/src/main/java/io/shardingjdbc/core/parsing/parser/context/selectitem/CommonSelectItem.java +++ b/sharding-jdbc-core/src/main/java/io/shardingjdbc/core/parsing/parser/context/selectitem/CommonSelectItem.java @@ -18,6 +18,7 @@ package io.shardingjdbc.core.parsing.parser.context.selectitem; import com.google.common.base.Optional; +import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.ToString; @@ -29,6 +30,7 @@ import lombok.ToString; */ @RequiredArgsConstructor @Getter +@EqualsAndHashCode @ToString public final class CommonSelectItem implements SelectItem { diff --git a/sharding-jdbc-core/src/main/java/io/shardingjdbc/core/parsing/parser/context/selectitem/StarSelectItem.java b/sharding-jdbc-core/src/main/java/io/shardingjdbc/core/parsing/parser/context/selectitem/StarSelectItem.java index 21ddd52e409..629b6df34a7 100644 --- a/sharding-jdbc-core/src/main/java/io/shardingjdbc/core/parsing/parser/context/selectitem/StarSelectItem.java +++ b/sharding-jdbc-core/src/main/java/io/shardingjdbc/core/parsing/parser/context/selectitem/StarSelectItem.java @@ -19,6 +19,7 @@ package io.shardingjdbc.core.parsing.parser.context.selectitem; import io.shardingjdbc.core.parsing.lexer.token.Symbol; import com.google.common.base.Optional; +import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.ToString; @@ -30,6 +31,7 @@ import lombok.ToString; */ @RequiredArgsConstructor @Getter +@EqualsAndHashCode @ToString public final class StarSelectItem implements SelectItem {
['sharding-jdbc-core/src/main/java/io/shardingjdbc/core/parsing/parser/context/selectitem/StarSelectItem.java', 'sharding-jdbc-core/src/main/java/io/shardingjdbc/core/parsing/parser/context/selectitem/CommonSelectItem.java']
{'.java': 2}
2
2
0
0
2
1,455,385
302,756
41,047
533
106
18
4
2
303
31
65
1
0
0
1970-01-01T00:25:21
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,541
apache/shardingsphere/583/577
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/577
https://github.com/apache/shardingsphere/pull/583
https://github.com/apache/shardingsphere/pull/583
1
fixes
Support new line for YAML configuration
Please answer these questions before submitting your issue. Thanks! 获取数据源换行 String dataSources = propertyResolver.getProperty("names"); 建议 OrchestrationSpringBootConfiguration文件 line77 String dataSources = propertyResolver.getProperty("names"); 加一个去空格处理 改为 String dataSources = propertyResolver.getProperty("names").trim(); ### Which version of Sharding-Jdbc do you using? ### Expected behavior ### Actual behavior ### Steps to reproduce the behavior ### Please provide the reproduce example codes (such as github link) Code should based on https://github.com/shardingjdbc/sharding-jdbc-example
35521a2da3cb5242891ef0d0d5ecbec154845330
4c0b501c46680be8727a007f0df960cced52bb2a
https://github.com/apache/shardingsphere/compare/35521a2da3cb5242891ef0d0d5ecbec154845330...4c0b501c46680be8727a007f0df960cced52bb2a
diff --git a/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/main/java/io/shardingjdbc/orchestration/spring/boot/OrchestrationSpringBootConfiguration.java b/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/main/java/io/shardingjdbc/orchestration/spring/boot/OrchestrationSpringBootConfiguration.java index c275da9b59b..1b598f8b581 100644 --- a/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/main/java/io/shardingjdbc/orchestration/spring/boot/OrchestrationSpringBootConfiguration.java +++ b/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/main/java/io/shardingjdbc/orchestration/spring/boot/OrchestrationSpringBootConfiguration.java @@ -32,6 +32,7 @@ import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; +import org.springframework.util.StringUtils; import javax.sql.DataSource; import java.sql.SQLException; @@ -75,15 +76,17 @@ public class OrchestrationSpringBootConfiguration implements EnvironmentAware { private void setDataSourceMap(final Environment environment) { RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(environment, "sharding.jdbc.datasource."); String dataSources = propertyResolver.getProperty("names"); + Preconditions.checkState(!StringUtils.isEmpty(dataSources), "Wrong datasource properties, empty datasource !"); + dataSources = dataSources.trim(); for (String each : dataSources.split(",")) { - try { - Map<String, Object> dataSourceProps = propertyResolver.getSubProperties(each + "."); - Preconditions.checkState(!dataSourceProps.isEmpty(), "Wrong datasource properties!"); - DataSource dataSource = DataSourceUtil.getDataSource(dataSourceProps.get("type").toString(), dataSourceProps); - dataSourceMap.put(each, dataSource); - } catch (final ReflectiveOperationException ex) { - throw new ShardingJdbcException("Can't find datasource type!", ex); - } + try { + Map<String, Object> dataSourceProps = propertyResolver.getSubProperties(each + "."); + Preconditions.checkState(!dataSourceProps.isEmpty(), String.format("Wrong datasource [%s] properties!", each)); + DataSource dataSource = DataSourceUtil.getDataSource(dataSourceProps.get("type").toString(), dataSourceProps); + dataSourceMap.put(each, dataSource); + } catch (final ReflectiveOperationException ex) { + throw new ShardingJdbcException("Can't find datasource type!", ex); + } } } }
['sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/main/java/io/shardingjdbc/orchestration/spring/boot/OrchestrationSpringBootConfiguration.java']
{'.java': 1}
1
1
0
0
1
1,264,756
260,238
35,510
468
1,334
230
19
1
638
63
133
28
1
0
1970-01-01T00:25:17
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,509
apache/shardingsphere/1613/1603
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1603
https://github.com/apache/shardingsphere/pull/1613
https://github.com/apache/shardingsphere/pull/1613
1
fixes
After the integration of mybatis, mybatis Mapper is loop dead
## Bug Report **As a result, after integration with mybatis, some special operations lead to an endless cycle of mybatis** ### Which version of Sharding-Sphere did you use? ```xml <dependency> <groupId>io.shardingsphere</groupId> <artifactId>sharding-jdbc-spring-boot-starter</artifactId> <version>3.0.0</version> </dependency> ``` ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-JDBC ### Expected behavior **It doesn't create an infinite loop** ``` DEBUG org.mapper.UserRoleMapper.insertBySelect2 - ==> Preparing: INSERT INTO `user_role`(`username`, `role_name`) VALUES (?, ?) INFO Sharding-Sphere-SQL - Rule Type: master-slave INFO Sharding-Sphere-SQL - SQL: INSERT INTO `user_role`(`username`, `role_name`) VALUES (?, ?) ::: DataSources: write DEBUG org.mapper.UserRoleMapper.insertBySelect2 - ==> Parameters: write(String), write(String) DEBUG org.mapper.UserRoleMapper.insertBySelect2 - <== Updates: 1 ...... The database operation completes printing other business logs ``` ### Actual behavior ``` DEBUG org.mapper.UserRoleMapper.insertBySelect2 - ==> Preparing: INSERT INTO `user_role`(`username`, `role_name`) VALUES (?, ?) INFO Sharding-Sphere-SQL - Rule Type: master-slave INFO Sharding-Sphere-SQL - SQL: INSERT INTO `user_role`(`username`, `role_name`) VALUES (?, ?) ::: DataSources: write DEBUG org.mapper.UserRoleMapper.insertBySelect2 - ==> Parameters: write(String), write(String) DEBUG org.mapper.UserRoleMapper.insertBySelect2 - <== Updates: 1 DEBUG org.mapper.UserRoleMapper.insertBySelect2 - <== Updates: 1 DEBUG org.mapper.UserRoleMapper.insertBySelect2 - <== Updates: 1 DEBUG org.mapper.UserRoleMapper.insertBySelect2 - <== Updates: 1 DEBUG org.mapper.UserRoleMapper.insertBySelect2 - <== Updates: 1 DEBUG org.mapper.UserRoleMapper.insertBySelect2 - <== Updates: 1 DEBUG org.mapper.UserRoleMapper.insertBySelect2 - <== Updates: 1 DEBUG org.mapper.UserRoleMapper.insertBySelect2 - <== Updates: 1 DEBUG org.mapper.UserRoleMapper.insertBySelect2 - <== Updates: 1 DEBUG org.mapper.UserRoleMapper.insertBySelect2 - <== Updates: 1 DEBUG org.mapper.UserRoleMapper.insertBySelect2 - <== Updates: 1 DEBUG org.mapper.UserRoleMapper.insertBySelect2 - <== Updates: 1 ......Loop printing ``` ### Reason analyze (If you can) `java.sql.Statement#getMoreResults()`The interface returns false as specified below: ```java // io.shardingsphere.shardingjdbc.jdbc.adapter.AbstractStatementAdapter @Override public final boolean getMoreResults() { return false; } @Override public final boolean getMoreResults(final int current) { return false; } ``` **As a result, after integration with mybatis, some special operations cause mybatis to generate a dead loop. The position of the dead loop of mybatis code is as follows through debugging:** ```java // org.apache.ibatis.executor.resultset.DefaultResultSetHandler.java private ResultSetWrapper getFirstResultSet(Statement stmt) throws SQLException { ResultSet rs = stmt.getResultSet(); while (rs == null) { // move forward to get the first resultset in case the driver // doesn't return the resultset as the first result (HSQLDB 2.1) if (stmt.getMoreResults()) { rs = stmt.getResultSet(); } else { // Note: using sharding- JDBC, stmt.getupdatecount () is always greater than 1 (resulting in an infinite loop), // But using mysql's native driver returns -1 if (stmt.getUpdateCount() == -1) { // no more results. Must be no resultset break; } } } return rs != null ? new ResultSetWrapper(rs, configuration) : null; } ``` Use mybatis to reproduce the code: ```java @Repository @Mapper public interface UserRoleMapper extends BaseMapper<UserRole> { // Define update database statements in @select @Select("INSERT INTO `user_role`(`username`, `role_name`) VALUES (#{userRole.username}, #{userRole.roleName})") Integer insertBySelect(@Param("userRole") UserRole userRole); } ``` **My current solution** ``` java // Modify the io.shardingsphere.shardingjdbc.jdbc.core.statement.MasterSlavePreparedStatement @Override public final boolean getMoreResults() { return routedStatements.iterator().next().getMoreResults(); } ``` **After the test is modified in this way, online problems can be solved, but I do not know whether it will bring about other problems. I hope the official support (online is in use urgently).**
542720553f1bf604ba1133c8823373635b73000a
a24e6940bc8deb93667004987f55857f347692b4
https://github.com/apache/shardingsphere/compare/542720553f1bf604ba1133c8823373635b73000a...a24e6940bc8deb93667004987f55857f347692b4
diff --git a/sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/AbstractStatementAdapter.java b/sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/AbstractStatementAdapter.java index 246ea05edf2..ba72069b3c6 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/AbstractStatementAdapter.java +++ b/sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/AbstractStatementAdapter.java @@ -32,6 +32,7 @@ import java.util.Collection; * * @author zhangliang * @author gaohongtao + * @author yangyi */ @RequiredArgsConstructor public abstract class AbstractStatementAdapter extends AbstractUnsupportedOperationStatement { @@ -158,8 +159,12 @@ public abstract class AbstractStatementAdapter extends AbstractUnsupportedOperat } @Override - public final boolean getMoreResults() { - return false; + public final boolean getMoreResults() throws SQLException { + boolean result = false; + for (Statement each : getRoutedStatements()) { + result = each.getMoreResults(); + } + return result; } @Override
['sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/AbstractStatementAdapter.java']
{'.java': 1}
1
1
0
0
1
2,433,453
508,626
67,502
913
320
62
9
1
4,683
490
1,120
109
0
7
1970-01-01T00:25:44
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,506
apache/shardingsphere/1666/1658
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1658
https://github.com/apache/shardingsphere/pull/1666
https://github.com/apache/shardingsphere/pull/1666
1
fixes
SS 3.1.0.M1 count sql throw an error,3.1.0 works well
## Bug Report **For English only**, other languages will not accept. With the Configration #1653 The sql throw an exception with 3.1.0.M1 and works well with 3.0.0 ```sql SELECT COUNT(1) FROM ( SELECT r.`channel` as `channel_code`, r.`channel_name` as `channel_name`, COUNT(r.id) `total_cnt`, COUNT(r.connect_flag = "Y") `connected_cnt` FROM record_callin r LEFT JOIN sys_org_tree_rel tree ON tree.teamid = r.teamid LEFT JOIN sys_user u ON u.brokerid = r.brokerid where r.create_time >= '2018-01-01 00:00:00' and r.create_time <= '2019-01-01 00:00:00' GROUP BY r.`channel` ) TOTAL ``` this throws an error: ``` Caused by: java.lang.IllegalStateException: DQL must have sharding column with subquery. at com.google.common.base.Preconditions.checkState(Preconditions.java:444) ~[guava-20.0.jar:na] at io.shardingsphere.core.routing.router.sharding.ParsingSQLRouter.checkAndMergeShardingValue(ParsingSQLRouter.java:157) ~[sharding-core-3.1.0.M1.jar:na] at io.shardingsphere.core.routing.router.sharding.ParsingSQLRouter.route(ParsingSQLRouter.java:127) ~[sharding-core-3.1.0.M1.jar:na] at io.shardingsphere.core.routing.PreparedStatementRoutingEngine.route(PreparedStatementRoutingEngine.java:66) ~[sharding-core-3.1.0.M1.jar:na] at io.shardingsphere.shardingjdbc.jdbc.core.statement.ShardingPreparedStatement.sqlRoute(ShardingPreparedStatement.java:241) ~[sharding-jdbc-core-3.1.0.M1.jar:na] at io.shardingsphere.shardingjdbc.jdbc.core.statement.ShardingPreparedStatement.executeQuery(ShardingPreparedStatement.java:111) ~[sharding-jdbc-core-3.1.0.M1.jar:na] at com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor.queryTotal(PaginationInterceptor.java:207) ~[mybatis-plus-extension-3.0.6.jar:3.0.6] ... 116 common frames omitted ``` #1653 reason is I used single quote mark with column alias but this issue reason is different
c6acdfeee0bc069b032836931008a24b26460143
b8df689e73bf6c187bd8c90515184ff158fc815a
https://github.com/apache/shardingsphere/compare/c6acdfeee0bc069b032836931008a24b26460143...b8df689e73bf6c187bd8c90515184ff158fc815a
diff --git a/sharding-core/src/main/java/io/shardingsphere/core/routing/router/sharding/ParsingSQLRouter.java b/sharding-core/src/main/java/io/shardingsphere/core/routing/router/sharding/ParsingSQLRouter.java index 56034c9f339..c6fe888490b 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/routing/router/sharding/ParsingSQLRouter.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/routing/router/sharding/ParsingSQLRouter.java @@ -149,6 +149,9 @@ public final class ParsingSQLRouter implements ShardingRouter { if (selectStatement.getSubQueryStatements().isEmpty()) { return; } + if (selectStatement.getTables().isEmpty()) { + return; + } for (AndCondition each : sqlStatement.getConditions().getOrCondition().getAndConditions()) { for (Condition eachCondition : each.getConditions()) { Preconditions.checkState(ShardingOperator.EQUAL == eachCondition.getOperator(), "DQL only support '=' with subquery."); diff --git a/sharding-core/src/test/java/io/shardingsphere/core/routing/type/standard/StandardRoutingEngineForSubQueryTest.java b/sharding-core/src/test/java/io/shardingsphere/core/routing/type/standard/StandardRoutingEngineForSubQueryTest.java index 1f15d291453..d7cb21b876a 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/routing/type/standard/StandardRoutingEngineForSubQueryTest.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/routing/type/standard/StandardRoutingEngineForSubQueryTest.java @@ -67,6 +67,15 @@ public final class StandardRoutingEngineForSubQueryTest { assertSubquery(sql, parameters); } + @Test + public void assertUnshardingTalbe() { + String sql = "select (select max(id) from t_user b where b.id = ?) from t_user a where id = ? "; + List<Object> parameters = new LinkedList<>(); + parameters.add(1); + parameters.add(1); + assertSubquery(sql, parameters); + } + public void assertSubquery(final String sql, final List<Object> parameters) { ShardingRule shardingRule = createShardingRule(); ShardingTableMetaData shardingTableMetaData = buildShardingTableMetaData();
['sharding-core/src/main/java/io/shardingsphere/core/routing/router/sharding/ParsingSQLRouter.java', 'sharding-core/src/test/java/io/shardingsphere/core/routing/type/standard/StandardRoutingEngineForSubQueryTest.java']
{'.java': 2}
2
2
0
0
2
2,432,926
508,593
67,455
915
85
16
3
1
1,989
139
545
41
0
2
1970-01-01T00:25:45
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,491
apache/shardingsphere/2210/2193
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2193
https://github.com/apache/shardingsphere/pull/2210
https://github.com/apache/shardingsphere/pull/2210
1
fix
Table doesn't exist when sharding value in different datasource with in expression
## Table doesn't exist when sharding value in different data source with in expression ### Which version of ShardingSphere did you use? 4.0.0-RC1 ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-JDBC ### Expected behavior 21:31:45.941 [main] INFO ShardingSphere-SQL - Actual SQL: ds_0 ::: select * from ts_order_0001 where id = 1 or id = 3 21:31:45.941 [main] INFO ShardingSphere-SQL - Actual SQL: ds_1 ::: select * from ts_order_0003 where id = 1 or id = 3 ### Actual behavior 21:08:30.000 [main] INFO ShardingSphere-SQL - Actual SQL: ds_0 ::: select * from ts_order_0001 where id in (1, 3) 21:08:30.000 [main] INFO ShardingSphere-SQL - Actual SQL: ds_0 ::: select * from ts_order_0003 where id in (1, 3) 21:08:30.000 [main] INFO ShardingSphere-SQL - Actual SQL: ds_1 ::: select * from ts_order_0001 where id in (1, 3) 21:08:30.000 [main] INFO ShardingSphere-SQL - Actual SQL: ds_1 ::: select * from ts_order_0003 where id in (1, 3) Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test_d_0.ts_order_0003' doesn't exist ### Reason analyze (If you can) ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc. dependency ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.9</version> </dependency> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>sharding-jdbc-core</artifactId> <version>4.0.0-RC1</version> </dependency> ``` sql ```sql create database test_d_0; create database test_d_1; CREATE TABLE test_d_0.`ts_order_0000` (`id` BIGINT NOT NULL AUTO_INCREMENT,PRIMARY KEY (`id`)); CREATE TABLE test_d_0.`ts_order_0001` (`id` BIGINT NOT NULL AUTO_INCREMENT,PRIMARY KEY (`id`)); CREATE TABLE test_d_1.`ts_order_0002` (`id` BIGINT NOT NULL AUTO_INCREMENT,PRIMARY KEY (`id`)); CREATE TABLE test_d_1.`ts_order_0003` (`id` BIGINT NOT NULL AUTO_INCREMENT,PRIMARY KEY (`id`)); ``` Java Code ```java BufferedReader reader = new BufferedReader(new InputStreamReader(ShardingDataSourceTest.class .getResourceAsStream("/sharding-config-example-1.yaml"), "utf-8")); StringBuffer sb = new StringBuffer(); CharBuffer charBuffer = CharBuffer.allocate(32); for (int count = reader.read(charBuffer); count > 0; count = reader.read(charBuffer)) { sb.append(charBuffer.flip()); } DataSource dataSource = YamlShardingDataSourceFactory.createDataSource(sb.toString().getBytes("utf-8")); Connection connection = dataSource.getConnection(); Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("select * from ts_order where id in (1, 3)"); ``` sharding rule sharding-config-example-1.yaml ```yaml dataSources: ds_0: !!com.alibaba.druid.pool.DruidDataSource driverClassName: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/test_d_0 username: root password: root135 ds_1: !!com.alibaba.druid.pool.DruidDataSource driverClassName: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/test_d_1 username: root password: root135 shardingRule: tables: ts_order: actualDataNodes: ds_0.ts_order_0000,ds_0.ts_order_0001,ds_1.ts_order_0002,ds_1.ts_order_0003 databaseStrategy: inline: shardingColumn: id algorithmExpression: ds_${new BigDecimal(id).abs().divideAndRemainder(4)[1].longValue().intdiv(2)} tableStrategy: inline: shardingColumn: id algorithmExpression: ts_order_${String.format("%04d",new BigDecimal(id).abs().divideAndRemainder(4)[1].longValue())} props: sql.show: true ``` ### Example codes for reproduce this issue (such as a github link).
2069f0867b0c159d762616bb7f7b22ca75295b86
518987aeda09840157d996d71c72ee3daceb6726
https://github.com/apache/shardingsphere/compare/2069f0867b0c159d762616bb7f7b22ca75295b86...518987aeda09840157d996d71c72ee3daceb6726
diff --git a/sharding-core/sharding-core-route/src/main/java/org/apache/shardingsphere/core/route/type/standard/StandardRoutingEngine.java b/sharding-core/sharding-core-route/src/main/java/org/apache/shardingsphere/core/route/type/standard/StandardRoutingEngine.java index 22091dd7b5b..a182840ba4b 100644 --- a/sharding-core/sharding-core-route/src/main/java/org/apache/shardingsphere/core/route/type/standard/StandardRoutingEngine.java +++ b/sharding-core/sharding-core-route/src/main/java/org/apache/shardingsphere/core/route/type/standard/StandardRoutingEngine.java @@ -42,9 +42,11 @@ import org.apache.shardingsphere.core.strategy.route.value.RouteValue; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; +import java.util.Set; /** * Standard routing engine. @@ -180,7 +182,7 @@ public final class StandardRoutingEngine implements RoutingEngine { for (String each : routedDataSources) { result.addAll(routeTables(tableRule, each, tableShardingValues)); } - return result; + return removeNonExistNodes(result, tableRule); } private Collection<String> routeDataSources(final TableRule tableRule, final List<RouteValue> databaseShardingValues) { @@ -205,6 +207,17 @@ public final class StandardRoutingEngine implements RoutingEngine { return result; } + private Collection<DataNode> removeNonExistNodes(final Collection<DataNode> routedDataNodes, final TableRule tableRule) { + Collection<DataNode> result = new LinkedList<>(); + Set<DataNode> actualDataNodeSet = new HashSet<>(tableRule.getActualDataNodes()); + for (DataNode each : routedDataNodes) { + if (actualDataNodeSet.contains(each)) { + result.add(each); + } + } + return result; + } + private void reviseInsertOptimizeResult(final ShardingCondition shardingCondition, final Collection<DataNode> dataNodes) { if (sqlStatement instanceof InsertStatement) { for (InsertOptimizeResultUnit each : optimizeResult.getInsertOptimizeResult().get().getUnits()) {
['sharding-core/sharding-core-route/src/main/java/org/apache/shardingsphere/core/route/type/standard/StandardRoutingEngine.java']
{'.java': 1}
1
1
0
0
1
3,226,481
652,129
81,744
1,104
605
120
15
1
3,943
367
1,060
102
0
4
1970-01-01T00:25:55
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,521
apache/shardingsphere/1279/1265
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1265
https://github.com/apache/shardingsphere/pull/1279
https://github.com/apache/shardingsphere/pull/1279
1
fixes
RoundRobinMasterSlaveLoadBalanceAlgorithm throw an ArrayIndexOutOfBoundsException
For English only, other languages we will close it directly. Please answer these questions before submitting your issue. Thanks! Before submit a new issue, please check existed issue first, to make sure your issue is not a duplicated one. ### Which version of Sharding-Sphere do you using? 3.0.0.M3 ### Which project do you using? Sharding-JDBC or Sharding-Proxy? Sharding-JDBC ### Expected behavior RoundRobinMasterSlaveLoadBalance always be OK ### Actual behavior after roundrobin Integer.MAX_VALUE times, will throw an ArrayIndexOutOfBoundsException. ### Reason analyze the AtomicInteger's getAndIncrement() may produce an negative numbers. ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc ### For bug report, please *MUST* provide the reproduce example codes (such as a github link).
23db595c3ad6aec93e66dbf7a8680270cb97c903
89d9049b2b8d0e04e35056fec2a89567dca202d0
https://github.com/apache/shardingsphere/compare/23db595c3ad6aec93e66dbf7a8680270cb97c903...89d9049b2b8d0e04e35056fec2a89567dca202d0
diff --git a/sharding-core/src/main/java/io/shardingsphere/core/api/algorithm/masterslave/RoundRobinMasterSlaveLoadBalanceAlgorithm.java b/sharding-core/src/main/java/io/shardingsphere/core/api/algorithm/masterslave/RoundRobinMasterSlaveLoadBalanceAlgorithm.java index 955c8c71b03..fe7effb48b0 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/api/algorithm/masterslave/RoundRobinMasterSlaveLoadBalanceAlgorithm.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/api/algorithm/masterslave/RoundRobinMasterSlaveLoadBalanceAlgorithm.java @@ -35,6 +35,6 @@ public final class RoundRobinMasterSlaveLoadBalanceAlgorithm implements MasterSl AtomicInteger count = COUNT_MAP.containsKey(name) ? COUNT_MAP.get(name) : new AtomicInteger(0); COUNT_MAP.putIfAbsent(name, count); count.compareAndSet(slaveDataSourceNames.size(), 0); - return slaveDataSourceNames.get(count.getAndIncrement() % slaveDataSourceNames.size()); + return slaveDataSourceNames.get(Math.abs(count.getAndIncrement()) % slaveDataSourceNames.size()); } }
['sharding-core/src/main/java/io/shardingsphere/core/api/algorithm/masterslave/RoundRobinMasterSlaveLoadBalanceAlgorithm.java']
{'.java': 1}
1
1
0
0
1
2,268,581
472,633
63,891
819
203
36
2
1
890
121
188
25
0
0
1970-01-01T00:25:37
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,522
apache/shardingsphere/1200/1199
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1199
https://github.com/apache/shardingsphere/pull/1200
https://github.com/apache/shardingsphere/pull/1200
1
fixes
Lost the BinaryResultSetRowPacket when there's null value
For English only, other languages we will close it directly. Please answer these questions before submitting your issue. Thanks! ### Which version of Sharding-Sphere do you using? 3.0.0.M3 ### Which project do you using? Sharding-JDBC or Sharding-Proxy? Sharding-Proxy ### Expected behavior Return the BinaryResultSetRowPacket when there's null value. ### Actual behavior Lost the BinaryResultSetRowPacket when there's null value. ### Reason analyze Sharding-Proxy burst Exception when write binary protocol null value, althouth have already filled the nullBitmap correctly. ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc Use preparedStatement select a row which contains null value column. ### For bug report, please *MUST* provide the reproduce example codes (such as a github link). Official example.
2efe41281663926e9caef26e516714ae786a52fd
80b476acb749c64a9f0279f3fcf5f308277eee27
https://github.com/apache/shardingsphere/compare/2efe41281663926e9caef26e516714ae786a52fd...80b476acb749c64a9f0279f3fcf5f308277eee27
diff --git a/sharding-proxy/src/main/java/io/shardingsphere/proxy/transport/mysql/packet/command/query/binary/execute/BinaryProtocolValue.java b/sharding-proxy/src/main/java/io/shardingsphere/proxy/transport/mysql/packet/command/query/binary/execute/BinaryProtocolValue.java index 6579c517db2..c29bad6ef09 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/proxy/transport/mysql/packet/command/query/binary/execute/BinaryProtocolValue.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/proxy/transport/mysql/packet/command/query/binary/execute/BinaryProtocolValue.java @@ -91,6 +91,9 @@ public final class BinaryProtocolValue { * @param binaryData binary data to be written */ public void write(final Object binaryData) { + if (null == binaryData) { + return; + } switch (columnType) { case MYSQL_TYPE_STRING: case MYSQL_TYPE_VARCHAR: @@ -108,11 +111,7 @@ public final class BinaryProtocolValue { payload.writeStringLenenc(binaryData.toString()); break; case MYSQL_TYPE_LONGLONG: - if (binaryData instanceof BigDecimal) { - payload.writeInt8(((BigDecimal) binaryData).longValue()); - } else { - payload.writeInt8((Long) binaryData); - } + writeInt8(binaryData); break; case MYSQL_TYPE_LONG: case MYSQL_TYPE_INT24: @@ -143,4 +142,12 @@ public final class BinaryProtocolValue { throw new IllegalArgumentException(String.format("Cannot find MySQL type '%s' in column type when write binary protocol value", columnType)); } } + + private void writeInt8(final Object binaryData) { + if (binaryData instanceof BigDecimal) { + payload.writeInt8(((BigDecimal) binaryData).longValue()); + } else { + payload.writeInt8((Long) binaryData); + } + } } diff --git a/sharding-proxy/src/test/java/io/shardingsphere/proxy/transport/mysql/packet/command/query/binary/execute/BinaryResultSetRowPacketTest.java b/sharding-proxy/src/test/java/io/shardingsphere/proxy/transport/mysql/packet/command/query/binary/execute/BinaryResultSetRowPacketTest.java index 3b38ad5a6eb..af4f039c9c8 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/proxy/transport/mysql/packet/command/query/binary/execute/BinaryResultSetRowPacketTest.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/proxy/transport/mysql/packet/command/query/binary/execute/BinaryResultSetRowPacketTest.java @@ -39,13 +39,13 @@ public final class BinaryResultSetRowPacketTest { private MySQLPacketPayload payload; @Test - @Ignore public void assertWrite() { BinaryResultSetRowPacket actual = new BinaryResultSetRowPacket(1, 2, Arrays.<Object>asList("value", null), Arrays.asList(ColumnType.MYSQL_TYPE_STRING, ColumnType.MYSQL_TYPE_STRING)); assertThat(actual.getSequenceId(), is(1)); assertThat(actual.getData(), is(Arrays.<Object>asList("value", null))); actual.write(payload); - verify(payload, times(2)).writeInt1(0x00); + verify(payload).writeInt1(0x00); + verify(payload).writeInt1(0x08); verify(payload).writeStringLenenc("value"); } }
['sharding-proxy/src/test/java/io/shardingsphere/proxy/transport/mysql/packet/command/query/binary/execute/BinaryResultSetRowPacketTest.java', 'sharding-proxy/src/main/java/io/shardingsphere/proxy/transport/mysql/packet/command/query/binary/execute/BinaryProtocolValue.java']
{'.java': 2}
2
2
0
0
2
2,251,726
469,108
63,204
805
614
112
17
1
903
123
186
24
0
0
1970-01-01T00:25:35
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,523
apache/shardingsphere/1196/1191
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1191
https://github.com/apache/shardingsphere/pull/1196
https://github.com/apache/shardingsphere/pull/1196
1
fixes
Proxy blocked when client connect and close repeatly
For English only, other languages we will close it directly. Please answer these questions before submitting your issue. Thanks! ### Which version of Sharding-Sphere do you using? 3.0.0.M3 ### Which project do you using? Sharding-JDBC or Sharding-Proxy? Sharding-Proxy ### Expected behavior High Availability. ### Actual behavior Proxy blocked when client connect and close repeatly. ### Reason analyze Only when a client close the connection meanwhile a query is not finish in this connection will triger this bug. When a frontend connection is closed the connection will become not writable, this cause MySQLFrontendHandler wait and never jump out the loop. ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc Execute a slow SQL then close the connection until the connections is used up. ### For bug report, please *MUST* provide the reproduce example codes (such as a github link). Official example.
bddd0064727e6adb20033cb2d0e3f48a280f7bc3
aa6833d268eb76055dbc368d05033264fd09a5a7
https://github.com/apache/shardingsphere/compare/bddd0064727e6adb20033cb2d0e3f48a280f7bc3...aa6833d268eb76055dbc368d05033264fd09a5a7
diff --git a/sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/ShardingProxy.java b/sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/ShardingProxy.java index c55bbe06705..649a304923d 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/ShardingProxy.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/ShardingProxy.java @@ -98,7 +98,7 @@ public final class ShardingProxy { } private void groupsEpoll(final ServerBootstrap bootstrap) { - workerGroup = new EpollEventLoopGroup(RULE_REGISTRY.getAcceptorSize()); + workerGroup = new EpollEventLoopGroup(); userGroup = new EpollEventLoopGroup(RULE_REGISTRY.getAcceptorSize()); bootstrap.group(bossGroup, workerGroup) .channel(EpollServerSocketChannel.class) @@ -111,7 +111,7 @@ public final class ShardingProxy { } private void groupsNio(final ServerBootstrap bootstrap) { - workerGroup = new NioEventLoopGroup(RULE_REGISTRY.getAcceptorSize()); + workerGroup = new NioEventLoopGroup(); userGroup = new NioEventLoopGroup(RULE_REGISTRY.getAcceptorSize()); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) diff --git a/sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/common/FrontendHandler.java b/sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/common/FrontendHandler.java index d645a1fc986..8643d862010 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/common/FrontendHandler.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/common/FrontendHandler.java @@ -34,7 +34,7 @@ public abstract class FrontendHandler extends ChannelInboundHandlerAdapter { private boolean authorized; @Setter - private BackendConnection backendConnection; + private volatile BackendConnection backendConnection; @Override public final void channelActive(final ChannelHandlerContext context) {
['sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/common/FrontendHandler.java', 'sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/ShardingProxy.java']
{'.java': 2}
2
2
0
0
2
2,252,253
469,193
63,222
805
365
73
6
2
1,002
149
205
26
0
0
1970-01-01T00:25:35
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,524
apache/shardingsphere/1192/1191
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1191
https://github.com/apache/shardingsphere/pull/1192
https://github.com/apache/shardingsphere/pull/1192
1
fixes
Proxy blocked when client connect and close repeatly
For English only, other languages we will close it directly. Please answer these questions before submitting your issue. Thanks! ### Which version of Sharding-Sphere do you using? 3.0.0.M3 ### Which project do you using? Sharding-JDBC or Sharding-Proxy? Sharding-Proxy ### Expected behavior High Availability. ### Actual behavior Proxy blocked when client connect and close repeatly. ### Reason analyze Only when a client close the connection meanwhile a query is not finish in this connection will triger this bug. When a frontend connection is closed the connection will become not writable, this cause MySQLFrontendHandler wait and never jump out the loop. ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc Execute a slow SQL then close the connection until the connections is used up. ### For bug report, please *MUST* provide the reproduce example codes (such as a github link). Official example.
4e9b2c038c62a427d1ed084fe87d1f57ccade933
97948b5d29b3e3dbc158244899b49a7025edb940
https://github.com/apache/shardingsphere/compare/4e9b2c038c62a427d1ed084fe87d1f57ccade933...97948b5d29b3e3dbc158244899b49a7025edb940
diff --git a/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/jdbc/connection/BackendConnection.java b/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/jdbc/connection/BackendConnection.java index e5a757f3b04..a3c671d8d01 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/jdbc/connection/BackendConnection.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/jdbc/connection/BackendConnection.java @@ -75,6 +75,18 @@ public final class BackendConnection implements AutoCloseable { cachedResultSets.add(resultSet); } + /** + * Cancel statement. + */ + public void cancel() { + for (Statement each : cachedStatements) { + try { + each.cancel(); + } catch (final SQLException ignore) { + } + } + } + @Override public void close() throws SQLException { Collection<SQLException> exceptions = new LinkedList<>(); diff --git a/sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/common/FrontendHandler.java b/sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/common/FrontendHandler.java index bcf08e10851..d645a1fc986 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/common/FrontendHandler.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/common/FrontendHandler.java @@ -20,7 +20,9 @@ package io.shardingsphere.proxy.frontend.common; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; +import io.shardingsphere.proxy.backend.jdbc.connection.BackendConnection; import io.shardingsphere.proxy.frontend.common.executor.ChannelThreadExecutorGroup; +import lombok.Setter; /** * Frontend handler. @@ -31,6 +33,9 @@ public abstract class FrontendHandler extends ChannelInboundHandlerAdapter { private boolean authorized; + @Setter + private BackendConnection backendConnection; + @Override public final void channelActive(final ChannelHandlerContext context) { ChannelThreadExecutorGroup.getInstance().register(context.channel().id()); @@ -56,6 +61,7 @@ public abstract class FrontendHandler extends ChannelInboundHandlerAdapter { @Override public final void channelInactive(final ChannelHandlerContext context) { context.fireChannelInactive(); + backendConnection.cancel(); ChannelThreadExecutorGroup.getInstance().unregister(context.channel().id()); } } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/mysql/MySQLFrontendHandler.java b/sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/mysql/MySQLFrontendHandler.java index 4d6a2869087..e73dcada467 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/mysql/MySQLFrontendHandler.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/mysql/MySQLFrontendHandler.java @@ -105,6 +105,7 @@ public final class MySQLFrontendHandler extends FrontendHandler { public void run() { try (MySQLPacketPayload payload = new MySQLPacketPayload(message); BackendConnection backendConnection = new BackendConnection()) { + setBackendConnection(backendConnection); CommandPacket commandPacket = getCommandPacket(payload, backendConnection); Optional<CommandResponsePackets> responsePackets = commandPacket.execute(); if (!responsePackets.isPresent()) { @@ -132,9 +133,12 @@ public final class MySQLFrontendHandler extends FrontendHandler { } private void writeMoreResults(final QueryCommandPacket queryCommandPacket, final int headPacketsCount) throws SQLException { + if (!context.channel().isActive()) { + return; + } currentSequenceId = headPacketsCount; while (queryCommandPacket.next()) { - while (!context.channel().isWritable()) { + while (!context.channel().isWritable() && context.channel().isActive()) { synchronized (MySQLFrontendHandler.this) { try { MySQLFrontendHandler.this.wait();
['sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/mysql/MySQLFrontendHandler.java', 'sharding-proxy/src/main/java/io/shardingsphere/proxy/backend/jdbc/connection/BackendConnection.java', 'sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/common/FrontendHandler.java']
{'.java': 3}
3
3
0
0
3
2,249,962
468,843
63,241
805
763
132
24
3
1,002
149
205
26
0
0
1970-01-01T00:25:35
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,492
apache/shardingsphere/2206/2205
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2205
https://github.com/apache/shardingsphere/pull/2206
https://github.com/apache/shardingsphere/pull/2206
1
fixes
When use ShardingQueryAssistedEncryptor to find assistedQueryColumns, an outOfIndex exception will occur.
Here is the point: ``` ShardingEncryptorStrategy /** * Get assisted query column. * * @param logicTableName logic table name * @param columnName column name * @return assisted query column */ public Optional<String> getAssistedQueryColumn(final String logicTableName, final String columnName) { for (ColumnNode each : columns) { ColumnNode target = new ColumnNode(logicTableName, columnName); if (each.equals(target)) { return Optional.of(assistedQueryColumns.get(columns.indexOf(target)).getColumnName()); } } return Optional.absent(); } ```
2c82896d0db0f74c3cc346f6ca038df523ba417f
42f0cd16623e3aefb3b973c31f02894e3c95c35d
https://github.com/apache/shardingsphere/compare/2c82896d0db0f74c3cc346f6ca038df523ba417f...42f0cd16623e3aefb3b973c31f02894e3c95c35d
diff --git a/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/strategy/encrypt/ShardingEncryptorStrategy.java b/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/strategy/encrypt/ShardingEncryptorStrategy.java index f06942e5886..e7a97f0bb70 100644 --- a/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/strategy/encrypt/ShardingEncryptorStrategy.java +++ b/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/strategy/encrypt/ShardingEncryptorStrategy.java @@ -17,7 +17,6 @@ package org.apache.shardingsphere.core.strategy.encrypt; -import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; @@ -32,6 +31,7 @@ import org.apache.shardingsphere.spi.encrypt.ShardingQueryAssistedEncryptor; import java.util.Collection; import java.util.Collections; +import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; @@ -105,6 +105,9 @@ public final class ShardingEncryptorStrategy { * @return assisted query column */ public Optional<String> getAssistedQueryColumn(final String logicTableName, final String columnName) { + if (assistedQueryColumns.isEmpty()) { + return Optional.absent(); + } for (ColumnNode each : columns) { ColumnNode target = new ColumnNode(logicTableName, columnName); if (each.equals(target)) { @@ -145,12 +148,10 @@ public final class ShardingEncryptorStrategy { * @return encrypt table names */ public Collection<String> getEncryptTableNames() { - return Collections2.transform(columns, new Function<ColumnNode, String>() { - - @Override - public String apply(final ColumnNode input) { - return input.getTableName(); - } - }); + Collection<String> result = new LinkedHashSet<>(); + for (ColumnNode each : columns) { + result.add(each.getTableName()); + } + return result; } } diff --git a/sharding-core/sharding-core-common/src/test/java/org/apache/shardingsphere/core/strategy/encrypt/ShardingEncryptorStrategyTest.java b/sharding-core/sharding-core-common/src/test/java/org/apache/shardingsphere/core/strategy/encrypt/ShardingEncryptorStrategyTest.java index 1e89575a0b2..42d8f8f0f36 100644 --- a/sharding-core/sharding-core-common/src/test/java/org/apache/shardingsphere/core/strategy/encrypt/ShardingEncryptorStrategyTest.java +++ b/sharding-core/sharding-core-common/src/test/java/org/apache/shardingsphere/core/strategy/encrypt/ShardingEncryptorStrategyTest.java @@ -27,6 +27,7 @@ import java.util.Properties; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; public final class ShardingEncryptorStrategyTest { @@ -39,14 +40,51 @@ public final class ShardingEncryptorStrategyTest { @Test(expected = IllegalArgumentException.class) public void assertInvalidConstructor() { - EncryptorRuleConfiguration encryptorRuleConfiguration = new EncryptorRuleConfiguration("test", "test.pwd1, test.pwd2", "test.pwd1_index", new Properties()); + EncryptorRuleConfiguration encryptorRuleConfiguration = new EncryptorRuleConfiguration("assistedTest", "test.pwd1, test.pwd2", "test.pwd1_index", new Properties()); new ShardingEncryptorStrategy(encryptorRuleConfiguration); } @Test public void assertGetAssistedQueryColumn() { - EncryptorRuleConfiguration encryptorRuleConfiguration = new EncryptorRuleConfiguration("test", "test.pwd1, test.pwd2", "test.pwd1_index,test.pwd2_index", new Properties()); + EncryptorRuleConfiguration encryptorRuleConfiguration = new EncryptorRuleConfiguration("assistedTest", "test.pwd1, test.pwd2", "test.pwd1_index,test.pwd2_index", new Properties()); ShardingEncryptorStrategy actual = new ShardingEncryptorStrategy(encryptorRuleConfiguration); assertThat(actual.getAssistedQueryColumn("test", "pwd1"), is(Optional.of("pwd1_index"))); + assertThat(actual.getAssistedQueryColumn("test", "pwd3"), is(Optional.<String>absent())); + } + + @Test + public void assertGetAssistedQueryColumnWithoutResult() { + EncryptorRuleConfiguration encryptorRuleConfiguration = new EncryptorRuleConfiguration("test", "test.pwd1, test.pwd2", new Properties()); + ShardingEncryptorStrategy actual = new ShardingEncryptorStrategy(encryptorRuleConfiguration); + assertThat(actual.getAssistedQueryColumn("test", "pwd1"), is(Optional.<String>absent())); + } + + @Test + public void assertGetAssistedQueryCount() { + EncryptorRuleConfiguration encryptorRuleConfiguration = new EncryptorRuleConfiguration("assistedTest", "test.pwd1, test.pwd2", "test.pwd1_index,test.pwd2_index", new Properties()); + ShardingEncryptorStrategy actual = new ShardingEncryptorStrategy(encryptorRuleConfiguration); + assertThat(actual.getAssistedQueryColumnCount("test"), is(2)); + } + + @Test + public void assertGetAssistedQueryColumnCountWithoutResult() { + EncryptorRuleConfiguration encryptorRuleConfiguration = new EncryptorRuleConfiguration("test", "test.pwd1, test.pwd2", new Properties()); + ShardingEncryptorStrategy actual = new ShardingEncryptorStrategy(encryptorRuleConfiguration); + assertThat(actual.getAssistedQueryColumnCount("test"), is(0)); + assertThat(actual.getAssistedQueryColumnCount("test1"), is(0)); + } + + @Test + public void assertGetEncryptTableNames() { + EncryptorRuleConfiguration encryptorRuleConfiguration = new EncryptorRuleConfiguration("assistedTest", "test.pwd1, test.pwd2", "test.pwd1_index,test.pwd2_index", new Properties()); + ShardingEncryptorStrategy actual = new ShardingEncryptorStrategy(encryptorRuleConfiguration); + assertThat(actual.getEncryptTableNames().size(), is(1)); + } + + @Test + public void assertIsHasShardingQueryAssistedEncryptor() { + EncryptorRuleConfiguration encryptorRuleConfiguration = new EncryptorRuleConfiguration("assistedTest", "test.pwd1, test.pwd2", "test.pwd1_index,test.pwd2_index", new Properties()); + ShardingEncryptorStrategy actual = new ShardingEncryptorStrategy(encryptorRuleConfiguration); + assertTrue(actual.isHasShardingQueryAssistedEncryptor("test")); } }
['sharding-core/sharding-core-common/src/test/java/org/apache/shardingsphere/core/strategy/encrypt/ShardingEncryptorStrategyTest.java', 'sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/strategy/encrypt/ShardingEncryptorStrategy.java']
{'.java': 2}
2
2
0
0
2
3,232,805
653,469
81,881
1,107
609
105
17
1
677
62
133
21
0
1
1970-01-01T00:25:55
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,493
apache/shardingsphere/2182/2152
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2152
https://github.com/apache/shardingsphere/pull/2182
https://github.com/apache/shardingsphere/pull/2182
1
fix
MemoryQueryResult getColumnIndex throw exception when using Oracle database
## Bug Report when execute Oracle's DQL, getting the result throws an exception ``` java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.rangeCheck(ArrayList.java:657) at java.util.ArrayList.get(ArrayList.java:433) at org.apache.shardingsphere.core.execute.sql.execute.result.QueryResultMetaData.getColumnIndex(QueryResultMetaData.java:140) at org.apache.shardingsphere.core.execute.sql.execute.result.MemoryQueryResult.getValue(MemoryQueryResult.java:95) at org.apache.shardingsphere.core.merge.dql.common.StreamMergedResult.getValue(StreamMergedResult.java:56) at org.apache.shardingsphere.core.merge.dql.common.DecoratorMergedResult.getValue(DecoratorMergedResult.java:46) at org.apache.shardingsphere.shardingjdbc.jdbc.core.resultset.ShardingResultSet.getString(ShardingResultSet.java:141) at org.hibernate.type.descriptor.sql.VarcharTypeDescriptor$2.doExtract(VarcharTypeDescriptor.java:62) at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47) at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:261) at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:257) at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:247) at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:333) at org.hibernate.loader.Loader.extractKeysFromResultSet(Loader.java:794) at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:719) at org.hibernate.loader.Loader.processResultSet(Loader.java:991) at org.hibernate.loader.Loader.doQuery(Loader.java:949) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:341) at org.hibernate.loader.Loader.doList(Loader.java:2692) at org.hibernate.loader.Loader.doList(Loader.java:2675) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2507) at org.hibernate.loader.Loader.list(Loader.java:2502) at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:502) at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:392) at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216) at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1490) at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1445) at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1414) at org.hibernate.query.Query.getResultList(Query.java:146) at org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:72) at org.springframework.data.jpa.repository.support.SimpleJpaRepository.readPage(SimpleJpaRepository.java:570) at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:389) at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:357) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:377) at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200) at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:641) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:605) at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:590) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:135) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) at com.sun.proxy.$Proxy88.findAll(Unknown Source) at com.fudabd.oracletest.controller.TerminalController.listTerminal(TerminalController.java:83) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:891) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:981) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:873) at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:858) at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) ``` ### Which version of ShardingSphere did you use? 3.1.0 and 4.0.0-RC1-SNAPSHOT ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-JDBC ### Expected behavior get results correctly ### Actual behavior throw exception `java.lang.IndexOutOfBoundsException: Index: 0, Size: 0` ### Reason analyze (If you can) MemoryQueryResult will get the table metadata when init, the columnLabel in oracle metadata is upper case. But the input of `getColumnIndex` method is lower case so that can't find the index. ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc. 1. clone example codes 2. change sharding-jdbc version to 3.1.0 or 4.0.0-RC1-SNAPSHOT 3. check configuration of jdbc at file `application-sharding-databases-oracle.properties` 4. run `OracleTestApplication` 5. visit http://localhost:8080/insertTest 6. visit http://localhost:8080/listTerminal ### Example codes for reproduce this issue (such as a github link). https://github.com/fdlzp/sharding-jdbc_jpa_oracle
f63e9cb1d1532aa95e5745f3b98842e669543eb6
5a5ccfefbc57dcb523a3e74360e69a0874e98d0e
https://github.com/apache/shardingsphere/compare/f63e9cb1d1532aa95e5745f3b98842e669543eb6...5a5ccfefbc57dcb523a3e74360e69a0874e98d0e
diff --git a/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultMetaData.java b/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultMetaData.java index e40fcceedbf..4a47497162b 100644 --- a/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultMetaData.java +++ b/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultMetaData.java @@ -18,8 +18,6 @@ package org.apache.shardingsphere.core.execute.sql.execute.result; import com.google.common.base.Optional; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Multimap; import lombok.SneakyThrows; import org.apache.shardingsphere.core.rule.ShardingRule; import org.apache.shardingsphere.core.rule.TableRule; @@ -29,9 +27,9 @@ import org.apache.shardingsphere.spi.encrypt.ShardingEncryptor; import java.sql.ResultSetMetaData; import java.sql.SQLException; -import java.util.ArrayList; import java.util.Collections; -import java.util.Map.Entry; +import java.util.Map; +import java.util.TreeMap; /** * Query result meta data. @@ -40,7 +38,7 @@ import java.util.Map.Entry; */ public final class QueryResultMetaData { - private final Multimap<String, Integer> columnLabelAndIndexes; + private final Map<String, Integer> columnLabelAndIndexes; private final ResultSetMetaData resultSetMetaData; @@ -62,9 +60,9 @@ public final class QueryResultMetaData { } @SneakyThrows - private Multimap<String, Integer> getColumnLabelAndIndexMap(final ResultSetMetaData resultSetMetaData) { - Multimap<String, Integer> result = HashMultimap.create(); - for (int columnIndex = 1; columnIndex <= resultSetMetaData.getColumnCount(); columnIndex++) { + private Map<String, Integer> getColumnLabelAndIndexMap(final ResultSetMetaData resultSetMetaData) { + Map<String, Integer> result = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + for (int columnIndex = resultSetMetaData.getColumnCount(); columnIndex > 0; columnIndex--) { result.put(resultSetMetaData.getColumnLabel(columnIndex), columnIndex); } return result; @@ -75,8 +73,9 @@ public final class QueryResultMetaData { * * @return column count */ + @SneakyThrows public int getColumnCount() { - return columnLabelAndIndexes.size(); + return resultSetMetaData.getColumnCount(); } /** @@ -87,12 +86,7 @@ public final class QueryResultMetaData { */ @SneakyThrows public String getColumnLabel(final int columnIndex) { - for (Entry<String, Integer> entry : columnLabelAndIndexes.entries()) { - if (columnIndex == entry.getValue()) { - return entry.getKey(); - } - } - throw new SQLException("Column index out of range", "9999"); + return resultSetMetaData.getColumnLabel(columnIndex); } /** @@ -113,7 +107,7 @@ public final class QueryResultMetaData { * @return column name */ public Integer getColumnIndex(final String columnLabel) { - return new ArrayList<>(columnLabelAndIndexes.get(columnLabel)).get(0); + return columnLabelAndIndexes.get(columnLabel); } /** diff --git a/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/DQLMergeEngine.java b/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/DQLMergeEngine.java index 486f4a5beea..376bf9cd335 100644 --- a/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/DQLMergeEngine.java +++ b/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/DQLMergeEngine.java @@ -101,7 +101,7 @@ public final class DQLMergeEngine implements MergeEngine { private Map<String, Integer> getColumnLabelIndexMap(final QueryResult queryResult) throws SQLException { Map<String, Integer> result = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); - for (int i = 1; i <= queryResult.getColumnCount(); i++) { + for (int i = queryResult.getColumnCount(); i > 0; i--) { result.put(SQLUtil.getExactlyValue(queryResult.getColumnLabel(i)), i); } return result; diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/PreparedStatementExecutorTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/PreparedStatementExecutorTest.java index d7655be20cd..f16b15b1de1 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/PreparedStatementExecutorTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/PreparedStatementExecutorTest.java @@ -78,6 +78,7 @@ public final class PreparedStatementExecutorTest extends AbstractBaseExecutorTes ResultSet resultSet = mock(ResultSet.class); ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class); when(resultSetMetaData.getColumnName(1)).thenReturn("column"); + when(resultSetMetaData.getColumnLabel(1)).thenReturn("column"); when(resultSetMetaData.getTableName(1)).thenReturn("table_x"); when(resultSetMetaData.getColumnCount()).thenReturn(1); when(resultSet.getString(1)).thenReturn("value"); @@ -95,6 +96,7 @@ public final class PreparedStatementExecutorTest extends AbstractBaseExecutorTes ResultSet resultSet2 = mock(ResultSet.class); ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class); when(resultSetMetaData.getColumnName(1)).thenReturn("column"); + when(resultSetMetaData.getColumnLabel(1)).thenReturn("column"); when(resultSetMetaData.getTableName(1)).thenReturn("table_x"); when(resultSetMetaData.getColumnCount()).thenReturn(1); when(resultSet1.getMetaData()).thenReturn(resultSetMetaData); diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/StatementExecutorTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/StatementExecutorTest.java index 424b3f7400e..058a9a90112 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/StatementExecutorTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/StatementExecutorTest.java @@ -79,6 +79,7 @@ public final class StatementExecutorTest extends AbstractBaseExecutorTest { ResultSet resultSet = mock(ResultSet.class); ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class); when(resultSetMetaData.getColumnName(1)).thenReturn("column"); + when(resultSetMetaData.getColumnLabel(1)).thenReturn("column"); when(resultSetMetaData.getTableName(1)).thenReturn("table_x"); when(resultSetMetaData.getColumnCount()).thenReturn(1); when(resultSet.getString(1)).thenReturn("value"); @@ -97,6 +98,7 @@ public final class StatementExecutorTest extends AbstractBaseExecutorTest { ResultSet resultSet2 = mock(ResultSet.class); ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class); when(resultSetMetaData.getColumnName(1)).thenReturn("column"); + when(resultSetMetaData.getColumnLabel(1)).thenReturn("column"); when(resultSetMetaData.getTableName(1)).thenReturn("table_x"); when(resultSetMetaData.getColumnCount()).thenReturn(1); when(resultSet1.getMetaData()).thenReturn(resultSetMetaData);
['sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/PreparedStatementExecutorTest.java', 'sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/DQLMergeEngine.java', 'sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/StatementExecutorTest.java', 'sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultMetaData.java']
{'.java': 4}
4
4
0
0
4
3,235,447
653,911
81,818
1,108
1,618
323
28
2
12,360
385
2,487
155
3
1
1970-01-01T00:25:54
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,494
apache/shardingsphere/1987/1985
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1985
https://github.com/apache/shardingsphere/pull/1987
https://github.com/apache/shardingsphere/pull/1987
1
fixes
Exception fired during concurrently query
## Bug Report **For English only**, other languages will not accept. Before report a bug, make sure you have: - Searched open and closed [GitHub issues](https://github.com/sharding-sphere/sharding-sphere/issues). - Read documentation: [ShardingSphere Doc](http://shardingsphere.io/document/current/en/overview/). Please pay attention on issues you submitted, because we maybe need more details. If no response **more than 7 days** and we cannot reproduce it on current information, we will **close it**. Please answer these questions before submitting your issue. Thanks! ### Which version of ShardingSphere did you use? 4.0.0-M1 ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-Proxy ### Expected behavior Execute query correctly. ### Actual behavior Exception 1: java.lang.NullPointerException: null at com.mysql.jdbc.ResultSetImpl.checkColumnBounds(ResultSetImpl.java:766) at com.mysql.jdbc.ResultSetImpl.getObject(ResultSetImpl.java:4420) at com.zaxxer.hikari.pool.HikariProxyResultSet.getObject(HikariProxyResultSet.java) at org.apache.shardingsphere.core.executor.sql.execute.result.StreamQueryResult.getValue(StreamQueryResult.java:75) at org.apache.shardingsphere.core.merger.dql.common.StreamMergedResult.getValue(StreamMergedResult.java:49) at org.apache.shardingsphere.shardingproxy.backend.communication.jdbc.JDBCDatabaseCommunicationEngine.getQueryData(JDBCDatabaseCommunicationEngine.java:149) at org.apache.shardingsphere.shardingproxy.transport.mysql.packet.command.query.binary.execute.MySQLQueryComStmtExecutePacketExecutor.getQueryData(MySQLQueryComStmtExecutePacketExecutor.java:1 13) at org.apache.shardingsphere.shardingproxy.transport.mysql.packet.command.query.binary.execute.MySQLQueryComStmtExecutePacketExecutor.getQueryData(MySQLQueryComStmtExecutePacketExecutor.java:5 3) at org.apache.shardingsphere.shardingproxy.frontend.mysql.MySQLFrontendEngine.writeMoreResults(MySQLFrontendEngine.java:152) at org.apache.shardingsphere.shardingproxy.frontend.mysql.MySQLFrontendEngine.writePackets(MySQLFrontendEngine.java:133) at org.apache.shardingsphere.shardingproxy.frontend.mysql.MySQLFrontendEngine.executeCommand(MySQLFrontendEngine.java:108) at org.apache.shardingsphere.shardingproxy.frontend.common.netty.FrontendChannelInboundHandler$1.run(FrontendChannelInboundHandler.java:70) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) Exception 2: java.sql.SQLException: Operation not allowed after ResultSet closed at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:965) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:898) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:887) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:861) at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:743) at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:6289) at com.zaxxer.hikari.pool.HikariProxyResultSet.next(HikariProxyResultSet.java) at org.apache.shardingsphere.core.executor.sql.execute.result.StreamQueryResult.next(StreamQueryResult.java:68) at org.apache.shardingsphere.core.merger.dql.iterator.IteratorStreamMergedResult.next(IteratorStreamMergedResult.java:43) at org.apache.shardingsphere.shardingproxy.backend.communication.jdbc.JDBCDatabaseCommunicationEngine.next(JDBCDatabaseCommunicationEngine.java:141) at org.apache.shardingsphere.shardingproxy.transport.mysql.packet.command.query.binary.execute.MySQLQueryComStmtExecutePacketExecutor.next(MySQLQueryComStmtExecutePacketExecutor.java:108) at org.apache.shardingsphere.shardingproxy.frontend.mysql.MySQLFrontendEngine.writeMoreResults(MySQLFrontendEngine.java:147) at org.apache.shardingsphere.shardingproxy.frontend.mysql.MySQLFrontendEngine.writePackets(MySQLFrontendEngine.java:134) at org.apache.shardingsphere.shardingproxy.frontend.mysql.MySQLFrontendEngine.executeCommand(MySQLFrontendEngine.java:108) at org.apache.shardingsphere.shardingproxy.frontend.common.netty.FrontendChannelInboundHandler$1.run(FrontendChannelInboundHandler.java:70) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) Exception 3: [ERROR] 18:30:44.867 [ShardingSphere-Command-20] o.a.s.s.f.c.n.FrontendChannelInboundHandler - Exception occur: java.sql.SQLException: null at org.apache.shardingsphere.shardingproxy.backend.communication.jdbc.connection.BackendConnection.throwSQLExceptionIfNecessary(BackendConnection.java:296) at org.apache.shardingsphere.shardingproxy.backend.communication.jdbc.connection.BackendConnection.close(BackendConnection.java:246) at org.apache.shardingsphere.shardingproxy.backend.communication.jdbc.connection.BackendConnection.close(BackendConnection.java:228) at org.apache.shardingsphere.shardingproxy.frontend.common.netty.FrontendChannelInboundHandler$1.run(FrontendChannelInboundHandler.java:73) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) ### Reason analyze (If you can) MySQL connection closed during query. Defect of BackendConnection status management. ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc. 200 connections concurrently execute SQLs. ### Example codes for reproduce this issue (such as a github link).
9494940d8f0460c782331abb6117eba90ba3fd11
18f80bbbe4d12cd8a47267647fd68cf9d5f2b15e
https://github.com/apache/shardingsphere/compare/9494940d8f0460c782331abb6117eba90ba3fd11...18f80bbbe4d12cd8a47267647fd68cf9d5f2b15e
diff --git a/sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/connection/BackendConnection.java b/sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/connection/BackendConnection.java index 36099314411..0a1b6e687e6 100644 --- a/sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/connection/BackendConnection.java +++ b/sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/connection/BackendConnection.java @@ -132,7 +132,6 @@ public final class BackendConnection implements AutoCloseable { * @throws SQLException SQL exception */ public List<Connection> getConnections(final ConnectionMode connectionMode, final String dataSourceName, final int connectionSize) throws SQLException { - stateHandler.setRunningStatusIfNecessary(); if (stateHandler.isInTransaction()) { return getConnectionsWithTransaction(connectionMode, dataSourceName, connectionSize); } else { diff --git a/sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/connection/ConnectionStateHandler.java b/sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/connection/ConnectionStateHandler.java index 18dc8bea4d4..213f785fd30 100644 --- a/sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/connection/ConnectionStateHandler.java +++ b/sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/connection/ConnectionStateHandler.java @@ -57,8 +57,8 @@ public class ConnectionStateHandler { /** * Change connection status to running if necessary. */ - void setRunningStatusIfNecessary() { - if (ConnectionStatus.TRANSACTION != status.get()) { + public void setRunningStatusIfNecessary() { + if (ConnectionStatus.TRANSACTION != status.get() && ConnectionStatus.RUNNING != status.get()) { status.getAndSet(ConnectionStatus.RUNNING); } } diff --git a/sharding-proxy/sharding-proxy-backend/src/test/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/connection/BackendConnectionTest.java b/sharding-proxy/sharding-proxy-backend/src/test/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/connection/BackendConnectionTest.java index 3e9ab27416f..04db6ff0a7a 100644 --- a/sharding-proxy/sharding-proxy-backend/src/test/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/connection/BackendConnectionTest.java +++ b/sharding-proxy/sharding-proxy-backend/src/test/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/connection/BackendConnectionTest.java @@ -158,7 +158,8 @@ public final class BackendConnectionTest { backendConnection.setCurrentSchema("schema_0"); when(backendDataSource.getConnections((ConnectionMode) any(), anyString(), eq(12), eq(TransactionType.LOCAL))).thenReturn(MockConnectionUtil.mockNewConnections(12)); backendConnection.getConnections(ConnectionMode.MEMORY_STRICTLY, "ds1", 12); - assertThat(backendConnection.getStateHandler().getStatus(), is(ConnectionStatus.RUNNING)); + assertThat(backendConnection.getStateHandler().getStatus(), is(ConnectionStatus.INIT)); + backendConnection.getStateHandler().setRunningStatusIfNecessary(); mockResultSetAndStatement(backendConnection); actual = backendConnection; } diff --git a/sharding-proxy/sharding-proxy-frontend/sharding-proxy-frontend-core/src/main/java/org/apache/shardingsphere/shardingproxy/frontend/command/CommandExecutorTask.java b/sharding-proxy/sharding-proxy-frontend/sharding-proxy-frontend-core/src/main/java/org/apache/shardingsphere/shardingproxy/frontend/command/CommandExecutorTask.java index 1ecf27029fb..b6117210b1c 100644 --- a/sharding-proxy/sharding-proxy-frontend/sharding-proxy-frontend-core/src/main/java/org/apache/shardingsphere/shardingproxy/frontend/command/CommandExecutorTask.java +++ b/sharding-proxy/sharding-proxy-frontend/sharding-proxy-frontend-core/src/main/java/org/apache/shardingsphere/shardingproxy/frontend/command/CommandExecutorTask.java @@ -62,6 +62,7 @@ public final class CommandExecutorTask implements Runnable { try (BackendConnection backendConnection = this.backendConnection; PacketPayload payload = databaseFrontendEngine.getCodecEngine().createPacketPayload((ByteBuf) message)) { backendConnection.getStateHandler().waitUntilConnectionReleasedIfNecessary(); + backendConnection.getStateHandler().setRunningStatusIfNecessary(); isNeedFlush = executeCommand(context, payload, backendConnection); connectionSize = backendConnection.getConnectionSize(); // CHECKSTYLE:OFF
['sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/connection/ConnectionStateHandler.java', 'sharding-proxy/sharding-proxy-frontend/sharding-proxy-frontend-core/src/main/java/org/apache/shardingsphere/shardingproxy/frontend/command/CommandExecutorTask.java', 'sharding-proxy/sharding-proxy-backend/src/test/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/connection/BackendConnectionTest.java', 'sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/connection/BackendConnection.java']
{'.java': 4}
4
4
0
0
4
3,235,152
653,522
81,725
1,093
387
77
6
3
6,095
257
1,317
100
2
0
1970-01-01T00:25:51
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,495
apache/shardingsphere/1964/1957
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1957
https://github.com/apache/shardingsphere/pull/1964
https://github.com/apache/shardingsphere/pull/1964
1
fixes
autogen key sharding-column can't be routed succeed while using default sharding strategy
## Bug Report ### Which version of ShardingSphere did you use? 4.0.0.M1-SNAPSHOT ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-JDBC ### Expected behavior order_id use SNOWFLAKE algorithm, which is the table sharding-colum. `INSERT INTO t_order (user_id, status) VALUES (?, ?) ` should be routed to t_order_0 or t_order_1 ### Actual behavior route to t_order_0 and t_order_1 ### Reason analyze (If you can) OptimizeEngine haven't make autogen sharding-column as `ShardingCondition` ### Example codes for reproduce this issue (such as a github link). following unit test case of sharding-example project. `io.shardingsphere.example.jdbc.nodep.JavaConfigurationExampleTest#assertShardingTables`
86c04995ff95b05c8d1c7998cc52ba3aa306a798
427c66a46ba63faed99a71b3f5f7018cdd04edd4
https://github.com/apache/shardingsphere/compare/86c04995ff95b05c8d1c7998cc52ba3aa306a798...427c66a46ba63faed99a71b3f5f7018cdd04edd4
diff --git a/sharding-core/src/main/java/org/apache/shardingsphere/core/optimizer/engine/sharding/insert/InsertOptimizeEngine.java b/sharding-core/src/main/java/org/apache/shardingsphere/core/optimizer/engine/sharding/insert/InsertOptimizeEngine.java index a8f4861efd8..a0b06b63037 100644 --- a/sharding-core/src/main/java/org/apache/shardingsphere/core/optimizer/engine/sharding/insert/InsertOptimizeEngine.java +++ b/sharding-core/src/main/java/org/apache/shardingsphere/core/optimizer/engine/sharding/insert/InsertOptimizeEngine.java @@ -179,13 +179,9 @@ public final class InsertOptimizeEngine implements OptimizeEngine { private void fillShardingCondition(final ShardingCondition shardingCondition, final Comparable<?> currentGeneratedKey) { Column generateKeyColumn = shardingRule.findGenerateKeyColumn(insertStatement.getTables().getSingleTableName()).get(); - if (isShardingColumn(generateKeyColumn)) { + if (shardingRule.isShardingColumn(generateKeyColumn)) { shardingCondition.getShardingValues().add(new ListRouteValue<>(generateKeyColumn, new GeneratedKeyCondition(generateKeyColumn, -1, currentGeneratedKey).getConditionValues(parameters))); } insertStatement.setContainGenerateKey(true); } - - private boolean isShardingColumn(final Column generateKeyColumn) { - return shardingRule.getTableRule(generateKeyColumn.getTableName()).getAllShardingColumns().contains(generateKeyColumn.getName()); - } }
['sharding-core/src/main/java/org/apache/shardingsphere/core/optimizer/engine/sharding/insert/InsertOptimizeEngine.java']
{'.java': 1}
1
1
0
0
1
3,046,836
617,149
77,632
1,030
340
72
6
1
747
91
187
23
0
0
1970-01-01T00:25:51
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,497
apache/shardingsphere/1958/1959
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1959
https://github.com/apache/shardingsphere/pull/1958
https://github.com/apache/shardingsphere/pull/1958
1
fixes
Proxy will load all schema from registry when startup
## Bug Report **For English only**, other languages will not accept. Before report a bug, make sure you have: - Searched open and closed [GitHub issues](https://github.com/sharding-sphere/sharding-sphere/issues). - Read documentation: [ShardingSphere Doc](http://shardingsphere.io/document/current/en/overview/). Please pay attention on issues you submitted, because we maybe need more details. If no response **more than 7 days** and we cannot reproduce it on current information, we will **close it**. Please answer these questions before submitting your issue. Thanks! ### Which version of ShardingSphere did you use? 4.0.0.M1-SNAPSHOT ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-Proxy ### Expected behavior Only load some configurations user want from regsitry when startup. ### Actual behavior Load all the configs from registry when startup. ### Reason analyze (If you can) ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc. ### Example codes for reproduce this issue (such as a github link).
5fd3c8662ef58d422547d2fb89f738b9f725840b
d31a27fc337a1b6d1739e01a304d457d04e83858
https://github.com/apache/shardingsphere/compare/5fd3c8662ef58d422547d2fb89f738b9f725840b...d31a27fc337a1b6d1739e01a304d457d04e83858
diff --git a/sharding-core/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java b/sharding-core/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java index e46267be97d..59c9e8c2d9f 100644 --- a/sharding-core/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java +++ b/sharding-core/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java @@ -114,8 +114,7 @@ public final class SQLBuilder { result.append(each); } } - List<List<Object>> parameterSets = insertParameters.isEmpty() ? new ArrayList<>(Collections.singleton(parameters)) : new ArrayList<>(Collections.singleton(insertParameters)); - return new SQLUnit(result.toString(), parameterSets); + return insertParameters.isEmpty() ? new SQLUnit(result.toString(), new ArrayList<>(parameters)) : new SQLUnit(result.toString(), insertParameters); } /** @@ -156,8 +155,7 @@ public final class SQLBuilder { result.append(each); } } - List<List<Object>> parameterSets = insertParameters.isEmpty() ? new ArrayList<>(Collections.singleton(parameters)) : new ArrayList<>(Collections.singleton(insertParameters)); - return new SQLUnit(result.toString(), parameterSets); + return insertParameters.isEmpty() ? new SQLUnit(result.toString(), parameters) : new SQLUnit(result.toString(), insertParameters); } private void appendTablePlaceholder(final TablePlaceholder tablePlaceholder, final String actualTableName, final StringBuilder stringBuilder) { diff --git a/sharding-core/src/main/java/org/apache/shardingsphere/core/routing/BatchRouteUnit.java b/sharding-core/src/main/java/org/apache/shardingsphere/core/routing/BatchRouteUnit.java index 186c3c40520..a66bb1c1d89 100644 --- a/sharding-core/src/main/java/org/apache/shardingsphere/core/routing/BatchRouteUnit.java +++ b/sharding-core/src/main/java/org/apache/shardingsphere/core/routing/BatchRouteUnit.java @@ -17,12 +17,16 @@ package org.apache.shardingsphere.core.routing; +import com.google.common.collect.Lists; import lombok.AccessLevel; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; +import java.util.Collections; import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; import java.util.Map; /** @@ -54,4 +58,19 @@ public final class BatchRouteUnit { public void mapAddBatchCount(final int jdbcAddBatchTimes) { jdbcAndActualAddBatchCallTimesMap.put(jdbcAddBatchTimes, actualCallAddBatchTimes++); } + + /** + * Get parameter sets. + * + * @return parameter sets + */ + public List<List<Object>> getParameterSets() { + List<List<Object>> result = new LinkedList<>(); + if (routeUnit.getSqlUnit().getParameters().isEmpty() || 0 == actualCallAddBatchTimes) { + result.add(Collections.emptyList()); + } else { + result.addAll(Lists.partition(routeUnit.getSqlUnit().getParameters(), routeUnit.getSqlUnit().getParameters().size() / actualCallAddBatchTimes)); + } + return result; + } } diff --git a/sharding-core/src/main/java/org/apache/shardingsphere/core/routing/SQLUnit.java b/sharding-core/src/main/java/org/apache/shardingsphere/core/routing/SQLUnit.java index 6eb16a79b1b..9df2bd749c5 100644 --- a/sharding-core/src/main/java/org/apache/shardingsphere/core/routing/SQLUnit.java +++ b/sharding-core/src/main/java/org/apache/shardingsphere/core/routing/SQLUnit.java @@ -28,6 +28,7 @@ import java.util.List; * SQL unit. * * @author maxiaoguang + * @author panjuan */ @RequiredArgsConstructor @Getter @@ -37,5 +38,5 @@ public final class SQLUnit { private final String sql; - private final List<List<Object>> parameterSets; + private final List<Object> parameters; } diff --git a/sharding-core/src/main/java/org/apache/shardingsphere/core/routing/router/sharding/DatabaseHintSQLRouter.java b/sharding-core/src/main/java/org/apache/shardingsphere/core/routing/router/sharding/DatabaseHintSQLRouter.java index c536137cabc..3bffd17c887 100644 --- a/sharding-core/src/main/java/org/apache/shardingsphere/core/routing/router/sharding/DatabaseHintSQLRouter.java +++ b/sharding-core/src/main/java/org/apache/shardingsphere/core/routing/router/sharding/DatabaseHintSQLRouter.java @@ -31,7 +31,6 @@ import org.apache.shardingsphere.core.rule.ShardingRule; import org.apache.shardingsphere.core.util.SQLLogger; import java.util.ArrayList; -import java.util.Collections; import java.util.List; /** @@ -60,7 +59,7 @@ public final class DatabaseHintSQLRouter implements ShardingRouter { RoutingResult routingResult = new DatabaseHintRoutingEngine( shardingRule.getShardingDataSourceNames().getDataSourceNames(), (HintShardingStrategy) shardingRule.getDefaultDatabaseShardingStrategy()).route(); for (TableUnit each : routingResult.getTableUnits().getTableUnits()) { - result.getRouteUnits().add(new RouteUnit(each.getDataSourceName(), new SQLUnit(logicSQL, new ArrayList<>(Collections.singleton(parameters))))); + result.getRouteUnits().add(new RouteUnit(each.getDataSourceName(), new SQLUnit(logicSQL, new ArrayList<>(parameters)))); } if (showSQL) { SQLLogger.logSQL(logicSQL, sqlStatement, result.getRouteUnits()); diff --git a/sharding-core/src/main/java/org/apache/shardingsphere/core/util/SQLLogger.java b/sharding-core/src/main/java/org/apache/shardingsphere/core/util/SQLLogger.java index c1741d0a001..4535e40d016 100644 --- a/sharding-core/src/main/java/org/apache/shardingsphere/core/util/SQLLogger.java +++ b/sharding-core/src/main/java/org/apache/shardingsphere/core/util/SQLLogger.java @@ -48,10 +48,10 @@ public final class SQLLogger { log("Logic SQL: {}", logicSQL); log("SQLStatement: {}", sqlStatement); for (RouteUnit each : routeUnits) { - if (each.getSqlUnit().getParameterSets().get(0).isEmpty()) { + if (each.getSqlUnit().getParameters().isEmpty()) { log("Actual SQL: {} ::: {}", each.getDataSourceName(), each.getSqlUnit().getSql()); } else { - log("Actual SQL: {} ::: {} ::: {}", each.getDataSourceName(), each.getSqlUnit().getSql(), each.getSqlUnit().getParameterSets()); + log("Actual SQL: {} ::: {} ::: {}", each.getDataSourceName(), each.getSqlUnit().getSql(), each.getSqlUnit().getParameters()); } } } diff --git a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/executor/AbstractStatementExecutor.java b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/executor/AbstractStatementExecutor.java index 2f06298ed96..469b900ab9a 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/executor/AbstractStatementExecutor.java +++ b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/executor/AbstractStatementExecutor.java @@ -117,7 +117,7 @@ public class AbstractStatementExecutor { @Override public List<Object> apply(final StatementExecuteUnit input) { - return input.getRouteUnit().getSqlUnit().getParameterSets().get(0); + return input.getRouteUnit().getSqlUnit().getParameters(); } })); } diff --git a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/executor/BatchPreparedStatementExecutor.java b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/executor/BatchPreparedStatementExecutor.java index 1c4b60bfd13..b2dd6a05b16 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/executor/BatchPreparedStatementExecutor.java +++ b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/executor/BatchPreparedStatementExecutor.java @@ -20,6 +20,7 @@ package org.apache.shardingsphere.shardingjdbc.executor; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Predicate; +import com.google.common.collect.Collections2; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import lombok.Getter; @@ -139,7 +140,7 @@ public final class BatchPreparedStatementExecutor extends AbstractStatementExecu } private void reviseBatchRouteUnit(final BatchRouteUnit oldBatchRouteUnit, final BatchRouteUnit newBatchRouteUnit) { - oldBatchRouteUnit.getRouteUnit().getSqlUnit().getParameterSets().add(newBatchRouteUnit.getRouteUnit().getSqlUnit().getParameterSets().get(0)); + oldBatchRouteUnit.getRouteUnit().getSqlUnit().getParameters().addAll(newBatchRouteUnit.getRouteUnit().getSqlUnit().getParameters()); oldBatchRouteUnit.mapAddBatchCount(batchCount); } @@ -214,24 +215,39 @@ public final class BatchPreparedStatementExecutor extends AbstractStatementExecu * @return parameter sets */ public List<List<Object>> getParameterSet(final Statement statement) { - Optional<StatementExecuteUnit> target; List<List<Object>> result = new LinkedList<>(); for (ShardingExecuteGroup<StatementExecuteUnit> each : getExecuteGroups()) { - target = Iterators.tryFind(each.getInputs().iterator(), new Predicate<StatementExecuteUnit>() { - - @Override - public boolean apply(final StatementExecuteUnit input) { - return input.getStatement().equals(statement); - } - }); + Optional<StatementExecuteUnit> target = getStatementExecuteUnit(statement, each); if (target.isPresent()) { - result.addAll(target.get().getRouteUnit().getSqlUnit().getParameterSets()); + result = getParameterSets(target.get()); break; } } return result; } + private Optional<StatementExecuteUnit> getStatementExecuteUnit(final Statement statement, final ShardingExecuteGroup<StatementExecuteUnit> executeGroup) { + return Iterators.tryFind(executeGroup.getInputs().iterator(), new Predicate<StatementExecuteUnit>() { + + @Override + public boolean apply(final StatementExecuteUnit input) { + return input.getStatement().equals(statement); + } + }); + } + + private List<List<Object>> getParameterSets(final StatementExecuteUnit executeUnit) { + List<List<Object>> result; + result = Collections2.filter(routeUnits, new Predicate<BatchRouteUnit>() { + + @Override + public boolean apply(final BatchRouteUnit input) { + return input.getRouteUnit().equals(executeUnit.getRouteUnit()); + } + }).iterator().next().getParameterSets(); + return result; + } + @Override public void clear() throws SQLException { super.clear(); diff --git a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/EncryptPreparedStatement.java b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/EncryptPreparedStatement.java index f8254ea0233..17e67bc27d3 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/EncryptPreparedStatement.java +++ b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/EncryptPreparedStatement.java @@ -95,7 +95,7 @@ public final class EncryptPreparedStatement extends AbstractShardingPreparedStat try { SQLUnit sqlUnit = getSQLUnit(sql); preparedStatement = preparedStatementGenerator.createPreparedStatement(sqlUnit.getSql()); - replaySetParameter(preparedStatement, sqlUnit.getParameterSets().get(0)); + replaySetParameter(preparedStatement, sqlUnit.getParameters()); this.resultSet = new EncryptResultSet(this, preparedStatement.executeQuery(), preparedStatementGenerator.connection.getEncryptRule()); return resultSet; } finally { @@ -113,7 +113,7 @@ public final class EncryptPreparedStatement extends AbstractShardingPreparedStat try { SQLUnit sqlUnit = getSQLUnit(sql); preparedStatement = preparedStatementGenerator.createPreparedStatement(sqlUnit.getSql()); - replaySetParameter(preparedStatement, sqlUnit.getParameterSets().get(0)); + replaySetParameter(preparedStatement, sqlUnit.getParameters()); return preparedStatement.executeUpdate(); } finally { clearParameters(); @@ -125,7 +125,7 @@ public final class EncryptPreparedStatement extends AbstractShardingPreparedStat try { SQLUnit sqlUnit = getSQLUnit(sql); preparedStatement = preparedStatementGenerator.createPreparedStatement(sqlUnit.getSql()); - replaySetParameter(preparedStatement, sqlUnit.getParameterSets().get(0)); + replaySetParameter(preparedStatement, sqlUnit.getParameters()); boolean result = preparedStatement.execute(); this.resultSet = new EncryptResultSet(this, preparedStatement.getResultSet(), preparedStatementGenerator.connection.getEncryptRule()); return result; @@ -161,7 +161,7 @@ public final class EncryptPreparedStatement extends AbstractShardingPreparedStat private void replayBatchPreparedStatement() throws SQLException { for (SQLUnit each : sqlUnits) { - replaySetParameter(preparedStatement, each.getParameterSets().get(0)); + replaySetParameter(preparedStatement, each.getParameters()); preparedStatement.addBatch(); } } diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/BatchPreparedStatementExecutorTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/BatchPreparedStatementExecutorTest.java index 8ed4154b571..3a091e3e353 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/BatchPreparedStatementExecutorTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/BatchPreparedStatementExecutorTest.java @@ -127,9 +127,7 @@ public final class BatchPreparedStatementExecutorTest extends AbstractBaseExecut executeGroups.add(new ShardingExecuteGroup<>(preparedStatementExecuteUnits)); Collection<BatchRouteUnit> routeUnits = new LinkedList<>(); for (PreparedStatement each : preparedStatements) { - List<List<Object>> parameterSets = new LinkedList<>(); - parameterSets.add(Collections.singletonList((Object) 1)); - RouteUnit routeUnit = new RouteUnit("ds_0", new SQLUnit(SQL, parameterSets)); + RouteUnit routeUnit = new RouteUnit("ds_0", new SQLUnit(SQL, Collections.singletonList((Object) 1))); BatchRouteUnit batchRouteUnit = new BatchRouteUnit(routeUnit); batchRouteUnit.mapAddBatchCount(0); batchRouteUnit.mapAddBatchCount(1); diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/PreparedStatementExecutorTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/PreparedStatementExecutorTest.java index b8defdadc8b..cecfa88b01f 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/PreparedStatementExecutorTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/PreparedStatementExecutorTest.java @@ -263,8 +263,7 @@ public final class PreparedStatementExecutorTest extends AbstractBaseExecutorTes for (PreparedStatement each : preparedStatements) { List<List<Object>> parameterSets = new LinkedList<>(); String sql = SQLType.DQL.equals(sqlType) ? DQL_SQL : DML_SQL; - parameterSets.add(Collections.singletonList((Object) 1)); - preparedStatementExecuteUnits.add(new StatementExecuteUnit(new RouteUnit("ds_0", new SQLUnit(sql, parameterSets)), each, ConnectionMode.MEMORY_STRICTLY)); + preparedStatementExecuteUnits.add(new StatementExecuteUnit(new RouteUnit("ds_0", new SQLUnit(sql, Collections.singletonList((Object) 1))), each, ConnectionMode.MEMORY_STRICTLY)); } Field field = PreparedStatementExecutor.class.getSuperclass().getDeclaredField("executeGroups"); field.setAccessible(true); diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/SQLExecuteCallbackFactoryTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/SQLExecuteCallbackFactoryTest.java index c9c1710fed7..4871c70a4e8 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/SQLExecuteCallbackFactoryTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/SQLExecuteCallbackFactoryTest.java @@ -36,7 +36,6 @@ import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Collection; import java.util.Collections; -import java.util.List; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -61,7 +60,7 @@ public class SQLExecuteCallbackFactoryTest { when(connection.getMetaData()).thenReturn(metaData); when(metaData.getURL()).thenReturn("jdbc:mysql://localhost:3306/test"); units = Lists.newArrayList( - new StatementExecuteUnit(new RouteUnit("ds", new SQLUnit("SELECT now()", Collections.<List<Object>>emptyList())), preparedStatement, ConnectionMode.CONNECTION_STRICTLY) + new StatementExecuteUnit(new RouteUnit("ds", new SQLUnit("SELECT now()", Collections.emptyList())), preparedStatement, ConnectionMode.CONNECTION_STRICTLY) ); } diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/StatementExecutorTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/StatementExecutorTest.java index fd97de4b019..00188208a1c 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/StatementExecutorTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/StatementExecutorTest.java @@ -331,10 +331,8 @@ public final class StatementExecutorTest extends AbstractBaseExecutorTest { List<StatementExecuteUnit> statementExecuteUnits = new LinkedList<>(); executeGroups.add(new ShardingExecuteGroup<>(statementExecuteUnits)); for (Statement each : statements) { - List<List<Object>> parameterSets = new LinkedList<>(); String sql = SQLType.DQL.equals(sqlType) ? DQL_SQL : DML_SQL; - parameterSets.add(Collections.singletonList((Object) 1)); - statementExecuteUnits.add(new StatementExecuteUnit(new RouteUnit("ds_0", new SQLUnit(sql, parameterSets)), each, ConnectionMode.MEMORY_STRICTLY)); + statementExecuteUnits.add(new StatementExecuteUnit(new RouteUnit("ds_0", new SQLUnit(sql, Collections.singletonList((Object) 1))), each, ConnectionMode.MEMORY_STRICTLY)); } Field field = StatementExecutor.class.getSuperclass().getDeclaredField("executeGroups"); field.setAccessible(true); diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/ShardingPreparedStatementTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/ShardingPreparedStatementTest.java index a413d563845..c3ffeadb672 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/ShardingPreparedStatementTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/ShardingPreparedStatementTest.java @@ -196,7 +196,6 @@ public final class ShardingPreparedStatementTest extends AbstractShardingJDBCDat preparedStatement.setString(1, "init"); preparedStatement.setString(2, "batch"); preparedStatement.addBatch(); - int[] result = preparedStatement.executeBatch(); assertThat(result.length, is(3)); assertThat(result[0], is(4)); diff --git a/sharding-opentracing/src/main/java/org/apache/shardingsphere/opentracing/hook/OpenTracingSQLExecutionHook.java b/sharding-opentracing/src/main/java/org/apache/shardingsphere/opentracing/hook/OpenTracingSQLExecutionHook.java index 24877811ac6..33d2d38c0d1 100644 --- a/sharding-opentracing/src/main/java/org/apache/shardingsphere/opentracing/hook/OpenTracingSQLExecutionHook.java +++ b/sharding-opentracing/src/main/java/org/apache/shardingsphere/opentracing/hook/OpenTracingSQLExecutionHook.java @@ -27,7 +27,6 @@ import org.apache.shardingsphere.opentracing.ShardingTracer; import org.apache.shardingsphere.opentracing.constant.ShardingTags; import org.apache.shardingsphere.spi.hook.SQLExecutionHook; -import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -57,20 +56,12 @@ public final class OpenTracingSQLExecutionHook implements SQLExecutionHook { .withTag(Tags.DB_TYPE.getKey(), "sql") .withTag(Tags.DB_INSTANCE.getKey(), routeUnit.getDataSourceName()) .withTag(Tags.DB_STATEMENT.getKey(), routeUnit.getSqlUnit().getSql()) - .withTag(ShardingTags.DB_BIND_VARIABLES.getKey(), toString(routeUnit.getSqlUnit().getParameterSets())).startManual(); + .withTag(ShardingTags.DB_BIND_VARIABLES.getKey(), toString(routeUnit.getSqlUnit().getParameters())).startManual(); } - private String toString(final List<List<Object>> parameterSets) { - return parameterSets.isEmpty() ? "" : Joiner.on(", ").join(toStringList(parameterSets)); - } - - private List<String> toStringList(final List<List<Object>> parameterSets) { - List<String> result = new LinkedList<>(); - for (List<Object> each : parameterSets) { - result.add(String.format("[%s]", Joiner.on(", ").join(each))); - } - return result; + private String toString(final List<Object> parameterSets) { + return parameterSets.isEmpty() ? "" : String.format("[%s]", Joiner.on(", ").join(parameterSets)); } @Override diff --git a/sharding-opentracing/src/test/java/org/apache/shardingsphere/opentracing/hook/OpenTracingSQLExecutionHookTest.java b/sharding-opentracing/src/test/java/org/apache/shardingsphere/opentracing/hook/OpenTracingSQLExecutionHookTest.java index fd604a5290e..fa2652853bc 100644 --- a/sharding-opentracing/src/test/java/org/apache/shardingsphere/opentracing/hook/OpenTracingSQLExecutionHookTest.java +++ b/sharding-opentracing/src/test/java/org/apache/shardingsphere/opentracing/hook/OpenTracingSQLExecutionHookTest.java @@ -81,7 +81,7 @@ public final class OpenTracingSQLExecutionHookTest extends BaseOpenTracingHookTe DataSourceMetaData dataSourceMetaData = mock(DataSourceMetaData.class); when(dataSourceMetaData.getHostName()).thenReturn("localhost"); when(dataSourceMetaData.getPort()).thenReturn(8888); - sqlExecutionHook.start(createRouteUnit("success_ds", "SELECT * FROM success_tbl;", Collections.singletonList(Arrays.<Object>asList("1", 2))), dataSourceMetaData, true, null); + sqlExecutionHook.start(createRouteUnit("success_ds", "SELECT * FROM success_tbl;", Arrays.<Object>asList("1", 2)), dataSourceMetaData, true, null); sqlExecutionHook.finishSuccess(); MockSpan actual = getActualSpan(); assertThat(actual.operationName(), is("/Sharding-Sphere/executeSQL/")); @@ -103,7 +103,7 @@ public final class OpenTracingSQLExecutionHookTest extends BaseOpenTracingHookTe when(dataSourceMetaData.getHostName()).thenReturn("localhost"); when(dataSourceMetaData.getPort()).thenReturn(8888); sqlExecutionHook.start( - createRouteUnit("success_ds", "SELECT * FROM success_tbl;", Collections.singletonList(Arrays.<Object>asList("1", 2))), dataSourceMetaData, false, ShardingExecuteDataMap.getDataMap()); + createRouteUnit("success_ds", "SELECT * FROM success_tbl;", Arrays.<Object>asList("1", 2)), dataSourceMetaData, false, ShardingExecuteDataMap.getDataMap()); sqlExecutionHook.finishSuccess(); MockSpan actual = getActualSpan(); assertThat(actual.operationName(), is("/Sharding-Sphere/executeSQL/")); @@ -124,7 +124,7 @@ public final class OpenTracingSQLExecutionHookTest extends BaseOpenTracingHookTe DataSourceMetaData dataSourceMetaData = mock(DataSourceMetaData.class); when(dataSourceMetaData.getHostName()).thenReturn("localhost"); when(dataSourceMetaData.getPort()).thenReturn(8888); - sqlExecutionHook.start(createRouteUnit("failure_ds", "SELECT * FROM failure_tbl;", Collections.<List<Object>>emptyList()), dataSourceMetaData, true, null); + sqlExecutionHook.start(createRouteUnit("failure_ds", "SELECT * FROM failure_tbl;", Collections.emptyList()), dataSourceMetaData, true, null); sqlExecutionHook.finishFailure(new RuntimeException("SQL execution error")); MockSpan actual = getActualSpan(); assertThat(actual.operationName(), is("/Sharding-Sphere/executeSQL/")); @@ -141,8 +141,8 @@ public final class OpenTracingSQLExecutionHookTest extends BaseOpenTracingHookTe verify(activeSpan, times(0)).deactivate(); } - private RouteUnit createRouteUnit(final String dataSourceName, final String sql, final List<List<Object>> parameterSets) { - SQLUnit sqlUnit = new SQLUnit(sql, parameterSets); + private RouteUnit createRouteUnit(final String dataSourceName, final String sql, final List<Object> parameters) { + SQLUnit sqlUnit = new SQLUnit(sql, parameters); return new RouteUnit(dataSourceName, sqlUnit); } } diff --git a/sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/wrapper/PreparedStatementExecutorWrapper.java b/sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/wrapper/PreparedStatementExecutorWrapper.java index eb9b88b5e38..13f93fdafee 100644 --- a/sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/wrapper/PreparedStatementExecutorWrapper.java +++ b/sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/wrapper/PreparedStatementExecutorWrapper.java @@ -37,9 +37,6 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedList; import java.util.List; /** @@ -68,7 +65,7 @@ public final class PreparedStatementExecutorWrapper implements JDBCExecutorWrapp SQLRouteResult result = new SQLRouteResult(sqlStatement); for (String each : new MasterSlaveRouter( ((MasterSlaveSchema) logicSchema).getMasterSlaveRule(), GLOBAL_REGISTRY.getShardingProperties().<Boolean>getValue(ShardingPropertiesConstant.SQL_SHOW)).route(rewriteSQL)) { - result.getRouteUnits().add(new RouteUnit(each, new SQLUnit(rewriteSQL, new ArrayList<>(Collections.singleton(parameters))))); + result.getRouteUnits().add(new RouteUnit(each, new SQLUnit(rewriteSQL, parameters))); } return result; } @@ -81,8 +78,7 @@ public final class PreparedStatementExecutorWrapper implements JDBCExecutorWrapp @Override public Statement createStatement(final Connection connection, final SQLUnit sqlUnit, final boolean isReturnGeneratedKeys) throws SQLException { PreparedStatement result = isReturnGeneratedKeys ? connection.prepareStatement(sqlUnit.getSql(), Statement.RETURN_GENERATED_KEYS) : connection.prepareStatement(sqlUnit.getSql()); - List<Object> parameters = getRoutedParameters(sqlUnit); - for (int i = 0; i < parameters.size(); i++) { + for (int i = 0; i < sqlUnit.getParameters().size(); i++) { result.setObject(i + 1, parameters.get(i)); } return result; @@ -92,12 +88,4 @@ public final class PreparedStatementExecutorWrapper implements JDBCExecutorWrapp public boolean executeSQL(final Statement statement, final String sql, final boolean isReturnGeneratedKeys) throws SQLException { return ((PreparedStatement) statement).execute(); } - - private List<Object> getRoutedParameters(final SQLUnit sqlUnit) { - List<Object> result = new LinkedList<>(); - for (List<Object> each : sqlUnit.getParameterSets()) { - result.addAll(each); - } - return result; - } } diff --git a/sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/wrapper/StatementExecutorWrapper.java b/sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/wrapper/StatementExecutorWrapper.java index 1d2148e922a..c690941b79a 100644 --- a/sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/wrapper/StatementExecutorWrapper.java +++ b/sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/wrapper/StatementExecutorWrapper.java @@ -37,7 +37,6 @@ import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.Collections; -import java.util.List; /** * Executor wrapper for statement. @@ -62,7 +61,7 @@ public final class StatementExecutorWrapper implements JDBCExecutorWrapper { SQLRouteResult result = new SQLRouteResult(sqlStatement); for (String each : new MasterSlaveRouter( ((MasterSlaveSchema) logicSchema).getMasterSlaveRule(), GLOBAL_REGISTRY.getShardingProperties().<Boolean>getValue(ShardingPropertiesConstant.SQL_SHOW)).route(rewriteSQL)) { - result.getRouteUnits().add(new RouteUnit(each, new SQLUnit(rewriteSQL, Collections.<List<Object>>emptyList()))); + result.getRouteUnits().add(new RouteUnit(each, new SQLUnit(rewriteSQL, Collections.emptyList()))); } return result; } diff --git a/sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/schema/LogicSchemas.java b/sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/schema/LogicSchemas.java index f64d6e45e43..ab5fec3c0f9 100644 --- a/sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/schema/LogicSchemas.java +++ b/sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/schema/LogicSchemas.java @@ -33,6 +33,7 @@ import org.apache.shardingsphere.shardingproxy.config.yaml.YamlDataSourceParamet import org.apache.shardingsphere.shardingproxy.context.GlobalContext; import org.apache.shardingsphere.shardingproxy.util.DataSourceConverter; +import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; @@ -44,6 +45,7 @@ import java.util.concurrent.ConcurrentHashMap; * Logic schemas. * * @author zhangliang + * @author panjuan */ @Getter public final class LogicSchemas { @@ -74,25 +76,29 @@ public final class LogicSchemas { * @param schemaRules schema rule map */ public void init(final Map<String, Map<String, YamlDataSourceParameter>> schemaDataSources, final Map<String, RuleConfiguration> schemaRules) { - init(schemaDataSources, schemaRules, false); + init(schemaRules.keySet(), schemaDataSources, schemaRules, false); } /** * Initialize proxy context. * + * @param localSchemaNames local schema names * @param schemaDataSources data source map * @param schemaRules schema rule map * @param isUsingRegistry is using registry or not */ - public void init(final Map<String, Map<String, YamlDataSourceParameter>> schemaDataSources, + public void init(final Collection<String> localSchemaNames, final Map<String, Map<String, YamlDataSourceParameter>> schemaDataSources, final Map<String, RuleConfiguration> schemaRules, final boolean isUsingRegistry) { databaseType = JDBCDriverURLRecognizerEngine.getDatabaseType(schemaDataSources.values().iterator().next().values().iterator().next().getUrl()); - initSchemas(schemaDataSources, schemaRules, isUsingRegistry); + initSchemas(localSchemaNames, schemaDataSources, schemaRules, isUsingRegistry); } - private void initSchemas(final Map<String, Map<String, YamlDataSourceParameter>> schemaDataSources, final Map<String, RuleConfiguration> schemaRules, final boolean isUsingRegistry) { + private void initSchemas(final Collection<String> localSchemaNames, + final Map<String, Map<String, YamlDataSourceParameter>> schemaDataSources, final Map<String, RuleConfiguration> schemaRules, final boolean isUsingRegistry) { for (Entry<String, RuleConfiguration> entry : schemaRules.entrySet()) { - logicSchemas.put(entry.getKey(), createLogicSchema(entry.getKey(), schemaDataSources, entry.getValue(), isUsingRegistry)); + if (localSchemaNames.isEmpty() || localSchemaNames.contains(entry.getKey())) { + logicSchemas.put(entry.getKey(), createLogicSchema(entry.getKey(), schemaDataSources, entry.getValue(), isUsingRegistry)); + } } } diff --git a/sharding-proxy/sharding-proxy-bootstrap/src/main/java/org/apache/shardingsphere/shardingproxy/Bootstrap.java b/sharding-proxy/sharding-proxy-bootstrap/src/main/java/org/apache/shardingsphere/shardingproxy/Bootstrap.java index 726be7d625a..4dfdcdfbebc 100644 --- a/sharding-proxy/sharding-proxy-bootstrap/src/main/java/org/apache/shardingsphere/shardingproxy/Bootstrap.java +++ b/sharding-proxy/sharding-proxy-bootstrap/src/main/java/org/apache/shardingsphere/shardingproxy/Bootstrap.java @@ -100,7 +100,7 @@ public final class Bootstrap { new OrchestrationConfigurationYamlSwapper().swap(serverConfig.getOrchestration()), shardingSchemaNames)) { initShardingOrchestrationFacade(serverConfig, ruleConfigs, shardingOrchestrationFacade); GlobalContext.getInstance().init(shardingOrchestrationFacade.getConfigService().loadAuthentication(), shardingOrchestrationFacade.getConfigService().loadProperties()); - LogicSchemas.getInstance().init(getSchemaDataSourceParameterMap(shardingOrchestrationFacade), getSchemaRules(shardingOrchestrationFacade), true); + LogicSchemas.getInstance().init(shardingSchemaNames, getSchemaDataSourceParameterMap(shardingOrchestrationFacade), getSchemaRules(shardingOrchestrationFacade), true); initOpenTracing(); ShardingProxy.getInstance().start(port); }
['sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/SQLExecuteCallbackFactoryTest.java', 'sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/BatchPreparedStatementExecutorTest.java', 'sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/executor/BatchPreparedStatementExecutor.java', 'sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/wrapper/PreparedStatementExecutorWrapper.java', 'sharding-core/src/main/java/org/apache/shardingsphere/core/routing/BatchRouteUnit.java', 'sharding-opentracing/src/main/java/org/apache/shardingsphere/opentracing/hook/OpenTracingSQLExecutionHook.java', 'sharding-opentracing/src/test/java/org/apache/shardingsphere/opentracing/hook/OpenTracingSQLExecutionHookTest.java', 'sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/schema/LogicSchemas.java', 'sharding-core/src/main/java/org/apache/shardingsphere/core/routing/SQLUnit.java', 'sharding-core/src/main/java/org/apache/shardingsphere/core/routing/router/sharding/DatabaseHintSQLRouter.java', 'sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/communication/jdbc/wrapper/StatementExecutorWrapper.java', 'sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/executor/AbstractStatementExecutor.java', 'sharding-core/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java', 'sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/StatementExecutorTest.java', 'sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/PreparedStatementExecutorTest.java', 'sharding-proxy/sharding-proxy-bootstrap/src/main/java/org/apache/shardingsphere/shardingproxy/Bootstrap.java', 'sharding-core/src/main/java/org/apache/shardingsphere/core/util/SQLLogger.java', 'sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/ShardingPreparedStatementTest.java', 'sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/EncryptPreparedStatement.java']
{'.java': 19}
19
19
0
0
19
3,016,297
611,051
76,962
1,011
8,884
1,717
133
13
1,130
151
249
28
2
0
1970-01-01T00:25:51
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,508
apache/shardingsphere/1644/1643
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1643
https://github.com/apache/shardingsphere/pull/1644
https://github.com/apache/shardingsphere/pull/1644
1
fixes
Result data incomplete when there's Limit sub clause
## Bug Report ### Which version of ShardingSphere did you use? 3.0.1-SNAPSHOT ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-JDBC and Sharding-Proxy ### Expected behavior Take ShardingType.SHARDING_DATABASES for example: The SQL is single routed to demo_ds_0.t_order. SELECT * FROM t_order WHERE user_id = 0 LIMIT 5, 10; 10 rows are expected: order_id: 0, user_id: 0, status: 6 order_id: 0, user_id: 0, status: 7 order_id: 0, user_id: 0, status: 8 order_id: 0, user_id: 0, status: 9 order_id: 0, user_id: 0, status: 10 order_id: 0, user_id: 0, status: 11 order_id: 0, user_id: 0, status: 12 order_id: 0, user_id: 0, status: 13 order_id: 0, user_id: 0, status: 14 order_id: 0, user_id: 0, status: 15 ### Actual behavior Get 5 rows result: order_id: 0, user_id: 0, status: 11 order_id: 0, user_id: 0, status: 12 order_id: 0, user_id: 0, status: 13 order_id: 0, user_id: 0, status: 14 order_id: 0, user_id: 0, status: 15 ### Reason analyze (If you can) This will be happen only on single routing which do not rewrite the logical SQL's Limit sub clause. 5 rows is skipped. 5 is the offset of Limit sub clause. This is duo to offset skipping procedure in merge step. When single routing, offset should not be skipped. ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc. Take ShardingType.SHARDING_DATABASES for example: The SQL is single routed to demo_ds_0.t_order. SELECT * FROM t_order WHERE user_id = 0 LIMIT 5, 10; ### Example codes for reproduce this issue (such as a github link). Offical example.
421ebb4b9840da8a9c9e441ca23379c7d6c03be5
34ac2c256e11a3d770a67e235110e6cab0012c9e
https://github.com/apache/shardingsphere/compare/421ebb4b9840da8a9c9e441ca23379c7d6c03be5...34ac2c256e11a3d770a67e235110e6cab0012c9e
diff --git a/sharding-core/src/main/java/io/shardingsphere/core/merger/dql/DQLMergeEngine.java b/sharding-core/src/main/java/io/shardingsphere/core/merger/dql/DQLMergeEngine.java index 9077f445e92..9cd897d915d 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/merger/dql/DQLMergeEngine.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/merger/dql/DQLMergeEngine.java @@ -120,7 +120,7 @@ public final class DQLMergeEngine implements MergeEngine { private MergedResult decorate(final MergedResult mergedResult) throws SQLException { Limit limit = selectStatement.getLimit(); - if (null == limit) { + if (null == limit || 1 == queryResults.size()) { return mergedResult; } if (DatabaseType.MySQL == limit.getDatabaseType() || DatabaseType.PostgreSQL == limit.getDatabaseType() || DatabaseType.H2 == limit.getDatabaseType()) { diff --git a/sharding-core/src/test/java/io/shardingsphere/core/merger/dql/DQLMergeEngineTest.java b/sharding-core/src/test/java/io/shardingsphere/core/merger/dql/DQLMergeEngineTest.java index e3633e3e532..97939af1b12 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/merger/dql/DQLMergeEngineTest.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/merger/dql/DQLMergeEngineTest.java @@ -18,6 +18,7 @@ package io.shardingsphere.core.merger.dql; import com.google.common.base.Optional; +import com.google.common.collect.Lists; import io.shardingsphere.core.constant.AggregationType; import io.shardingsphere.core.constant.DatabaseType; import io.shardingsphere.core.constant.OrderDirection; @@ -41,6 +42,7 @@ import org.junit.Test; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; +import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -53,6 +55,8 @@ public final class DQLMergeEngineTest { private DQLMergeEngine mergeEngine; + private List<QueryResult> singleQueryResult; + private List<QueryResult> queryResults; private SelectStatement selectStatement; @@ -65,7 +69,12 @@ public final class DQLMergeEngineTest { when(resultSet.getMetaData()).thenReturn(resultSetMetaData); when(resultSetMetaData.getColumnCount()).thenReturn(1); when(resultSetMetaData.getColumnLabel(1)).thenReturn("count(*)"); - queryResults = Collections.<QueryResult>singletonList(new TestQueryResult(resultSet)); + singleQueryResult = Collections.<QueryResult>singletonList(new TestQueryResult(resultSet)); + List<ResultSet> resultSets = Lists.newArrayList(resultSet, mock(ResultSet.class), mock(ResultSet.class), mock(ResultSet.class)); + queryResults = new ArrayList<>(resultSets.size()); + for (ResultSet each : resultSets) { + queryResults.add(new TestQueryResult(each)); + } selectStatement = new SelectStatement(); } @@ -75,6 +84,13 @@ public final class DQLMergeEngineTest { assertThat(mergeEngine.merge(), instanceOf(IteratorStreamMergedResult.class)); } + @Test + public void assertBuildIteratorStreamMergedResultWithLimit() throws SQLException { + selectStatement.setLimit(new Limit(DatabaseType.MySQL)); + mergeEngine = new DQLMergeEngine(singleQueryResult, selectStatement); + assertThat(mergeEngine.merge(), instanceOf(IteratorStreamMergedResult.class)); + } + @Test public void assertBuildIteratorStreamMergedResultWithMySQLLimit() throws SQLException { selectStatement.setLimit(new Limit(DatabaseType.MySQL));
['sharding-core/src/test/java/io/shardingsphere/core/merger/dql/DQLMergeEngineTest.java', 'sharding-core/src/main/java/io/shardingsphere/core/merger/dql/DQLMergeEngine.java']
{'.java': 2}
2
2
0
0
2
2,439,030
509,803
67,670
916
87
23
2
1
1,662
258
520
55
0
0
1970-01-01T00:25:45
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,505
apache/shardingsphere/1705/1704
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1704
https://github.com/apache/shardingsphere/pull/1705
https://github.com/apache/shardingsphere/pull/1705
1
fixes
CommandExecutor.writeMoreResults deadlock
## Bug Report **For English only**, other languages will not accept. Before report a bug, make sure you have: - Searched open and closed [GitHub issues](https://github.com/sharding-sphere/sharding-sphere/issues). - Read documentation: [ShardingSphere Doc](http://shardingsphere.io/document/current/en/overview/). Please pay attention on issues you submitted, because we maybe need more details. If no response **more than 7 days** and we cannot reproduce it on current information, we will **close it**. Please answer these questions before submitting your issue. Thanks! ### Which version of ShardingSphere did you use? 3.1.0-SNAPSHOT ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-Proxy ### Expected behavior When flag isWritable turn to false, it can turn back to ture in future. ### Actual behavior When flag isWritable turn to false, it can't turn back to ture in future. ### Reason analyze (If you can) When flag isWritable turn to false, the data that has been written didn't flush. So the client can't read any data, this cause the water level high. ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc. set proxy.frontend.flush.threshold: 1000000 ### Example codes for reproduce this issue (such as a github link). N.A.
37177982e5db638419e8ae42d6c53cba06057952
1d80445e0dabebf74536ed246a9b43fc51a1ffc3
https://github.com/apache/shardingsphere/compare/37177982e5db638419e8ae42d6c53cba06057952...1d80445e0dabebf74536ed246a9b43fc51a1ffc3
diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/mysql/CommandExecutor.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/mysql/CommandExecutor.java index 3c3d9cf89d1..a6b0e4e5cdc 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/mysql/CommandExecutor.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/mysql/CommandExecutor.java @@ -105,6 +105,7 @@ public final class CommandExecutor implements Runnable { while (queryCommandPacket.next()) { count++; while (!context.channel().isWritable() && context.channel().isActive()) { + context.flush(); synchronized (frontendHandler) { try { frontendHandler.wait();
['sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/mysql/CommandExecutor.java']
{'.java': 1}
1
1
0
0
1
2,347,466
489,331
64,972
865
33
4
1
1
1,363
192
311
34
2
0
1970-01-01T00:25:46
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,504
apache/shardingsphere/1706/1671
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1671
https://github.com/apache/shardingsphere/pull/1706
https://github.com/apache/shardingsphere/pull/1706
1
fixes
Upgrade from 3.0.0 to 3.1.0.M1 error reporting,java.lang.NullPointerException: Cannot invoke method mod() on null object
sharding code: > sharding database column name : traceId sharding strategy :ds${traceId%4} ``` // 配置真实数据源 Map<String, DataSource> dataSourceMap = new HashMap<>(); dataSourceMap.put("ds0",ds0DataSource()); dataSourceMap.put("ds1",ds1DataSource()); dataSourceMap.put("ds2",ds2DataSource()); dataSourceMap.put("ds3",ds3DataSource()); dataSourceMap.put("mainDataSource",mainDataSource()); // 配置Order表规则 TableRuleConfiguration orderTableRuleConfig = new TableRuleConfiguration(); orderTableRuleConfig.setLogicTable("push_message"); orderTableRuleConfig.setActualDataNodes("ds${0..3}.push_message"); //分布式主键 orderTableRuleConfig.setKeyGeneratorColumnName("id"); ShardingDefaultKeyGenerator shardingDefaultKeyGenerator = new ShardingDefaultKeyGenerator(); orderTableRuleConfig.setKeyGenerator(shardingDefaultKeyGenerator); // 配置分库策略 orderTableRuleConfig.setDatabaseShardingStrategyConfig( new InlineShardingStrategyConfiguration("traceId", "ds${traceId%4}")); // 配置分片规则 ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration(); shardingRuleConfig.getTableRuleConfigs().add(orderTableRuleConfig); shardingRuleConfig.setDefaultDataSourceName("mainDataSource"); Properties properties = new Properties(); properties.setProperty("sql.show","true"); properties.setProperty("max.connections.size.per.query","200"); properties.setProperty("executor.size",String.valueOf(Runtime.getRuntime().availableProcessors() * 2)); DataSource dataSource = ShardingDataSourceFactory.createDataSource( dataSourceMap, shardingRuleConfig, new ConcurrentHashMap(), properties); return dataSource ``` error info: ``` java.lang.NullPointerException: Cannot invoke method mod() on null object at org.codehaus.groovy.runtime.NullObject.invokeMethod(NullObject.java:91) at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:48) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) at org.codehaus.groovy.runtime.callsite.NullCallSite.call(NullCallSite.java:35) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125) at Script2$_run_closure1.doCall(Script2.groovy:1) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93) at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325) at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:294) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1019) at groovy.lang.Closure.call(Closure.java:426) at groovy.lang.Closure.call(Closure.java:420) at com.fly.ApplicationTests.testInline(ApplicationTests.java:98) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) ``` sharding key is hump naming,calculating rote Error, ```java //InlineShardingStrategy.java private String execute(final PreciseShardingValue shardingValue) { Closure<?> result = closure.rehydrate(new Expando(), null, null); result.setResolveStrategy(Closure.DELEGATE_ONLY); //method toLowerCase() result.setProperty(shardingValue.getColumnName().toLowerCase(), shardingValue.getValue()); return result.call().toString(); } ``` unit test : 1. test fail ``` @Test public void testInline(){ Closure<?> closure = new InlineExpressionParser("ds${traceId%4}").evaluateClosure(); Closure<?> result = closure.rehydrate(new Expando(), null, null); result.setResolveStrategy(Closure.DELEGATE_ONLY); PreciseShardingValue shardingValue = new PreciseShardingValue("push_message","traceId",342342); result.setProperty(shardingValue.getColumnName().toLowerCase(), shardingValue.getValue()); System.out.println("--------:"+result.call().toString()); } ``` 2. test pass ``` @Test public void testInline(){ Closure<?> closure = new InlineExpressionParser("ds${traceid%4}").evaluateClosure(); Closure<?> result = closure.rehydrate(new Expando(), null, null); result.setResolveStrategy(Closure.DELEGATE_ONLY); PreciseShardingValue shardingValue = new PreciseShardingValue("push_message","traceId",342342); result.setProperty(shardingValue.getColumnName().toLowerCase(), shardingValue.getValue()); System.out.println("--------:"+result.call().toString()); } ```
3dbe77790c3ff3fafa685823165890e20f439d04
2a61efcba24cc95a23e50ecff6586742bd3ae95d
https://github.com/apache/shardingsphere/compare/3dbe77790c3ff3fafa685823165890e20f439d04...2a61efcba24cc95a23e50ecff6586742bd3ae95d
diff --git a/sharding-core/src/main/java/io/shardingsphere/core/routing/strategy/inline/InlineShardingStrategy.java b/sharding-core/src/main/java/io/shardingsphere/core/routing/strategy/inline/InlineShardingStrategy.java index 4923c1d4d37..cd7e7ed2691 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/routing/strategy/inline/InlineShardingStrategy.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/routing/strategy/inline/InlineShardingStrategy.java @@ -82,7 +82,7 @@ public final class InlineShardingStrategy implements ShardingStrategy { private String execute(final PreciseShardingValue shardingValue) { Closure<?> result = closure.rehydrate(new Expando(), null, null); result.setResolveStrategy(Closure.DELEGATE_ONLY); - result.setProperty(shardingValue.getColumnName().toLowerCase(), shardingValue.getValue()); + result.setProperty(shardingValue.getColumnName(), shardingValue.getValue()); return result.call().toString(); }
['sharding-core/src/main/java/io/shardingsphere/core/routing/strategy/inline/InlineShardingStrategy.java']
{'.java': 1}
1
1
0
0
1
2,347,507
489,309
64,971
865
185
30
2
1
7,564
284
1,633
130
0
5
1970-01-01T00:25:46
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
329
keycloak/keycloak/359/16818
keycloak
keycloak
https://github.com/keycloak/keycloak/issues/16818
https://github.com/keycloak/keycloak/pull/359
https://github.com/keycloak/keycloak/issues/16818#issuecomment-1415724725
1
resolve
Any tests using PhantomJS failing in some newer linux environments
### Before reporting an issue - [X] I have searched existing issues - [X] I have reproduced the issue with the latest release ### Area testsuite ### Describe the bug After setup new laptop, Any test using PhantomJS is failing for me with the error like this: ``` 09:01:26,169 INFO [org.keycloak.testsuite.adapter.servlet.DemoServletsAdapterTest] [DemoServletsAdapterTest] testWithoutKeycloakConf() STARTED Feb 03, 2023 9:01:26 AM org.openqa.selenium.phantomjs.PhantomJSDriverService <init> INFO: executable: /home/mposolda/IdeaProjects/keycloak/testsuite/integration-arquillian/tests/base/target/drone/1c947d57fce2f21ce0b43fe2ed7cd361/phantomjs-2.1.1-linux-x86_64/bin/phantomjs Feb 03, 2023 9:01:26 AM org.openqa.selenium.phantomjs.PhantomJSDriverService <init> INFO: port: 1443 Feb 03, 2023 9:01:26 AM org.openqa.selenium.phantomjs.PhantomJSDriverService <init> INFO: arguments: [--ignore-ssl-errors=true, --web-security=false, --webdriver=1443, --webdriver-logfile=/home/mposolda/IdeaProjects/keycloak/testsuite/integration-arquillian/tests/base/phantomjsdriver.log] Feb 03, 2023 9:01:26 AM org.openqa.selenium.phantomjs.PhantomJSDriverService <init> INFO: environment: {} Auto configuration failed 139991832651712:error:25066067:DSO support routines:DLFCN_LOAD:could not load the shared library:dso_dlfcn.c:185:filename(libproviders.so): libproviders.so: cannot open shared object file: No such file or directory 139991832651712:error:25070067:DSO support routines:DSO_load:could not load the shared library:dso_lib.c:244: 139991832651712:error:0E07506E:configuration file routines:MODULE_LOAD_DSO:error loading dso:conf_mod.c:285:module=providers, path=providers 139991832651712:error:0E076071:configuration file routines:MODULE_RUN:unknown module name:conf_mod.c:222:module=providers Feb 03, 2023 9:01:46 AM org.openqa.selenium.os.OsProcess checkForError SEVERE: org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1) 09:01:46,486 ERROR [org.keycloak.testsuite.adapter.servlet.DemoServletsAdapterTest] [DemoServletsAdapterTest] testWithoutKeycloakConf() FAILED ``` I am seeing this on Ubuntu 22.04 as well as on RHEL 9.1 virtual machine. Java version is OpenJDK11 or OpenJDK17. ### Solution It helps to set this environment variable: ``` export OPENSSL_CONF=/dev/null ``` See for example here for more details https://github.com/nodejs/node/issues/43132 Can we eventually set this variable by default to avoid such issues? ### Version 20.0.3 ### How to Reproduce? For example run this test on Ubuntu 22.04 or on RHEL 9.1 (reproduced with RHEL 9.1 virtual machine). Java version is OpenJDK11 or OpenJDK17. ``` mvn clean install -Dtest=DemoServletsAdapterTest ```
e25b2b05aee074a0ec2bf51118d4249e17e230b8
201b35be54575d9c83a6ee4b08c5d5b7a094b5d9
https://github.com/keycloak/keycloak/compare/e25b2b05aee074a0ec2bf51118d4249e17e230b8...201b35be54575d9c83a6ee4b08c5d5b7a094b5d9
diff --git a/integration/tomcat7/adapter/src/main/java/org/keycloak/adapters/tomcat7/AuthenticatedActionsValve.java b/integration/tomcat7/adapter/src/main/java/org/keycloak/adapters/tomcat7/AuthenticatedActionsValve.java index 9088533faa..541fc90ceb 100755 --- a/integration/tomcat7/adapter/src/main/java/org/keycloak/adapters/tomcat7/AuthenticatedActionsValve.java +++ b/integration/tomcat7/adapter/src/main/java/org/keycloak/adapters/tomcat7/AuthenticatedActionsValve.java @@ -11,6 +11,7 @@ import org.apache.catalina.Valve; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.catalina.valves.ValveBase; +import org.keycloak.adapters.AdapterDeploymentContext; import org.keycloak.adapters.AuthenticatedActionsHandler; import org.keycloak.adapters.KeycloakDeployment; @@ -27,10 +28,10 @@ import org.keycloak.adapters.KeycloakDeployment; */ public class AuthenticatedActionsValve extends ValveBase { private static final Logger log = Logger.getLogger(""+AuthenticatedActionsValve.class); - protected KeycloakDeployment deployment; + protected AdapterDeploymentContext deploymentContext; - public AuthenticatedActionsValve(KeycloakDeployment deployment, Valve next, Container container, ObjectName objectName) { - this.deployment = deployment; + public AuthenticatedActionsValve(AdapterDeploymentContext deploymentContext, Valve next, Container container, ObjectName controller) { + this.deploymentContext = deploymentContext; if (next == null) throw new RuntimeException("WTF is next null?!"); setNext(next); setContainer(container); @@ -40,10 +41,17 @@ public class AuthenticatedActionsValve extends ValveBase { @Override public void invoke(Request request, Response response) throws IOException, ServletException { log.finer("AuthenticatedActionsValve.invoke" + request.getRequestURI()); - AuthenticatedActionsHandler handler = new AuthenticatedActionsHandler(deployment, new CatalinaHttpFacade(request, response)); - if (handler.handledRequest()) { - return; + CatalinaHttpFacade facade = new CatalinaHttpFacade(request, response); + KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade); + if (deployment != null && deployment.isConfigured()) { + AuthenticatedActionsHandler handler = new AuthenticatedActionsHandler(deployment, new CatalinaHttpFacade(request, response)); + if (handler.handledRequest()) { + return; + } + } getNext().invoke(request, response); } + + } diff --git a/integration/tomcat7/adapter/src/main/java/org/keycloak/adapters/tomcat7/KeycloakAuthenticatorValve.java b/integration/tomcat7/adapter/src/main/java/org/keycloak/adapters/tomcat7/KeycloakAuthenticatorValve.java index 2dd4e97563..5ce3050d5c 100755 --- a/integration/tomcat7/adapter/src/main/java/org/keycloak/adapters/tomcat7/KeycloakAuthenticatorValve.java +++ b/integration/tomcat7/adapter/src/main/java/org/keycloak/adapters/tomcat7/KeycloakAuthenticatorValve.java @@ -23,8 +23,10 @@ import org.apache.catalina.core.StandardContext; import org.apache.catalina.deploy.LoginConfig; import org.keycloak.KeycloakSecurityContext; import org.keycloak.adapters.AdapterConstants; +import org.keycloak.adapters.AdapterDeploymentContext; import org.keycloak.adapters.AuthChallenge; import org.keycloak.adapters.AuthOutcome; +import org.keycloak.adapters.HttpFacade; import org.keycloak.adapters.KeycloakDeployment; import org.keycloak.adapters.KeycloakDeploymentBuilder; import org.keycloak.adapters.PreAuthActionsHandler; @@ -43,7 +45,7 @@ import org.keycloak.adapters.RefreshableKeycloakSecurityContext; public class KeycloakAuthenticatorValve extends FormAuthenticator implements LifecycleListener { private final static Logger log = Logger.getLogger(""+KeycloakAuthenticatorValve.class); protected CatalinaUserSessionManagement userSessionManagement = new CatalinaUserSessionManagement(); - protected KeycloakDeployment deployment; + protected AdapterDeploymentContext deploymentContext; @Override public void lifecycleEvent(LifecycleEvent event) { @@ -64,9 +66,17 @@ public class KeycloakAuthenticatorValve extends FormAuthenticator implements Lif } public void initInternal() { - this.deployment = KeycloakDeploymentBuilder.build(getConfigInputStream(context)); - log.info("deployment realm:" + deployment.getRealm() + " resource:" + deployment.getResourceName()); - AuthenticatedActionsValve actions = new AuthenticatedActionsValve(deployment, getNext(), getContainer(), getObjectName()); + InputStream configInputStream = getConfigInputStream(context); + KeycloakDeployment kd = null; + if (configInputStream == null) { + log.warning("No adapter configuration. Keycloak is unconfigured and will deny all requests."); + kd = new KeycloakDeployment(); + } else { + kd = KeycloakDeploymentBuilder.build(configInputStream); + } + deploymentContext = new AdapterDeploymentContext(kd); + context.getServletContext().setAttribute(AdapterDeploymentContext.class.getName(), deploymentContext); + AuthenticatedActionsValve actions = new AuthenticatedActionsValve(deploymentContext, getNext(), getContainer(), getObjectName()); setNext(actions); } @@ -102,12 +112,12 @@ public class KeycloakAuthenticatorValve extends FormAuthenticator implements Lif @Override public void invoke(Request request, Response response) throws IOException, ServletException { try { - PreAuthActionsHandler handler = new PreAuthActionsHandler(userSessionManagement, deployment, - new CatalinaHttpFacade(request, response)); + CatalinaHttpFacade facade = new CatalinaHttpFacade(request, response); + PreAuthActionsHandler handler = new PreAuthActionsHandler(userSessionManagement, deploymentContext, facade); if (handler.handleRequest()) { return; } - checkKeycloakSession(request); + checkKeycloakSession(request, facade); super.invoke(request, response); } finally { } @@ -116,6 +126,11 @@ public class KeycloakAuthenticatorValve extends FormAuthenticator implements Lif @Override public boolean authenticate(Request request, HttpServletResponse response, LoginConfig config) throws IOException { CatalinaHttpFacade facade = new CatalinaHttpFacade(request, response); + KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade); + if (deployment == null || !deployment.isConfigured()) { + return false; + } + CatalinaRequestAuthenticator authenticator = new CatalinaRequestAuthenticator(deployment, this, userSessionManagement, facade, request); AuthOutcome outcome = authenticator.authenticate(); if (outcome == AuthOutcome.AUTHENTICATED) { @@ -132,29 +147,22 @@ public class KeycloakAuthenticatorValve extends FormAuthenticator implements Lif } /** - * Checks that access token is still valid. Will attempt refresh of token if - * it is not. - * + * Checks that access token is still valid. Will attempt refresh of token if it is not. + * * @param request */ - protected void checkKeycloakSession(Request request) { - if (request.getSessionInternal(false) == null || request.getSessionInternal().getPrincipal() == null) - return; - RefreshableKeycloakSecurityContext session = (RefreshableKeycloakSecurityContext) request.getSessionInternal() - .getNote(KeycloakSecurityContext.class.getName()); - if (session == null) - return; + protected void checkKeycloakSession(Request request, HttpFacade facade) { + if (request.getSessionInternal(false) == null || request.getSessionInternal().getPrincipal() == null) return; + RefreshableKeycloakSecurityContext session = (RefreshableKeycloakSecurityContext) request.getSessionInternal().getNote(KeycloakSecurityContext.class.getName()); + if (session == null) return; // just in case session got serialized - session.setDeployment(deployment); - if (session.isActive()) - return; + if (session.getDeployment() == null) session.setDeployment(deploymentContext.resolveDeployment(facade)); + if (session.isActive()) return; - // FYI: A refresh requires same scope, so same roles will be set. - // Otherwise, refresh will fail and token will + // FYI: A refresh requires same scope, so same roles will be set. Otherwise, refresh will fail and token will // not be updated session.refreshExpiredToken(); - if (session.isActive()) - return; + if (session.isActive()) return; request.getSessionInternal().removeNote(KeycloakSecurityContext.class.getName()); request.setUserPrincipal(null);
['integration/tomcat7/adapter/src/main/java/org/keycloak/adapters/tomcat7/KeycloakAuthenticatorValve.java', 'integration/tomcat7/adapter/src/main/java/org/keycloak/adapters/tomcat7/AuthenticatedActionsValve.java']
{'.java': 2}
2
2
0
0
2
1,629,567
326,972
48,927
499
4,818
931
76
2
2,772
254
782
55
1
3
1970-01-01T00:23:19
16,979
Java
{'Java': 35144476, 'TypeScript': 3163746, 'JavaScript': 205312, 'FreeMarker': 164182, 'Python': 79730, 'Scala': 67371, 'XSLT': 43979, 'CSS': 43935, 'Shell': 30081, 'HTML': 25543, 'Batchfile': 5364, 'Groovy': 4915, 'Mustache': 4694, 'Dockerfile': 2543, 'Gnuplot': 2173, 'AMPL': 1552, 'Fluent': 217}
Apache License 2.0
120
ibotpeaches/apktool/1570/1564
ibotpeaches
apktool
https://github.com/iBotPeaches/Apktool/issues/1564
https://github.com/iBotPeaches/Apktool/pull/1570
https://github.com/iBotPeaches/Apktool/pull/1570
1
fixes
Could not decode res(arsc)
### Information 1. **Apktool Version (`2.2.3`)** - 2. **Operating System (Windows)** - 3. **APK From? I don't know.** - ### Stacktrace/Logcat ``` I: Using Apktool 2.2.3 on test.zip I: Loading resource table... W: null Exception in thread "main" java.lang.NullPointerException at brut.androlib.res.data.value.ResValueFactory.factory(ResValueFactory.java:74) at brut.androlib.res.decoder.ARSCDecoder.readValue(ARSCDecoder.java:315) at brut.androlib.res.decoder.ARSCDecoder.readEntry(ARSCDecoder.java:241) at brut.androlib.res.decoder.ARSCDecoder.readTableType(ARSCDecoder.java:226) at brut.androlib.res.decoder.ARSCDecoder.readTableTypeSpec(ARSCDecoder.java:156) at brut.androlib.res.decoder.ARSCDecoder.readTablePackage(ARSCDecoder.java:118) at brut.androlib.res.decoder.ARSCDecoder.readTableHeader(ARSCDecoder.java:80) at brut.androlib.res.decoder.ARSCDecoder.decode(ARSCDecoder.java:47) at brut.androlib.res.AndrolibResources.getResPackagesFromApk(AndrolibResources.java:562) at brut.androlib.res.AndrolibResources.loadMainPkg(AndrolibResources.java:72) at brut.androlib.res.AndrolibResources.getResTable(AndrolibResources.java:64) at brut.androlib.Androlib.getResTable(Androlib.java:68) at brut.androlib.ApkDecoder.setTargetSdkVersion(ApkDecoder.java:207) at brut.androlib.ApkDecoder.decode(ApkDecoder.java:109) at brut.apktool.Main.cmdDecode(Main.java:166) at brut.apktool.Main.main(Main.java:81) ``` ### Steps to Reproduce 1. `apktool d -s test.zip ` ### APK [test.zip](https://github.com/iBotPeaches/Apktool/files/1157951/test.zip)
ad59fdd378fe56fb108a53be2a89c9c05b1018d1
15bc16c6bd40eec1ce5de6177fa178675ac5b9fa
https://github.com/ibotpeaches/apktool/compare/ad59fdd378fe56fb108a53be2a89c9c05b1018d1...15bc16c6bd40eec1ce5de6177fa178675ac5b9fa
diff --git a/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResValueFactory.java b/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResValueFactory.java index c8d30b85..e3db655f 100644 --- a/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResValueFactory.java +++ b/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResValueFactory.java @@ -71,6 +71,9 @@ public class ResValueFactory { } public ResIntBasedValue factory(String value, int rawValue) { + if (value == null) { + return new ResFileValue("", rawValue); + } if (value.startsWith("res/")) { return new ResFileValue(value, rawValue); }
['brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResValueFactory.java']
{'.java': 1}
1
1
0
0
1
474,222
106,474
13,907
97
92
20
3
1
1,706
85
465
37
1
1
1970-01-01T00:25:01
16,931
Java
{'Java': 703364, 'Kotlin': 10370, 'Shell': 4847, 'Smali': 3679, 'Batchfile': 1154}
Apache License 2.0
116
ibotpeaches/apktool/1764/1741
ibotpeaches
apktool
https://github.com/iBotPeaches/Apktool/issues/1741
https://github.com/iBotPeaches/Apktool/pull/1764
https://github.com/iBotPeaches/Apktool/pull/1764
1
fixes
Bugs during apktool.jar compieltion from sources
@iBotPeaches With latest updates on source code (3 days ago) I got this error during compilation on final tests ``` [MENTION=292510]brut[/MENTION].androlib.aapt1.BuildAndDecodeTest > classMethod FAILED java.lang.NullPointerException at brut.androlib.res.decoder.ResFileDecoder.decode(ResFileDecoder.java:132) at brut.androlib.res.decoder.ResFileDecoder.decode(ResFileDecoder.java:115) at brut.androlib.res.AndrolibResources.decode(AndrolibResources.java:258) at brut.androlib.Androlib.decodeResourcesFull(Androlib.java:131) at brut.androlib.ApkDecoder.decode(ApkDecoder.java:124) at brut.androlib.aapt1.BuildAndDecodeTest.beforeClass(BuildAndDecodeTest.java:61) brut.androlib.aapt1.LargeIntsInManifestTest > checkIfLargeIntsAreHandledTest FAILED java.lang.NullPointerException at brut.androlib.res.decoder.ResFileDecoder.decode(ResFileDecoder.java:132) at brut.androlib.res.decoder.ResFileDecoder.decode(ResFileDecoder.java:115) at brut.androlib.res.AndrolibResources.decode(AndrolibResources.java:258) at brut.androlib.Androlib.decodeResourcesFull(Androlib.java:131) at brut.androlib.ApkDecoder.decode(ApkDecoder.java:124) at brut.androlib.aapt1.LargeIntsInManifestTest.checkIfLargeIntsAreHandledTest(LargeIntsInManifestTest.java:66) brut.androlib.aapt1.ProviderAttributeTest > isProviderStringReplacementWorking FAILED java.lang.NullPointerException at brut.androlib.res.decoder.ResFileDecoder.decode(ResFileDecoder.java:132) at brut.androlib.res.decoder.ResFileDecoder.decode(ResFileDecoder.java:115) at brut.androlib.res.AndrolibResources.decode(AndrolibResources.java:258) at brut.androlib.Androlib.decodeResourcesFull(Androlib.java:131) at brut.androlib.ApkDecoder.decode(ApkDecoder.java:124) at brut.androlib.aapt1.ProviderAttributeTest.isProviderStringReplacementWorking(ProviderAttributeTest.java:70) brut.androlib.aapt1.UnknownCompressionTest > doubleExtensionStoredTest FAILED brut.directory.PathNotExist: Entry not found: assets/bin/Data/two.extension.file at brut.directory.ZipRODirectory.getCompressionLevel(ZipRODirectory.java:108) at brut.androlib.aapt1.UnknownCompressionTest.doubleExtensionStoredTest(UnknownCompressionTest.java:80) brut.androlib.aapt1.UnknownCompressionTest > pkmExtensionDeflatedTest FAILED brut.directory.PathNotExist: Entry not found: assets/bin/Data/test.pkm at brut.directory.ZipRODirectory.getCompressionLevel(ZipRODirectory.java:108) at brut.androlib.aapt1.UnknownCompressionTest.pkmExtensionDeflatedTest(UnknownCompressionTest.java:69) 59 tests completed, 5 failed ```
e679d7161561145b02220535c9c229ae8603e524
6b9fb5bb51ca647cfc0c6966716ac00a0513282e
https://github.com/ibotpeaches/apktool/compare/e679d7161561145b02220535c9c229ae8603e524...6b9fb5bb51ca647cfc0c6966716ac00a0513282e
diff --git a/brut.j.dir/src/main/java/brut/directory/ZipUtils.java b/brut.j.dir/src/main/java/brut/directory/ZipUtils.java index 7898b19d..57cfd017 100644 --- a/brut.j.dir/src/main/java/brut/directory/ZipUtils.java +++ b/brut.j.dir/src/main/java/brut/directory/ZipUtils.java @@ -54,7 +54,8 @@ public class ZipUtils { throws BrutException, IOException { for (final File file : folder.listFiles()) { if (file.isFile()) { - final ZipEntry zipEntry = new ZipEntry(BrutIO.sanitizeUnknownFile(folder, file.getPath().substring(prefixLength))); + final String cleanedPath = BrutIO.sanitizeUnknownFile(folder, file.getPath().substring(prefixLength)); + final ZipEntry zipEntry = new ZipEntry(BrutIO.normalizePath(cleanedPath)); // aapt binary by default takes in parameters via -0 arsc to list extensions that shouldn't be // compressed. We will replicate that behavior diff --git a/brut.j.util/src/main/java/brut/util/BrutIO.java b/brut.j.util/src/main/java/brut/util/BrutIO.java index e58c7964..20d5b09f 100644 --- a/brut.j.util/src/main/java/brut/util/BrutIO.java +++ b/brut.j.util/src/main/java/brut/util/BrutIO.java @@ -97,6 +97,16 @@ public class BrutIO { return canonicalEntryPath.substring(canonicalDirPath.length()); } + public static String normalizePath(String path) { + char separator = File.separatorChar; + + if (separator != '/') { + return path.replace(separator, '/'); + } + + return path; + } + public static void copy(File inputFile, ZipOutputStream outputFile) throws IOException { try ( FileInputStream fis = new FileInputStream(inputFile)
['brut.j.util/src/main/java/brut/util/BrutIO.java', 'brut.j.dir/src/main/java/brut/directory/ZipUtils.java']
{'.java': 2}
2
2
0
0
2
491,864
110,335
14,408
98
573
107
13
2
2,758
103
662
43
0
1
1970-01-01T00:25:22
16,931
Java
{'Java': 703364, 'Kotlin': 10370, 'Shell': 4847, 'Smali': 3679, 'Batchfile': 1154}
Apache License 2.0
118
ibotpeaches/apktool/1641/1639
ibotpeaches
apktool
https://github.com/iBotPeaches/Apktool/issues/1639
https://github.com/iBotPeaches/Apktool/pull/1641
https://github.com/iBotPeaches/Apktool/pull/1641
1
fixes
Regression: if frame-path does not exist
https://github.com/iBotPeaches/Apktool/blob/3ec4f360ab09782421e47d16f88a95dd7f7d2058/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/AndrolibResources.java#L793 Ten lines further down the directory is created if it does not exist already.
97003d5c70eebd73ea57b1faca8a2f4531126276
c23c1303dd79d057af0132e697ffc62260704969
https://github.com/ibotpeaches/apktool/compare/97003d5c70eebd73ea57b1faca8a2f4531126276...c23c1303dd79d057af0132e697ffc62260704969
diff --git a/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/AndrolibResources.java b/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/AndrolibResources.java index 05c8e840..76aea94f 100644 --- a/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/AndrolibResources.java +++ b/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/AndrolibResources.java @@ -790,7 +790,7 @@ final public class AndrolibResources { File dir = new File(path); - if (!dir.isDirectory()) { + if (!dir.isDirectory() && dir.isFile()) { throw new AndrolibException("--frame-path is set to a file, not a directory."); }
['brut.apktool/apktool-lib/src/main/java/brut/androlib/res/AndrolibResources.java']
{'.java': 1}
1
1
0
0
1
477,400
107,240
14,019
97
85
18
2
1
250
15
84
3
1
0
1970-01-01T00:25:07
16,931
Java
{'Java': 703364, 'Kotlin': 10370, 'Shell': 4847, 'Smali': 3679, 'Batchfile': 1154}
Apache License 2.0
119
ibotpeaches/apktool/1601/1444
ibotpeaches
apktool
https://github.com/iBotPeaches/Apktool/issues/1444
https://github.com/iBotPeaches/Apktool/pull/1601
https://github.com/iBotPeaches/Apktool/pull/1601
1
fixes
APKTool 2.2.2 - ClassCastException ResColorValue -> ResAttr
https://github.com/iBotPeaches/Apktool/issues/1060 It is almost the same issue with above. Apktook tried to cast ResStringValue to ResAttr and it got an exception. Only this time it is ResColorValue. I personally modified the source as above and rebuilt the apktool, and it decompiled the apk without a problem. I'd like to report here just in case it is a bug. ``` 10:36 $ git diff diff --git a/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResStyleValue.java b/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResStyleValue.java index cc96e65..acba323 100644 --- a/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResStyleValue.java +++ b/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResStyleValue.java @@ -68,7 +68,7 @@ public class ResStyleValue extends ResBagValue implements if (resource.contains("ResReferenceValue@")) { continue; } else if (resource.contains("ResStringValue@") || resource.contains("ResStyleValue@") || - resource.contains("ResBoolValue@")) { + resource.contains("ResBoolValue@") || resource.contains("ResColorValue@")) { name = "@" + spec.getFullName(res.getResSpec().getPackage(), false); } else { ResAttr attr = (ResAttr) spec.getDefaultResource().getValue(); ``` ### Information 1. **Apktool Version (`apktool -version`)** - 2.2.2 2. **Operating System (Mac, Linux, Windows)** - Windows 3. **APK From? (Playstore, ROM, Other)** - Playstore ### Stacktrace/Logcat ``` $ java -jar ../apktool_2.2.2.jar d -f xxx.apk I: Using Apktool 2.2.2 on xxx.apk I: Loading resource table... I: Decoding AndroidManifest.xml with resources... I: Loading resource table from file: C:\\Users\\yyy\\AppData\\Local\\apktool\\framework\\1.apk I: Regular manifest package... I: Decoding file-resources... I: Decoding values */* XMLs... Exception in thread "main" java.lang.ClassCastException: brut.androlib.res.data.value.ResColorValue cannot be cast to brut.androlib.res.data.value.ResAttr at brut.androlib.res.data.value.ResStyleValue.serializeToResValuesXml(ResStyleValue.java:74) at brut.androlib.res.AndrolibResources.generateValuesFile(AndrolibResources.java:517) at brut.androlib.res.AndrolibResources.decode(AndrolibResources.java:267) at brut.androlib.Androlib.decodeResourcesFull(Androlib.java:131) at brut.androlib.ApkDecoder.decode(ApkDecoder.java:108) at brut.apktool.Main.cmdDecode(Main.java:166) at brut.apktool.Main.main(Main.java:81) ``` ### Steps to Reproduce 1. java -jar ../apktool_2.2.2.jar d -f xxx.apk
481299c748bb7d692cd9da4971a7879c17234e35
9abaa4ee30e5dcab9182f6d835a30ea8f406733f
https://github.com/ibotpeaches/apktool/compare/481299c748bb7d692cd9da4971a7879c17234e35...9abaa4ee30e5dcab9182f6d835a30ea8f406733f
diff --git a/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResStyleValue.java b/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResStyleValue.java index 297d3d51..d6df9629 100644 --- a/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResStyleValue.java +++ b/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResStyleValue.java @@ -63,17 +63,15 @@ public class ResStyleValue extends ResBagValue implements String name = null; String value = null; - String resource = spec.getDefaultResource().getValue().toString(); - // hacky-fix remove bad ReferenceVars - if (resource.contains("ResReferenceValue@")) { + ResValue resource = spec.getDefaultResource().getValue(); + if (resource instanceof ResReferenceValue) { continue; - } else if (resource.contains("ResStringValue@") || resource.contains("ResStyleValue@") || - resource.contains("ResBoolValue@")) { - name = "@" + spec.getFullName(res.getResSpec().getPackage(), false); - } else { - ResAttr attr = (ResAttr) spec.getDefaultResource().getValue(); + } else if (resource instanceof ResAttr) { + ResAttr attr = (ResAttr) resource; value = attr.convertToResXmlFormat(mItems[i].m2); name = spec.getFullName(res.getResSpec().getPackage(), true); + } else { + name = "@" + spec.getFullName(res.getResSpec().getPackage(), false); } if (value == null) {
['brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResStyleValue.java']
{'.java': 1}
1
1
0
0
1
475,950
106,899
13,960
97
884
169
14
1
2,749
224
732
54
1
2
1970-01-01T00:25:03
16,931
Java
{'Java': 703364, 'Kotlin': 10370, 'Shell': 4847, 'Smali': 3679, 'Batchfile': 1154}
Apache License 2.0
121
ibotpeaches/apktool/1568/1534
ibotpeaches
apktool
https://github.com/iBotPeaches/Apktool/issues/1534
https://github.com/iBotPeaches/Apktool/pull/1568
https://github.com/iBotPeaches/Apktool/pull/1568
1
fixes
Error decompiling Hangouts v.20+
### Information 1. 2.2.4-acb004-SNAPSHOT (and 2.2.3) 2. Mac 3. Play Store ### Stacktrace/Logcat ``` I: Using Apktool 2.2.4-acb004-SNAPSHOT on Hangouts.apk I: Loading resource table... Exception in thread "main" brut.androlib.AndrolibException: Could not decode arsc file at brut.androlib.res.decoder.ARSCDecoder.decode(ARSCDecoder.java:52) at brut.androlib.res.AndrolibResources.getResPackagesFromApk(AndrolibResources.java:562) at brut.androlib.res.AndrolibResources.loadMainPkg(AndrolibResources.java:72) at brut.androlib.res.AndrolibResources.getResTable(AndrolibResources.java:64) at brut.androlib.Androlib.getResTable(Androlib.java:68) at brut.androlib.ApkDecoder.setTargetSdkVersion(ApkDecoder.java:207) at brut.androlib.ApkDecoder.decode(ApkDecoder.java:109) at brut.apktool.Main.cmdDecode(Main.java:166) at brut.apktool.Main.main(Main.java:81) Caused by: java.io.IOException: Expected: 0x00000008, got: 0x00000202 at brut.util.ExtDataInput.skipCheckShort(ExtDataInput.java:56) at brut.androlib.res.decoder.ARSCDecoder.readValue(ARSCDecoder.java:309) at brut.androlib.res.decoder.ARSCDecoder.readEntry(ARSCDecoder.java:241) at brut.androlib.res.decoder.ARSCDecoder.readTableType(ARSCDecoder.java:226) at brut.androlib.res.decoder.ARSCDecoder.readTableTypeSpec(ARSCDecoder.java:156) at brut.androlib.res.decoder.ARSCDecoder.readTablePackage(ARSCDecoder.java:118) at brut.androlib.res.decoder.ARSCDecoder.readTableHeader(ARSCDecoder.java:80) at brut.androlib.res.decoder.ARSCDecoder.decode(ARSCDecoder.java:47) ... 8 more ``` ### Steps to Reproduce 1. apktool d Hangouts.apk
e93ae011a8a8bdf05f0c9dc3d3ed03f1d1283d59
eda95b3da2b93700b3e3abe0991b584b83553f91
https://github.com/ibotpeaches/apktool/compare/e93ae011a8a8bdf05f0c9dc3d3ed03f1d1283d59...eda95b3da2b93700b3e3abe0991b584b83553f91
diff --git a/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/decoder/ARSCDecoder.java b/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/decoder/ARSCDecoder.java index 1888e954..95c5610b 100644 --- a/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/decoder/ARSCDecoder.java +++ b/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/decoder/ARSCDecoder.java @@ -156,7 +156,7 @@ public class ARSCDecoder { readTableType(); // skip "TYPE 8 chunks" and/or padding data at the end of this chunk - if(mCountIn.getCount() < mHeader.endPosition) { + if (mCountIn.getCount() < mHeader.endPosition) { mCountIn.skip(mHeader.endPosition - mCountIn.getCount()); } @@ -238,6 +238,12 @@ public class ARSCDecoder { short flags = mIn.readShort(); int specNamesId = mIn.readInt(); + // If we are here, we probably already inserted any remaining dummy resources. No need to parse + // any resources that doesn't have type information + if (mCountIn.getCount() == mHeader.endPosition) { + return; + } + ResValue value = (flags & ENTRY_FLAG_COMPLEX) == 0 ? readValue() : readComplexEntry(); if (mTypeSpec.isString() && value instanceof ResFileValue) { @@ -519,6 +525,8 @@ public class ARSCDecoder { private HashMap<Integer, ResTypeSpec> mResTypeSpecs = new HashMap<>(); private final static short ENTRY_FLAG_COMPLEX = 0x0001; + private final static short ENTRY_FLAG_PUBLIC = 0x0002; + private final static short ENTRY_FLAG_WEAK = 0x0004; public static class Header { public final short type;
['brut.apktool/apktool-lib/src/main/java/brut/androlib/res/decoder/ARSCDecoder.java']
{'.java': 1}
1
1
0
0
1
473,852
106,390
13,899
97
499
112
10
1
1,633
87
473
34
0
1
1970-01-01T00:25:01
16,931
Java
{'Java': 703364, 'Kotlin': 10370, 'Shell': 4847, 'Smali': 3679, 'Batchfile': 1154}
Apache License 2.0
122
ibotpeaches/apktool/1490/1160
ibotpeaches
apktool
https://github.com/iBotPeaches/Apktool/issues/1160
https://github.com/iBotPeaches/Apktool/pull/1490
https://github.com/iBotPeaches/Apktool/pull/1490
1
fix
ApkDecoder locks input file
Running ``` ApkDecoder decoder = new ApkDecoder(); try { decoder.setDecodeSources(ApkDecoder.DECODE_SOURCES_NONE); decoder.setDecodeResources(ApkDecoder.DECODE_RESOURCES_FULL); decoder.setApkFile(new File("i.apk")); decoder.setOutDir(new File("out")); decoder.setAnalysisMode(true, true); decoder.decode(); Thread.sleep(60000 * 100); } catch (Exception e) { e.printStackTrace(); } ``` causes Apktool to lock the input file under Windows until the JVM is exited.
4800bd7b449c63d237c78b980e21cd7906ddb5d1
66c1b468655d363087a3a58d7d65a1e267bd53b3
https://github.com/ibotpeaches/apktool/compare/4800bd7b449c63d237c78b980e21cd7906ddb5d1...66c1b468655d363087a3a58d7d65a1e267bd53b3
diff --git a/brut.apktool/apktool-cli/src/main/java/brut/apktool/Main.java b/brut.apktool/apktool-cli/src/main/java/brut/apktool/Main.java index 74470801..6e292713 100644 --- a/brut.apktool/apktool-cli/src/main/java/brut/apktool/Main.java +++ b/brut.apktool/apktool-cli/src/main/java/brut/apktool/Main.java @@ -187,6 +187,11 @@ public class Main { } catch (DirectoryException ex) { System.err.println("Could not modify internal dex files. Please ensure you have permission."); System.exit(1); + } finally { + try { + decoder.close(); + } catch (IOException e) { + } } } diff --git a/brut.apktool/apktool-lib/src/main/java/brut/androlib/Androlib.java b/brut.apktool/apktool-lib/src/main/java/brut/androlib/Androlib.java index 8a1aaf55..d51cb8d4 100644 --- a/brut.apktool/apktool-lib/src/main/java/brut/androlib/Androlib.java +++ b/brut.apktool/apktool-lib/src/main/java/brut/androlib/Androlib.java @@ -741,6 +741,10 @@ public class Androlib { return files; } + public void close() throws IOException { + mAndRes.close(); + } + private final static Logger LOGGER = Logger.getLogger(Androlib.class.getName()); private final static String SMALI_DIRNAME = "smali"; diff --git a/brut.apktool/apktool-lib/src/main/java/brut/androlib/ApkDecoder.java b/brut.apktool/apktool-lib/src/main/java/brut/androlib/ApkDecoder.java index aa2ca555..72a10488 100644 --- a/brut.apktool/apktool-lib/src/main/java/brut/androlib/ApkDecoder.java +++ b/brut.apktool/apktool-lib/src/main/java/brut/androlib/ApkDecoder.java @@ -60,6 +60,14 @@ public class ApkDecoder { } public void setApkFile(File apkFile) { + if (mApkFile != null) + { + try { + mApkFile.close(); + } catch (IOException e) { + } + } + mApkFile = new ExtFile(apkFile); mResTable = null; } @@ -73,93 +81,100 @@ public class ApkDecoder { } public void decode() throws AndrolibException, IOException, DirectoryException { - File outDir = getOutDir(); - AndrolibResources.sKeepBroken = mKeepBrokenResources; - - if (!mForceDelete && outDir.exists()) { - throw new OutDirExistsException(); - } - - if (!mApkFile.isFile() || !mApkFile.canRead()) { - throw new InFileNotFoundException(); - } - try { - OS.rmdir(outDir); - } catch (BrutException ex) { - throw new AndrolibException(ex); - } - outDir.mkdirs(); + File outDir = getOutDir(); + AndrolibResources.sKeepBroken = mKeepBrokenResources; - LOGGER.info("Using Apktool " + Androlib.getVersion() + " on " + mApkFile.getName()); + if (!mForceDelete && outDir.exists()) { + throw new OutDirExistsException(); + } - if (hasResources()) { - switch (mDecodeResources) { - case DECODE_RESOURCES_NONE: - mAndrolib.decodeResourcesRaw(mApkFile, outDir); - break; - case DECODE_RESOURCES_FULL: - setTargetSdkVersion(); - setAnalysisMode(mAnalysisMode, true); + if (!mApkFile.isFile() || !mApkFile.canRead()) { + throw new InFileNotFoundException(); + } - if (hasManifest()) { - mAndrolib.decodeManifestWithResources(mApkFile, outDir, getResTable()); - } - mAndrolib.decodeResourcesFull(mApkFile, outDir, getResTable()); - break; + try { + OS.rmdir(outDir); + } catch (BrutException ex) { + throw new AndrolibException(ex); } - } else { - // if there's no resources.asrc, decode the manifest without looking - // up attribute references - if (hasManifest()) { + outDir.mkdirs(); + + LOGGER.info("Using Apktool " + Androlib.getVersion() + " on " + mApkFile.getName()); + + if (hasResources()) { switch (mDecodeResources) { case DECODE_RESOURCES_NONE: - mAndrolib.decodeManifestRaw(mApkFile, outDir); + mAndrolib.decodeResourcesRaw(mApkFile, outDir); break; case DECODE_RESOURCES_FULL: - mAndrolib.decodeManifestFull(mApkFile, outDir, - getResTable()); + setTargetSdkVersion(); + setAnalysisMode(mAnalysisMode, true); + + if (hasManifest()) { + mAndrolib.decodeManifestWithResources(mApkFile, outDir, getResTable()); + } + mAndrolib.decodeResourcesFull(mApkFile, outDir, getResTable()); break; } + } else { + // if there's no resources.asrc, decode the manifest without looking + // up attribute references + if (hasManifest()) { + switch (mDecodeResources) { + case DECODE_RESOURCES_NONE: + mAndrolib.decodeManifestRaw(mApkFile, outDir); + break; + case DECODE_RESOURCES_FULL: + mAndrolib.decodeManifestFull(mApkFile, outDir, + getResTable()); + break; + } + } } - } - if (hasSources()) { - switch (mDecodeSources) { - case DECODE_SOURCES_NONE: - mAndrolib.decodeSourcesRaw(mApkFile, outDir, "classes.dex"); - break; - case DECODE_SOURCES_SMALI: - mAndrolib.decodeSourcesSmali(mApkFile, outDir, "classes.dex", mBakDeb, mApi); - break; + if (hasSources()) { + switch (mDecodeSources) { + case DECODE_SOURCES_NONE: + mAndrolib.decodeSourcesRaw(mApkFile, outDir, "classes.dex"); + break; + case DECODE_SOURCES_SMALI: + mAndrolib.decodeSourcesSmali(mApkFile, outDir, "classes.dex", mBakDeb, mApi); + break; + } } - } - if (hasMultipleSources()) { - // foreach unknown dex file in root, lets disassemble it - Set<String> files = mApkFile.getDirectory().getFiles(true); - for (String file : files) { - if (file.endsWith(".dex")) { - if (! file.equalsIgnoreCase("classes.dex")) { - switch(mDecodeSources) { - case DECODE_SOURCES_NONE: - mAndrolib.decodeSourcesRaw(mApkFile, outDir, file); - break; - case DECODE_SOURCES_SMALI: - mAndrolib.decodeSourcesSmali(mApkFile, outDir, file, mBakDeb, mApi); - break; + if (hasMultipleSources()) { + // foreach unknown dex file in root, lets disassemble it + Set<String> files = mApkFile.getDirectory().getFiles(true); + for (String file : files) { + if (file.endsWith(".dex")) { + if (! file.equalsIgnoreCase("classes.dex")) { + switch(mDecodeSources) { + case DECODE_SOURCES_NONE: + mAndrolib.decodeSourcesRaw(mApkFile, outDir, file); + break; + case DECODE_SOURCES_SMALI: + mAndrolib.decodeSourcesSmali(mApkFile, outDir, file, mBakDeb, mApi); + break; + } } } } } - } - mAndrolib.decodeRawFiles(mApkFile, outDir); - mAndrolib.decodeUnknownFiles(mApkFile, outDir, mResTable); - mUncompressedFiles = new ArrayList<String>(); - mAndrolib.recordUncompressedFiles(mApkFile, mUncompressedFiles); - mAndrolib.writeOriginalFiles(mApkFile, outDir); - writeMetaFile(); + mAndrolib.decodeRawFiles(mApkFile, outDir); + mAndrolib.decodeUnknownFiles(mApkFile, outDir, mResTable); + mUncompressedFiles = new ArrayList<String>(); + mAndrolib.recordUncompressedFiles(mApkFile, mUncompressedFiles); + mAndrolib.writeOriginalFiles(mApkFile, outDir); + writeMetaFile(); + } finally { + try { + mApkFile.close(); + } catch (IOException e) { + } + } } public void setDecodeSources(short mode) throws AndrolibException { @@ -273,6 +288,10 @@ public class ApkDecoder { } } + public void close() throws IOException { + mAndrolib.close(); + } + public final static short DECODE_SOURCES_NONE = 0x0000; public final static short DECODE_SOURCES_SMALI = 0x0001; diff --git a/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/AndrolibResources.java b/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/AndrolibResources.java index ae884321..3b308422 100644 --- a/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/AndrolibResources.java +++ b/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/AndrolibResources.java @@ -121,7 +121,8 @@ final public class AndrolibResources { File apk = getFrameworkApk(id, frameTag); LOGGER.info("Loading resource table from file: " + apk); - ResPackage[] pkgs = getResPackagesFromApk(new ExtFile(apk), resTable, true); + mFramework = new ExtFile(apk); + ResPackage[] pkgs = getResPackagesFromApk(mFramework, resTable, true); ResPackage pkg; if (pkgs.length > 1) { @@ -555,15 +556,23 @@ final public class AndrolibResources { private ResPackage[] getResPackagesFromApk(ExtFile apkFile,ResTable resTable, boolean keepBroken) throws AndrolibException { try { - BufferedInputStream bfi = new BufferedInputStream(apkFile.getDirectory().getFileInput("resources.arsc")); - return ARSCDecoder.decode(bfi, false, keepBroken, resTable).getPackages(); + Directory dir = apkFile.getDirectory(); + BufferedInputStream bfi = new BufferedInputStream(dir.getFileInput("resources.arsc")); + try { + return ARSCDecoder.decode(bfi, false, keepBroken, resTable).getPackages(); + } finally { + try { + bfi.close(); + } catch (IOException e) { + } + } } catch (DirectoryException ex) { throw new AndrolibException("Could not load resources.arsc from file: " + apkFile, ex); } } public File getFrameworkApk(int id, String frameTag) - throws AndrolibException { + throws AndrolibException { File dir = getFrameworkDir(); File apk; @@ -810,6 +819,10 @@ final public class AndrolibResources { } } + public void close() throws IOException { + mFramework.close(); + } + public ApkOptions apkOptions; // TODO: dirty static hack. I have to refactor decoding mechanisms. @@ -819,6 +832,8 @@ final public class AndrolibResources { private File mFrameworkDirectory = null; + private ExtFile mFramework = null; + private String mMinSdkVersion = null; private String mMaxSdkVersion = null; private String mTargetSdkVersion = null; diff --git a/brut.j.dir/src/main/java/brut/directory/AbstractDirectory.java b/brut.j.dir/src/main/java/brut/directory/AbstractDirectory.java index c2befcbe..ea906c7a 100644 --- a/brut.j.dir/src/main/java/brut/directory/AbstractDirectory.java +++ b/brut.j.dir/src/main/java/brut/directory/AbstractDirectory.java @@ -17,6 +17,7 @@ package brut.directory; import java.io.File; +import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.LinkedHashMap; @@ -235,6 +236,11 @@ public abstract class AbstractDirectory implements Directory { return dirs; } + + public void close() throws IOException { + + } + private SubPath getSubPath(String path) throws PathNotExist { ParsedPath parsed = parsePath(path); if (parsed.dir == null) { diff --git a/brut.j.dir/src/main/java/brut/directory/Directory.java b/brut.j.dir/src/main/java/brut/directory/Directory.java index 0199135d..e7a972be 100644 --- a/brut.j.dir/src/main/java/brut/directory/Directory.java +++ b/brut.j.dir/src/main/java/brut/directory/Directory.java @@ -50,5 +50,8 @@ public interface Directory { public int getCompressionLevel(String fileName) throws DirectoryException; + + public void close() throws IOException; + public final char separator = '/'; } diff --git a/brut.j.dir/src/main/java/brut/directory/ExtFile.java b/brut.j.dir/src/main/java/brut/directory/ExtFile.java index 583c3fa1..008e1b45 100644 --- a/brut.j.dir/src/main/java/brut/directory/ExtFile.java +++ b/brut.j.dir/src/main/java/brut/directory/ExtFile.java @@ -17,6 +17,7 @@ package brut.directory; import java.io.File; +import java.io.IOException; import java.net.URI; /** @@ -54,5 +55,9 @@ public class ExtFile extends File { return mDirectory; } + public void close() throws IOException { + mDirectory.close(); + } + private Directory mDirectory; } diff --git a/brut.j.dir/src/main/java/brut/directory/ZipRODirectory.java b/brut.j.dir/src/main/java/brut/directory/ZipRODirectory.java index bb76298a..a400ce34 100644 --- a/brut.j.dir/src/main/java/brut/directory/ZipRODirectory.java +++ b/brut.j.dir/src/main/java/brut/directory/ZipRODirectory.java @@ -151,4 +151,8 @@ public class ZipRODirectory extends AbstractDirectory { return mZipFile; } + + public void close() throws IOException { + mZipFile.close(); + } }
['brut.apktool/apktool-cli/src/main/java/brut/apktool/Main.java', 'brut.apktool/apktool-lib/src/main/java/brut/androlib/Androlib.java', 'brut.j.dir/src/main/java/brut/directory/ExtFile.java', 'brut.j.dir/src/main/java/brut/directory/Directory.java', 'brut.apktool/apktool-lib/src/main/java/brut/androlib/ApkDecoder.java', 'brut.j.dir/src/main/java/brut/directory/ZipRODirectory.java', 'brut.apktool/apktool-lib/src/main/java/brut/androlib/res/AndrolibResources.java', 'brut.j.dir/src/main/java/brut/directory/AbstractDirectory.java']
{'.java': 8}
8
8
0
0
8
453,717
101,079
13,544
94
8,498
1,677
203
8
592
43
127
19
0
1
1970-01-01T00:24:53
16,931
Java
{'Java': 703364, 'Kotlin': 10370, 'Shell': 4847, 'Smali': 3679, 'Batchfile': 1154}
Apache License 2.0
123
ibotpeaches/apktool/1147/1145
ibotpeaches
apktool
https://github.com/iBotPeaches/Apktool/issues/1145
https://github.com/iBotPeaches/Apktool/pull/1147
https://github.com/iBotPeaches/Apktool/pull/1147
1
fixes
I found a problem while unpacking a apk named by “xxx .apk” --- with the blank space at the end of the apk name.
hi, I found a problem while unpacking a apk named by “xxx .apk” --- with the blank space at the end of the apk name. (apktool V2.0.3 on Win7 ) ``` F:\\test>apktool.bat d -f "test .apk" I: Using Apktool 2.1.0-a64a03-SNAPSHOT on test .apk I: Loading resource table... I: Decoding AndroidManifest.xml with resources... Exception in thread "main" brut.androlib.AndrolibException: brut.directory.Direc toryException: java.io.FileNotFoundException: test \\AndroidManifest.xml (系统找 不到指定的路径。) at brut.androlib.res.decoder.ResFileDecoder.decodeManifest(ResFileDecode r.java:142) at brut.androlib.res.AndrolibResources.decodeManifestWithResources(Andro libResources.java:199) at brut.androlib.Androlib.decodeManifestWithResources(Androlib.java:142) at brut.androlib.ApkDecoder.decode(ApkDecoder.java:100) at brut.apktool.Main.cmdDecode(Main.java:165) at brut.apktool.Main.main(Main.java:81) Caused by: brut.directory.DirectoryException: java.io.FileNotFoundException: tes t \\AndroidManifest.xml (系统找不到指定的路径。) at brut.directory.FileDirectory.getFileOutputLocal(FileDirectory.java:64 ) at brut.directory.AbstractDirectory.getFileOutput(AbstractDirectory.java :115) at brut.androlib.res.decoder.ResFileDecoder.decodeManifest(ResFileDecode r.java:138) ... 5 more Caused by: java.io.FileNotFoundException: test \\AndroidManifest.xml (系统找不到 指定的路径。) at java.io.FileOutputStream.open0(Native Method) at java.io.FileOutputStream.open(Unknown Source) at java.io.FileOutputStream.<init>(Unknown Source) at java.io.FileOutputStream.<init>(Unknown Source) at brut.directory.FileDirectory.getFileOutputLocal(FileDirectory.java:62 ) ... 7 more ``` --- But, It is OK with the param "-o" F:\\test>apktool.bat d -f "test .apk" -o test so, Apktool do not handle the path correctly ?
114af9799d00d05d225ea2cda539d576c807eadf
ce66e17ee07629ddc9a46c473be4419339fd074a
https://github.com/ibotpeaches/apktool/compare/114af9799d00d05d225ea2cda539d576c807eadf...ce66e17ee07629ddc9a46c473be4419339fd074a
diff --git a/brut.apktool/apktool-cli/src/main/java/brut/apktool/Main.java b/brut.apktool/apktool-cli/src/main/java/brut/apktool/Main.java index 2256ca9e..eac49618 100644 --- a/brut.apktool/apktool-cli/src/main/java/brut/apktool/Main.java +++ b/brut.apktool/apktool-cli/src/main/java/brut/apktool/Main.java @@ -151,7 +151,7 @@ public class Main { // make out folder manually using name of apk String outName = apkName; outName = outName.endsWith(".apk") ? outName.substring(0, - outName.length() - 4) : outName + ".out"; + outName.length() - 4).trim() : outName + ".out"; // make file from path outName = new File(outName).getName();
['brut.apktool/apktool-cli/src/main/java/brut/apktool/Main.java']
{'.java': 1}
1
1
0
0
1
470,251
104,973
14,211
97
132
34
2
1
1,895
149
495
47
0
1
1970-01-01T00:24:13
16,931
Java
{'Java': 703364, 'Kotlin': 10370, 'Shell': 4847, 'Smali': 3679, 'Batchfile': 1154}
Apache License 2.0
8,683
appium/appium/1695/1549
appium
appium
https://github.com/appium/appium/issues/1549
https://github.com/appium/appium/pull/1695
https://github.com/appium/appium/pull/1695
1
fixes
Getting "unknown server-side error..." when real error is "Could not find an element…"
Android only: appium 11.2 python android native app If I'm on a page without a button and I try driver.find_element_by_xpath('//button') I see in the log: 2013-11-27T21:17:07.542Z - info: [BOOTSTRAP] [debug] Finding //button using XPATH with the contextId: 2013-11-27 15:17:07,552 [DEBUG] exec_logger.AppiumServer:info: [BOOTSTRAP] [info] Returning result: {"value":"Could not find an element using supplied strategy. ","status":13} [service.py:47] 2013-11-27 15:17:07,552 [DEBUG] exec_logger.AppiumServer:info: Responding to client with error: {"status":13,"value":{"message":"An unknown server-side error occurred while processing the command.","origValue":"Could not find an element using supplied strategy. "},"sessionId":"fe3c866f-81d6-4fff-a28f-5e9c40a17562"} [service.py:47] and the exception that is returned to my call is WebDriverException: Message: u'An unknown server-side error occurred while processing the command.' I did some digging in the bootstrap java and every time I convinced myself I knew where it was I would find something that changed my mind, but I did see that in handlers/Find.java it was doing stuff like catch (final ElementNotFoundException e) { return getErrorResult(e.getMessage()); } and getErrorResult is defined in Find's superclass CommandHandler as protected AndroidCommandResult getErrorResult(final String msg) { return new AndroidCommandResult(WDStatus.UNKNOWN_ERROR, msg); } I believe instead of the 13: UNKNOWN_ERROR, bootstrap should throw 7: NO_SUCH_ELEMENT
0dc74e9874cb66b5a836c7519ae3d828f8359b86
5d88a0eb4866a0cde8e6cbdfdeb01e6089045415
https://github.com/appium/appium/compare/0dc74e9874cb66b5a836c7519ae3d828f8359b86...5d88a0eb4866a0cde8e6cbdfdeb01e6089045415
diff --git a/lib/devices/android/bootstrap/src/io/appium/android/bootstrap/handler/Find.java b/lib/devices/android/bootstrap/src/io/appium/android/bootstrap/handler/Find.java index fe95c4585..6317a869d 100644 --- a/lib/devices/android/bootstrap/src/io/appium/android/bootstrap/handler/Find.java +++ b/lib/devices/android/bootstrap/src/io/appium/android/bootstrap/handler/Find.java @@ -33,10 +33,10 @@ import com.android.uiautomator.core.UiSelector; /** * This handler is used to find elements in the Android UI. - * + * * Based on which {@link Strategy}, {@link UiSelector}, and optionally the * contextId, the element Id or Ids are returned to the user. - * + * */ public class Find extends CommandHandler { AndroidElementsHash elements = AndroidElementsHash.getInstance(); @@ -60,11 +60,11 @@ public class Find extends CommandHandler { /* * @param command The {@link AndroidCommand} used for this handler. - * + * * @return {@link AndroidCommandResult} - * + * * @throws JSONException - * + * * @see io.appium.android.bootstrap.CommandHandler#execute(io.appium.android. * bootstrap.AndroidCommand) */ @@ -211,15 +211,15 @@ public class Find extends CommandHandler { return getSuccessResult(fetchElement(sel, contextId)); } } catch (final AndroidCommandException e) { - return getErrorResult(e.getMessage()); + return new AndroidCommandResult(WDStatus.UNKNOWN_ERROR, e.getMessage()); } catch (final ElementNotFoundException e) { - return getErrorResult(e.getMessage()); + return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT, e.getMessage()); } catch (final UnallowedTagNameException e) { - return getErrorResult(e.getMessage()); + return new AndroidCommandResult(WDStatus.UNKNOWN_ERROR, e.getMessage()); } catch (final ElementNotInHashException e) { - return getErrorResult(e.getMessage()); + return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT, e.getMessage()); } catch (final UiObjectNotFoundException e) { - return getErrorResult(e.getMessage()); + return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT, e.getMessage()); } } else { try { @@ -260,13 +260,13 @@ public class Find extends CommandHandler { } catch (final InvalidStrategyException e) { return getErrorResult(e.getMessage()); } catch (final UnallowedTagNameException e) { - return getErrorResult(e.getMessage()); + return new AndroidCommandResult(WDStatus.UNKNOWN_ERROR, e.getMessage()); } catch (final AndroidCommandException e) { - return getErrorResult(e.getMessage()); + return new AndroidCommandResult(WDStatus.UNKNOWN_ERROR, e.getMessage()); } catch (final UiObjectNotFoundException e) { - return getErrorResult(e.getMessage()); + return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT, e.getMessage()); } catch (final ElementNotFoundException e) { - return getErrorResult(e.getMessage()); + return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT, e.getMessage()); } } } @@ -274,12 +274,12 @@ public class Find extends CommandHandler { /** * Get the element from the {@link AndroidElementsHash} and return the element * id using JSON. - * + * * @param sel * A UiSelector that targets the element to fetch. * @param contextId * The Id of the element used for the context. - * + * * @return JSONObject * @throws JSONException * @throws ElementNotFoundException @@ -295,12 +295,12 @@ public class Find extends CommandHandler { /** * Get an array of elements from the {@link AndroidElementsHash} and return * the element's ids using JSON. - * + * * @param sel * A UiSelector that targets the element to fetch. * @param contextId * The Id of the element used for the context. - * + * * @return JSONObject * @throws JSONException * @throws UiObjectNotFoundException @@ -320,7 +320,7 @@ public class Find extends CommandHandler { /** * Create and return a UiSelector based on the strategy, text, and how many * you want returned. - * + * * @param strategy * The {@link Strategy} used to search for the element. * @param text @@ -400,7 +400,7 @@ public class Find extends CommandHandler { /** * Create and return a UiSelector based on Xpath attributes. - * + * * @param path * The Xpath path. * @param attr @@ -409,7 +409,7 @@ public class Find extends CommandHandler { * Any constraint. * @param substr * Any substr. - * + * * @return UiSelector * @throws AndroidCommandException */
['lib/devices/android/bootstrap/src/io/appium/android/bootstrap/handler/Find.java']
{'.java': 1}
1
1
0
0
1
133,828
29,053
4,260
54
1,327
273
42
1
1,522
182
394
28
0
0
1970-01-01T00:23:08
16,649
JavaScript
{'JavaScript': 1508008, 'TypeScript': 514934, 'Java': 28622, 'C#': 18579, 'HTML': 15974, 'Shell': 13107, 'RobotFramework': 7582, 'Handlebars': 2875, 'Python': 783, 'Ruby': 680, 'CSS': 122}
Apache License 2.0
8,680
appium/appium/4365/4200
appium
appium
https://github.com/appium/appium/issues/4200
https://github.com/appium/appium/pull/4365
https://github.com/appium/appium/pull/4365
2
fixes
Restart UIAutomator to find missing elements
Read the end of [this issue](https://github.com/appium/java-client/issues/74#issuecomment-61511540). According to @ranbena restarting UIAutomator works %100 of the time to fix an issue where sometimes elements aren't returned by getPAgeSource(). It's definitely a bug in Android UIAutomator, but it seems like we can work around it by restarting the UIAutomator process. Right now, restarting the process causes the Appium session to fail. What should we consider for fixing these missing elements? Options I've thought of so far: 1) Make a "restart UIAutomator" function available to clients. 2) Restart UIAutomator whenever an element isn't found (or add it to some retry logic) 3) Create a "Setting" (from our settings api) which when enabled restarts UIAutomator when elements aren't found, and doesn't restart UIAutomator when disabled. Any more ideas? @jlipps @bootstraponline @sebv @imurchie @0x1mason @JessicaSachs
23e1f6b5084ed1b8e474a7b6d21960696a93ca78
7971429ce9cc395f42da69527fa48aa4a6ef34e9
https://github.com/appium/appium/compare/23e1f6b5084ed1b8e474a7b6d21960696a93ca78...7971429ce9cc395f42da69527fa48aa4a6ef34e9
diff --git a/lib/devices/android/bootstrap/src/com/android/uiautomator/common/ReflectionUtils.java b/lib/devices/android/bootstrap/src/com/android/uiautomator/common/ReflectionUtils.java index 29ab12461..e5c5b6cd6 100644 --- a/lib/devices/android/bootstrap/src/com/android/uiautomator/common/ReflectionUtils.java +++ b/lib/devices/android/bootstrap/src/com/android/uiautomator/common/ReflectionUtils.java @@ -7,6 +7,7 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; import static io.appium.android.bootstrap.utils.API.API_18; +import java.lang.reflect.InvocationTargetException; public class ReflectionUtils { private static Field enableField(final Class<?> clazz, final String field) @@ -47,6 +48,32 @@ public class ReflectionUtils { public Object getBridge() { return bridge; } + + /** + * Clears the in-process Accessibility cache, removing any stale references. + * Because the AccessibilityInteractionClient singleton stores copies of AccessibilityNodeInfo + * instances, calls to public APIs such as `recycle` do not guarantee cached references get + * updated. See the android.view.accessibility AIC and ANI source code for more information. + */ + public static boolean clearAccessibilityCache() { + boolean success = false; + + try { + ReflectionUtils utils = new ReflectionUtils(); + Class c = Class.forName("android.view.accessibility.AccessibilityInteractionClient"); + Method getInstance = utils.getMethod(c, "getInstance"); + Object instance = getInstance.invoke(null); + Method clearCache = utils.getMethod(instance.getClass(), "clearCache"); + clearCache.invoke(instance); + success = true; + } catch (Exception ex) { + // Expected: ClassNotFoundException, NoSuchMethodException, IllegalAccessException, + // InvocationTargetException, NoSuchFieldException + Logger.error("Failed to clear Accessibility Node cache. " + ex.getMessage()); + } + + return success; + } public Method getControllerMethod(final String name, final Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException { diff --git a/lib/devices/android/bootstrap/src/io/appium/android/bootstrap/handler/Find.java b/lib/devices/android/bootstrap/src/io/appium/android/bootstrap/handler/Find.java index d9b2f5bf6..d781eaae2 100644 --- a/lib/devices/android/bootstrap/src/io/appium/android/bootstrap/handler/Find.java +++ b/lib/devices/android/bootstrap/src/io/appium/android/bootstrap/handler/Find.java @@ -1,7 +1,17 @@ package io.appium.android.bootstrap.handler; +import com.android.uiautomator.common.ReflectionUtils; import com.android.uiautomator.core.UiObjectNotFoundException; import com.android.uiautomator.core.UiSelector; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import javax.xml.parsers.ParserConfigurationException; +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.List; +import java.util.regex.Pattern; + import io.appium.android.bootstrap.*; import io.appium.android.bootstrap.exceptions.ElementNotFoundException; import io.appium.android.bootstrap.exceptions.InvalidSelectorException; @@ -12,15 +22,6 @@ import io.appium.android.bootstrap.utils.ClassInstancePair; import io.appium.android.bootstrap.utils.ElementHelpers; import io.appium.android.bootstrap.utils.UiAutomatorParser; import io.appium.android.bootstrap.utils.XMLHierarchy; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import javax.xml.parsers.ParserConfigurationException; -import java.util.ArrayList; -import java.util.Hashtable; -import java.util.List; -import java.util.regex.Pattern; import static io.appium.android.bootstrap.utils.API.API_18; @@ -62,6 +63,24 @@ public class Find extends CommandHandler { @Override public AndroidCommandResult execute(final AndroidCommand command) throws JSONException { + return execute(command, false); + } + + /** + * execute implementation. + * + * @see io.appium.android.bootstrap.handler.Find#execute(io.appium.android. + * bootstrap.AndroidCommand) + * + * @param command The {@link AndroidCommand} used for this handler. + * + * @param isRetry Is this invocation a second attempt? + * + * @return {@link AndroidCommandResult} + * @throws JSONException + */ + private AndroidCommandResult execute(final AndroidCommand command, boolean isRetry) + throws JSONException { final Hashtable<String, Object> params = command.params(); // only makes sense on a device @@ -82,7 +101,6 @@ public class Find extends CommandHandler { try { Object result = null; List<UiSelector> selectors = getSelectors(strategy, text, multiple); - if (!multiple) { for (final UiSelector sel : selectors) { try { @@ -97,8 +115,7 @@ public class Find extends CommandHandler { } else { List<AndroidElement> foundElements = new ArrayList<AndroidElement>(); for (final UiSelector sel : selectors) { - // With multiple selectors, we expect that some elements may not - // exist. + // With multiple selectors, we expect that some elements may not exist. try { Logger.debug("Using: " + sel.toString()); List<AndroidElement> elementsFromSelector = fetchElements(sel, contextId); @@ -112,10 +129,20 @@ public class Find extends CommandHandler { result = elementsToJSONArray(foundElements); } - // If there are no results, then return an error. if (result == null) { - return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT, - "No element found"); + if (!isRetry) { + Logger.debug("Failed to locate element. Clearing Accessibility cache and retrying."); + // some control updates fail to trigger AccessibilityEvents, resulting in stale AccessibilityNodeInfo + // instances. In these cases, UIAutomator will fail to locate visible elements. As a work-around, + // force clear the AccessibilityInteractionClient's cache and search again. This technique also + // appears to make Appium's searches conclude more quickly. See Appium issue #4200 + // https://github.com/appium/appium/issues/4200 + if (ReflectionUtils.clearAccessibilityCache()) { + return execute(command, true); + } + } + // If there are no results and we've already retried, return an error. + return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT, "No element found"); } return getSuccessResult(result); @@ -132,6 +159,7 @@ public class Find extends CommandHandler { } } + /** * Get the element from the {@link AndroidElementsHash} and return the element * id using JSON. diff --git a/lib/devices/android/bootstrap/src/io/appium/android/bootstrap/handler/Source.java b/lib/devices/android/bootstrap/src/io/appium/android/bootstrap/handler/Source.java index 1097ab336..82c32eab9 100644 --- a/lib/devices/android/bootstrap/src/io/appium/android/bootstrap/handler/Source.java +++ b/lib/devices/android/bootstrap/src/io/appium/android/bootstrap/handler/Source.java @@ -1,5 +1,6 @@ package io.appium.android.bootstrap.handler; +import com.android.uiautomator.common.ReflectionUtils; import io.appium.android.bootstrap.AndroidCommand; import io.appium.android.bootstrap.AndroidCommandResult; import io.appium.android.bootstrap.CommandHandler; @@ -21,6 +22,7 @@ import java.io.StringWriter; public class Source extends CommandHandler { @Override public AndroidCommandResult execute(AndroidCommand command) throws JSONException { + ReflectionUtils.clearAccessibilityCache(); Document doc = (Document) XMLHierarchy.getFormattedXMLDoc();
['lib/devices/android/bootstrap/src/io/appium/android/bootstrap/handler/Source.java', 'lib/devices/android/bootstrap/src/io/appium/android/bootstrap/handler/Find.java', 'lib/devices/android/bootstrap/src/com/android/uiautomator/common/ReflectionUtils.java']
{'.java': 3}
3
3
0
0
3
168,278
36,185
5,328
71
3,715
708
87
3
928
130
221
14
1
0
1970-01-01T00:23:40
16,649
JavaScript
{'JavaScript': 1508008, 'TypeScript': 514934, 'Java': 28622, 'C#': 18579, 'HTML': 15974, 'Shell': 13107, 'RobotFramework': 7582, 'Handlebars': 2875, 'Python': 783, 'Ruby': 680, 'CSS': 122}
Apache License 2.0
8,685
appium/appium/1145/1140
appium
appium
https://github.com/appium/appium/issues/1140
https://github.com/appium/appium/pull/1145
https://github.com/appium/appium/pull/1145
1
fix
catch NullPointerExceptions instead of crashing
As reported on the mailing list: ``` info: [ADB STDOUT] java.lang.NullPointerException info: [ADB STDOUT] at io.appium.android.bootstrap.handler.Click.execute(Click.java:42) ``` The server methods should never crash on a NullPointerException. The fix is to add NullPointerException to the existing try/catch blocks on every command.
868a3202bfe7c99966c9760dde4c0b12780cd95b
935e12bf6fae07eccdf3ed4970eca771376950c0
https://github.com/appium/appium/compare/868a3202bfe7c99966c9760dde4c0b12780cd95b...935e12bf6fae07eccdf3ed4970eca771376950c0
diff --git a/android/bootstrap/src/io/appium/android/bootstrap/handler/Clear.java b/android/bootstrap/src/io/appium/android/bootstrap/handler/Clear.java index 095b19255..a8871bdf1 100644 --- a/android/bootstrap/src/io/appium/android/bootstrap/handler/Clear.java +++ b/android/bootstrap/src/io/appium/android/bootstrap/handler/Clear.java @@ -43,8 +43,10 @@ public class Clear extends CommandHandler { } catch (final ElementNotInHashException e) { return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT, e.getMessage()); + } catch (final Exception e) { // handle NullPointerException + return getErrorResult("Unknown error clearing text"); } } - return getErrorResult("Unknown error clearing text"); + return getErrorResult("Unknown error"); } } diff --git a/android/bootstrap/src/io/appium/android/bootstrap/handler/Click.java b/android/bootstrap/src/io/appium/android/bootstrap/handler/Click.java index 599184020..9700a348c 100644 --- a/android/bootstrap/src/io/appium/android/bootstrap/handler/Click.java +++ b/android/bootstrap/src/io/appium/android/bootstrap/handler/Click.java @@ -47,6 +47,8 @@ public class Click extends CommandHandler { } catch (final ElementNotInHashException e) { return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT, e.getMessage()); + } catch (final Exception e) { // handle NullPointerException + return getErrorResult("Unknown error"); } } else { final Hashtable<String, Object> params = command.params(); diff --git a/android/bootstrap/src/io/appium/android/bootstrap/handler/Drag.java b/android/bootstrap/src/io/appium/android/bootstrap/handler/Drag.java index 596bc3c97..a6717556f 100644 --- a/android/bootstrap/src/io/appium/android/bootstrap/handler/Drag.java +++ b/android/bootstrap/src/io/appium/android/bootstrap/handler/Drag.java @@ -50,9 +50,10 @@ public class Drag extends CommandHandler { if (params.get("elementId") != JSONObject.NULL) { el = command.getElement(); } - } catch (final ElementNotInHashException e) { + } catch (final Exception e) { el = null; } + try { if (params.get("destElId") != JSONObject.NULL) { destEl = command.getDestElement(); diff --git a/android/bootstrap/src/io/appium/android/bootstrap/handler/Flick.java b/android/bootstrap/src/io/appium/android/bootstrap/handler/Flick.java index 3d360d446..63bcf8778 100644 --- a/android/bootstrap/src/io/appium/android/bootstrap/handler/Flick.java +++ b/android/bootstrap/src/io/appium/android/bootstrap/handler/Flick.java @@ -5,7 +5,6 @@ import io.appium.android.bootstrap.AndroidCommandResult; import io.appium.android.bootstrap.AndroidElement; import io.appium.android.bootstrap.CommandHandler; import io.appium.android.bootstrap.Logger; -import io.appium.android.bootstrap.exceptions.ElementNotInHashException; import io.appium.android.bootstrap.exceptions.InvalidCoordinatesException; import io.appium.android.bootstrap.utils.Point; @@ -14,7 +13,6 @@ import java.util.Hashtable; import org.json.JSONException; import com.android.uiautomator.core.UiDevice; -import com.android.uiautomator.core.UiObjectNotFoundException; /** * This handler is used to flick elements in the Android UI. @@ -83,11 +81,7 @@ public class Flick extends CommandHandler { end.x = start.x + xoffset; end.y = start.y + yoffset; - } catch (final ElementNotInHashException e) { - return getErrorResult(e.getMessage()); - } catch (final UiObjectNotFoundException e) { - return getErrorResult(e.getMessage()); - } catch (final InvalidCoordinatesException e) { + } catch (final Exception e) { return getErrorResult(e.getMessage()); } } else { diff --git a/android/bootstrap/src/io/appium/android/bootstrap/handler/GetAttribute.java b/android/bootstrap/src/io/appium/android/bootstrap/handler/GetAttribute.java index 20f19a8fe..092346fd3 100644 --- a/android/bootstrap/src/io/appium/android/bootstrap/handler/GetAttribute.java +++ b/android/bootstrap/src/io/appium/android/bootstrap/handler/GetAttribute.java @@ -54,7 +54,7 @@ public class GetAttribute extends CommandHandler { } catch (final ElementNotInHashException e) { return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT, e.getMessage()); - } catch (final NullPointerException e) { // el is null + } catch (final Exception e) { // el is null return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT, e.getMessage()); } diff --git a/android/bootstrap/src/io/appium/android/bootstrap/handler/GetName.java b/android/bootstrap/src/io/appium/android/bootstrap/handler/GetName.java index c50db3ba6..623e5f121 100644 --- a/android/bootstrap/src/io/appium/android/bootstrap/handler/GetName.java +++ b/android/bootstrap/src/io/appium/android/bootstrap/handler/GetName.java @@ -41,6 +41,8 @@ public class GetName extends CommandHandler { return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT, e.getMessage()); } catch (final ElementNotInHashException e) { return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT, e.getMessage()); + } catch (final Exception e) { // handle NullPointerException + return getErrorResult("Unknown error"); } } } diff --git a/android/bootstrap/src/io/appium/android/bootstrap/handler/GetSize.java b/android/bootstrap/src/io/appium/android/bootstrap/handler/GetSize.java index 7436fb413..3c2e65fe5 100644 --- a/android/bootstrap/src/io/appium/android/bootstrap/handler/GetSize.java +++ b/android/bootstrap/src/io/appium/android/bootstrap/handler/GetSize.java @@ -48,6 +48,8 @@ public class GetSize extends CommandHandler { } catch (final ElementNotInHashException e) { return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT, e.getMessage()); + } catch (final Exception e) { // handle NullPointerException + return getErrorResult("Unknown error"); } return getSuccessResult(res); } else { diff --git a/android/bootstrap/src/io/appium/android/bootstrap/handler/GetText.java b/android/bootstrap/src/io/appium/android/bootstrap/handler/GetText.java index e6b048461..61af00218 100644 --- a/android/bootstrap/src/io/appium/android/bootstrap/handler/GetText.java +++ b/android/bootstrap/src/io/appium/android/bootstrap/handler/GetText.java @@ -41,6 +41,8 @@ public class GetText extends CommandHandler { } catch (final ElementNotInHashException e) { return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT, e.getMessage()); + } catch (final Exception e) { // handle NullPointerException + return getErrorResult("Unknown error"); } } else { return getErrorResult("Unable to get text without an element."); diff --git a/android/bootstrap/src/io/appium/android/bootstrap/handler/SetAttribute.java b/android/bootstrap/src/io/appium/android/bootstrap/handler/SetAttribute.java index de5bef203..8a91c9c18 100644 --- a/android/bootstrap/src/io/appium/android/bootstrap/handler/SetAttribute.java +++ b/android/bootstrap/src/io/appium/android/bootstrap/handler/SetAttribute.java @@ -46,7 +46,10 @@ public class SetAttribute extends CommandHandler { } catch (final ElementNotInHashException e) { return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT, e.getMessage()); + } catch (final Exception e) { // handle NullPointerException + return getErrorResult("Unknown error"); } + } else { final Hashtable<String, Object> params = command.params(); diff --git a/android/bootstrap/src/io/appium/android/bootstrap/handler/SetText.java b/android/bootstrap/src/io/appium/android/bootstrap/handler/SetText.java index d4939d2ac..30b48a4f2 100644 --- a/android/bootstrap/src/io/appium/android/bootstrap/handler/SetText.java +++ b/android/bootstrap/src/io/appium/android/bootstrap/handler/SetText.java @@ -58,6 +58,8 @@ public class SetText extends CommandHandler { } catch (final ElementNotInHashException e) { return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT, e.getMessage()); + } catch (final Exception e) { // handle NullPointerException + return getErrorResult("Unknown error"); } } else { return getErrorResult("Unable to set text without an element."); diff --git a/android/bootstrap/src/io/appium/android/bootstrap/handler/Swipe.java b/android/bootstrap/src/io/appium/android/bootstrap/handler/Swipe.java index ae09f3749..5d2fe87e9 100644 --- a/android/bootstrap/src/io/appium/android/bootstrap/handler/Swipe.java +++ b/android/bootstrap/src/io/appium/android/bootstrap/handler/Swipe.java @@ -55,6 +55,8 @@ public class Swipe extends CommandHandler { return getErrorResult(e.getMessage()); } catch (final InvalidCoordinatesException e) { return getErrorResult(e.getMessage()); + } catch (final Exception e) { // handle NullPointerException + return getErrorResult("Unknown error"); } } else { try {
['android/bootstrap/src/io/appium/android/bootstrap/handler/SetAttribute.java', 'android/bootstrap/src/io/appium/android/bootstrap/handler/Drag.java', 'android/bootstrap/src/io/appium/android/bootstrap/handler/GetName.java', 'android/bootstrap/src/io/appium/android/bootstrap/handler/GetSize.java', 'android/bootstrap/src/io/appium/android/bootstrap/handler/Click.java', 'android/bootstrap/src/io/appium/android/bootstrap/handler/Clear.java', 'android/bootstrap/src/io/appium/android/bootstrap/handler/GetAttribute.java', 'android/bootstrap/src/io/appium/android/bootstrap/handler/Flick.java', 'android/bootstrap/src/io/appium/android/bootstrap/handler/Swipe.java', 'android/bootstrap/src/io/appium/android/bootstrap/handler/GetText.java', 'android/bootstrap/src/io/appium/android/bootstrap/handler/SetText.java']
{'.java': 11}
11
11
0
0
11
121,861
26,622
3,916
52
1,678
333
32
11
335
40
70
9
0
1
1970-01-01T00:22:58
16,649
JavaScript
{'JavaScript': 1508008, 'TypeScript': 514934, 'Java': 28622, 'C#': 18579, 'HTML': 15974, 'Shell': 13107, 'RobotFramework': 7582, 'Handlebars': 2875, 'Python': 783, 'Ruby': 680, 'CSS': 122}
Apache License 2.0
8,687
appium/appium/1104/1100
appium
appium
https://github.com/appium/appium/issues/1100
https://github.com/appium/appium/pull/1104
https://github.com/appium/appium/pull/1104
2
fix
Android button click returns false on success
When clicking a button on Android, uiautomator always returns false even though it was a successful click. Other buttons return the expected `true` value when clicked.
88f8bb47d82cacde31a2344808d31a0ce51a52f5
6844140adfe04167bee66dd27b196e8b2fc8e909
https://github.com/appium/appium/compare/88f8bb47d82cacde31a2344808d31a0ce51a52f5...6844140adfe04167bee66dd27b196e8b2fc8e909
diff --git a/android/bootstrap/src/io/appium/android/bootstrap/handler/Click.java b/android/bootstrap/src/io/appium/android/bootstrap/handler/Click.java index ee0e21e6d..599184020 100644 --- a/android/bootstrap/src/io/appium/android/bootstrap/handler/Click.java +++ b/android/bootstrap/src/io/appium/android/bootstrap/handler/Click.java @@ -39,8 +39,8 @@ public class Click extends CommandHandler { if (command.isElementCommand()) { try { final AndroidElement el = command.getElement(); - final boolean res = el.click(); - return getSuccessResult(res); + el.click(); + return getSuccessResult(true); } catch (final UiObjectNotFoundException e) { return new AndroidCommandResult(WDStatus.NO_SUCH_ELEMENT, e.getMessage());
['android/bootstrap/src/io/appium/android/bootstrap/handler/Click.java']
{'.java': 1}
1
1
0
0
1
121,880
26,626
3,916
52
140
26
4
1
168
26
34
2
0
0
1970-01-01T00:22:58
16,649
JavaScript
{'JavaScript': 1508008, 'TypeScript': 514934, 'Java': 28622, 'C#': 18579, 'HTML': 15974, 'Shell': 13107, 'RobotFramework': 7582, 'Handlebars': 2875, 'Python': 783, 'Ruby': 680, 'CSS': 122}
Apache License 2.0
8,688
appium/appium/703/675
appium
appium
https://github.com/appium/appium/issues/675
https://github.com/appium/appium/pull/703
https://github.com/appium/appium/pull/703
2
fixes
Source is broken
``` warn: remote object '/data/local/tmp/dump.xml' does not exist ``` I'm seeing this when testing on a local emulator. > info: [ADB STDOUT] Error in testRunServer: > info: [ADB STDOUT] java.lang.IllegalStateException: UiAutomationService not connected. Did you call #register()? The response to dump is strange. > adb -s emulator-5554 shell uiautomator dump /data/local/tmp/dump.xml > Killed
3c1b180073b92b4219799eb1ad5bac508a639ff1
4a2b957ae5edca0382c10b41523d1c8e72a22060
https://github.com/appium/appium/compare/3c1b180073b92b4219799eb1ad5bac508a639ff1...4a2b957ae5edca0382c10b41523d1c8e72a22060
diff --git a/android/bootstrap/src/io/appium/android/bootstrap/SocketServer.java b/android/bootstrap/src/io/appium/android/bootstrap/SocketServer.java index d77c243d4..f5b659265 100644 --- a/android/bootstrap/src/io/appium/android/bootstrap/SocketServer.java +++ b/android/bootstrap/src/io/appium/android/bootstrap/SocketServer.java @@ -117,7 +117,7 @@ class SocketServer { final TimerTask updateWatchers = new TimerTask() { @Override public void run() { - watchers.check(); + try { watchers.check(); } catch (Exception e) {} } }; timer.scheduleAtFixedRate(updateWatchers, 100, 100);
['android/bootstrap/src/io/appium/android/bootstrap/SocketServer.java']
{'.java': 1}
1
1
0
0
1
98,603
21,528
3,166
42
84
17
2
1
398
53
102
14
0
1
1970-01-01T00:22:50
16,649
JavaScript
{'JavaScript': 1508008, 'TypeScript': 514934, 'Java': 28622, 'C#': 18579, 'HTML': 15974, 'Shell': 13107, 'RobotFramework': 7582, 'Handlebars': 2875, 'Python': 783, 'Ruby': 680, 'CSS': 122}
Apache License 2.0
8,689
appium/appium/679/678
appium
appium
https://github.com/appium/appium/issues/678
https://github.com/appium/appium/pull/679
https://github.com/appium/appium/pull/679
1
fixes
finding android.webkit.WebView object fails
I am trying to find the android.webkit.WebView element in my hybrid android app. I am using XPATH "//web" to find_element. Appium server is searching for "android.widget.WebView" instead of "android.webkit.WebView" and fails. AndroidElementClassMap seems to look only in android.widget namespace. Used android 4.2 OS to test this. Thanks in advance. -Vishwanath
df073431e761173b7c62c79adde0a4ee76003585
745c170bdd68c54a7b87af947e9769fa74c0f75d
https://github.com/appium/appium/compare/df073431e761173b7c62c79adde0a4ee76003585...745c170bdd68c54a7b87af947e9769fa74c0f75d
diff --git a/android/bootstrap/src/io/appium/android/bootstrap/AndroidElementClassMap.java b/android/bootstrap/src/io/appium/android/bootstrap/AndroidElementClassMap.java index 2a56eafad..6d306a0d6 100644 --- a/android/bootstrap/src/io/appium/android/bootstrap/AndroidElementClassMap.java +++ b/android/bootstrap/src/io/appium/android/bootstrap/AndroidElementClassMap.java @@ -134,7 +134,7 @@ public class AndroidElementClassMap { map.put("viewpager", "ViewPager"); map.put("viewstub", "ViewStub"); map.put("viewswitcher", "ViewSwitcher"); - map.put("web", "WebView"); + map.put("web", "android.webkit.WebView"); map.put("window", "FrameLayout"); map.put("zoom", "ZoomButton"); map.put("zoomcontrols", "ZoomControls");
['android/bootstrap/src/io/appium/android/bootstrap/AndroidElementClassMap.java']
{'.java': 1}
1
1
0
0
1
96,184
21,019
3,091
41
78
21
2
1
367
50
85
11
0
0
1970-01-01T00:22:49
16,649
JavaScript
{'JavaScript': 1508008, 'TypeScript': 514934, 'Java': 28622, 'C#': 18579, 'HTML': 15974, 'Shell': 13107, 'RobotFramework': 7582, 'Handlebars': 2875, 'Python': 783, 'Ruby': 680, 'CSS': 122}
Apache License 2.0
1,327
material-components/material-components-android/2718/2615
material-components
material-components-android
https://github.com/material-components/material-components-android/issues/2615
https://github.com/material-components/material-components-android/pull/2718
https://github.com/material-components/material-components-android/pull/2718
1
resolves
[TextInputLayout] DropdownMenuEndIconDelegate is leaking ContextThemeWrapper instance
**Description:** DropdownMenuEndIconDelegate is leaking ContextThemeWrapper instance **Expected behavior:** Should not leak. **Source code:** Your own code of DropdownMenuEndIconDelegate **Minimal sample app repro:** Use LeakCanary to check this in your samples when switching between light/dark mode. **Android API version:** 25 **Material Library version:** 1.6.0-beta01 **Device:** PAX Aries 8
768d0cfa2ba99dfb207453e4882ab73abf824db0
08997f33e004111f4db4c5be7b83adb8418ae8b8
https://github.com/material-components/material-components-android/compare/768d0cfa2ba99dfb207453e4882ab73abf824db0...08997f33e004111f4db4c5be7b83adb8418ae8b8
diff --git a/lib/java/com/google/android/material/textfield/DropdownMenuEndIconDelegate.java b/lib/java/com/google/android/material/textfield/DropdownMenuEndIconDelegate.java index 011f5553c..45c625725 100644 --- a/lib/java/com/google/android/material/textfield/DropdownMenuEndIconDelegate.java +++ b/lib/java/com/google/android/material/textfield/DropdownMenuEndIconDelegate.java @@ -40,12 +40,12 @@ import android.text.Editable; import android.text.TextWatcher; import android.view.MotionEvent; import android.view.View; +import android.view.View.OnAttachStateChangeListener; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.View.OnTouchListener; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; -import android.view.accessibility.AccessibilityManager.TouchExplorationStateChangeListener; import android.widget.AutoCompleteTextView; import android.widget.AutoCompleteTextView.OnDismissListener; import android.widget.EditText; @@ -54,6 +54,8 @@ import androidx.annotation.DrawableRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.view.ViewCompat; +import androidx.core.view.accessibility.AccessibilityManagerCompat; +import androidx.core.view.accessibility.AccessibilityManagerCompat.TouchExplorationStateChangeListener; import androidx.core.view.accessibility.AccessibilityNodeInfoCompat; import com.google.android.material.animation.AnimationUtils; import com.google.android.material.color.MaterialColors; @@ -190,6 +192,38 @@ class DropdownMenuEndIconDelegate extends EndIconDelegate { editText.setOnDismissListener(null); } } + if (previousIcon == TextInputLayout.END_ICON_DROPDOWN_MENU) { + textInputLayout.removeOnAttachStateChangeListener(onAttachStateChangeListener); + removeTouchExplorationStateChangeListenerIfNeeded(); + } + } + }; + + private final OnAttachStateChangeListener onAttachStateChangeListener = new OnAttachStateChangeListener() { + @Override + public void onViewAttachedToWindow(View ignored) { + addTouchExplorationStateChangeListenerIfNeeded(); + } + + @Override + public void onViewDetachedFromWindow(View ignored) { + removeTouchExplorationStateChangeListenerIfNeeded(); + } + }; + + private final TouchExplorationStateChangeListener touchExplorationStateChangeListener = + new TouchExplorationStateChangeListener() { + @Override + public void onTouchExplorationStateChanged(boolean enabled) { + if (textInputLayout != null) { + final AutoCompleteTextView autoCompleteTextView = + (AutoCompleteTextView) textInputLayout.getEditText(); + if (autoCompleteTextView != null && !isEditable(autoCompleteTextView)) { + ViewCompat.setImportantForAccessibility( + endIconView, + enabled ? IMPORTANT_FOR_ACCESSIBILITY_NO : IMPORTANT_FOR_ACCESSIBILITY_YES); + } + } } }; @@ -265,20 +299,8 @@ class DropdownMenuEndIconDelegate extends EndIconDelegate { initAnimators(); accessibilityManager = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE); - if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { - accessibilityManager.addTouchExplorationStateChangeListener( - new TouchExplorationStateChangeListener() { - @Override - public void onTouchExplorationStateChanged(boolean enabled) { - if (textInputLayout.getEditText() != null - && !isEditable(textInputLayout.getEditText())) { - ViewCompat.setImportantForAccessibility( - endIconView, - enabled ? IMPORTANT_FOR_ACCESSIBILITY_NO : IMPORTANT_FOR_ACCESSIBILITY_YES); - } - } - }); - } + textInputLayout.addOnAttachStateChangeListener(onAttachStateChangeListener); + addTouchExplorationStateChangeListenerIfNeeded(); } @Override @@ -530,4 +552,20 @@ class DropdownMenuEndIconDelegate extends EndIconDelegate { return animator; } + + private void addTouchExplorationStateChangeListenerIfNeeded() { + if (accessibilityManager != null + && textInputLayout != null + && ViewCompat.isAttachedToWindow(textInputLayout)) { + AccessibilityManagerCompat.addTouchExplorationStateChangeListener( + accessibilityManager, touchExplorationStateChangeListener); + } + } + + private void removeTouchExplorationStateChangeListenerIfNeeded() { + if (accessibilityManager != null) { + AccessibilityManagerCompat.removeTouchExplorationStateChangeListener( + accessibilityManager, touchExplorationStateChangeListener); + } + } }
['lib/java/com/google/android/material/textfield/DropdownMenuEndIconDelegate.java']
{'.java': 1}
1
1
0
0
1
4,086,204
871,575
116,197
559
3,105
531
68
1
418
47
93
15
0
0
1970-01-01T00:27:33
15,271
Java
{'Java': 6714445}
Apache License 2.0
988
williamfiset/algorithms/98/59
williamfiset
algorithms
https://github.com/williamfiset/Algorithms/issues/59
https://github.com/williamfiset/Algorithms/pull/98
https://github.com/williamfiset/Algorithms/pull/98
1
solved
Cut polygon additional points
The [cut polygon](https://github.com/williamfiset/Algorithms/blob/master/Geometry/ConvexPolygonCutWithLineSegment.java) snippet seems to provide additional points when a cut operation is performed which probably shouldn't be there. For example, when the following runs the additional point (2,2) appears out of nowhere. ```java Pt[] squarePolygon = {new Pt(0, 0), new Pt(0, 4), new Pt(4, 0), new Pt(4, 4)}; Pt p1 = new Pt(-1, -1); Pt p2 = new Pt(5, 5); Pt[] poly1 = cut(squarePolygon, p1, p2); Pt[] poly2 = cut(squarePolygon, p2, p1); System.out.println("First polygon:"); for (Pt pt : poly1) System.out.println(pt); // Prints: // First polygon: // (4.0,4.0) // (0.0,0.0) // (0.0,4.0) // (2.0,2.0) <-- Probably should not be here? System.out.println("\\nSecond polygon:"); for (Pt pt : poly2) System.out.println(pt); // Second polygon: // (4.0,4.0) // (0.0,0.0) // (2.0,2.0) <-- Probably should not be here? // (4.0,0.0) ``` @FinnLidbetter assigning you since made this snippet right? Perhaps you can offer some insight.
dcf94d6cef0100a83acab2349a4ca9194d7056ba
2e4f2521663be0fd068ebdae4c313b35a5cc178e
https://github.com/williamfiset/algorithms/compare/dcf94d6cef0100a83acab2349a4ca9194d7056ba...2e4f2521663be0fd068ebdae4c313b35a5cc178e
diff --git a/com/williamfiset/algorithms/geometry/ConvexPolygonCutWithLineSegment.java b/com/williamfiset/algorithms/geometry/ConvexPolygonCutWithLineSegment.java index cc75a61..df72ad7 100644 --- a/com/williamfiset/algorithms/geometry/ConvexPolygonCutWithLineSegment.java +++ b/com/williamfiset/algorithms/geometry/ConvexPolygonCutWithLineSegment.java @@ -1,13 +1,14 @@ /** - * This algorithm cuts a convex polygon with a line segment and returns the two resulting pieces. + * This algorithm cuts a ordered convex polygon with a line segment and returns the two resulting pieces. * - * <p>Time Complexity: O(n) + * <p>Time Complexity: O(nlogn) * * @author Finn Lidbetter */ package com.williamfiset.algorithms.geometry; import java.util.*; +import java.lang.*; public class ConvexPolygonCutWithLineSegment { @@ -27,6 +28,29 @@ public class ConvexPolygonCutWithLineSegment { return "(" + x + "," + y + ")"; } } + + + //sorts the points in CW direction. + public static List<Pt> sortCW(List<Pt> poly){ + + int l = poly.size(); + double centroidX = 0; + double centroidY = 0; + for(int i = 0; i<l; i++){ + centroidX+= poly.get(i).x; + centroidY+= poly.get(i).y; + } + centroidX = centroidX/l; + centroidY = centroidY/l; + Pt center = new Pt(centroidX, centroidY); + + Collections.sort(poly, (a, b) -> { + double a1 = (Math.toDegrees(Math.atan2(a.x - center.x, a.y - center.y)) + 360) % 360; + double a2 = (Math.toDegrees(Math.atan2(b.x - center.x, b.y - center.y)) + 360) % 360; + return (int) (a1 - a2); + }); + return poly; + } // Cuts a convex polygon by a specified line and returns one part // of the polygon (swapping the endpoints p1 and p2 of the line @@ -61,14 +85,38 @@ public class ConvexPolygonCutWithLineSegment { double cross = bx * cy - by * cx; return cross < -EPS ? -1 : cross > EPS ? 1 : 0; } + + //takes Pt[] as an argument and returns List<Pt> + public static List<Pt> makeList(Pt[] squarePolygon){ + List<Pt> list = new ArrayList<Pt>(); + for (int i=0; i<squarePolygon.length; i++){ + list.add(squarePolygon[i]); + } + return list; + } + + //takes List<Pt> as an argument and returns Pt[] + public static Pt[] makeArray(List<Pt> list){ + int l = list.size(); + Pt[] temp = new Pt[l]; + for (int i=0; i<l; i++){ + temp[i] = list.get(i); + } + return temp; + } // Example usage public static void main(String[] args) { - - Pt[] squarePolygon = {new Pt(0, 0), new Pt(0, 4), new Pt(4, 0), new Pt(4, 4)}; + + Pt[] squarePolygon = {new Pt(0, 0), new Pt(0, 4), new Pt(4, 0), new Pt(4, 4), new Pt(0, 2)}; Pt p1 = new Pt(-1, -1); Pt p2 = new Pt(5, 5); - + + int l = squarePolygon.length; + List list = makeList(squarePolygon); + list = sortCW(list); + squarePolygon = makeArray(list); + Pt[] poly1 = cut(squarePolygon, p1, p2); Pt[] poly2 = cut(squarePolygon, p2, p1); @@ -76,18 +124,18 @@ public class ConvexPolygonCutWithLineSegment { for (Pt pt : poly1) System.out.println(pt); // Prints: // First polygon: + // (0.0,4.0) // (4.0,4.0) // (0.0,0.0) - // (0.0,4.0) - // (2.0,2.0) <-- Probably should not be here? + // (0.0,2.0) System.out.println("\\nSecond polygon:"); for (Pt pt : poly2) System.out.println(pt); + //Prints: // Second polygon: // (4.0,4.0) - // (0.0,0.0) - // (2.0,2.0) <-- Probably should not be here? // (4.0,0.0) + // (0.0,0.0) } }
['com/williamfiset/algorithms/geometry/ConvexPolygonCutWithLineSegment.java']
{'.java': 1}
1
1
0
0
1
763,745
213,584
26,065
197
2,093
644
66
1
1,140
141
357
31
1
1
1970-01-01T00:26:11
15,090
Java
{'Java': 1436763, 'JavaScript': 9310, 'Kotlin': 2635, 'Python': 755}
MIT License
190
prestodb/presto/6279/6278
prestodb
presto
https://github.com/prestodb/presto/issues/6278
https://github.com/prestodb/presto/pull/6279
https://github.com/prestodb/presto/pull/6279
1
fixes
Planning Class cast exception
This query now throws an error: ``` SELECT (MAX(x.a) OVER () - x.a) * 100.0 / MAX(x.a) OVER () FROM ( SELECT 1 as a ) x ``` ``` Query 20161005_231326_03851_gb7jd failed: com.facebook.presto.sql.tree.SymbolReference cannot be cast to com.facebook.presto.sql.tree.FunctionCall java.lang.ClassCastException: com.facebook.presto.sql.tree.SymbolReference cannot be cast to com.facebook.presto.sql.tree.FunctionCall at com.facebook.presto.sql.planner.QueryPlanner.window(QueryPlanner.java:617) at com.facebook.presto.sql.planner.QueryPlanner.plan(QueryPlanner.java:140) at com.facebook.presto.sql.planner.RelationPlanner.visitQuerySpecification(RelationPlanner.java:443) at com.facebook.presto.sql.planner.RelationPlanner.visitQuerySpecification(RelationPlanner.java:94) at com.facebook.presto.sql.tree.QuerySpecification.accept(QuerySpecification.java:125) at com.facebook.presto.sql.tree.AstVisitor.process(AstVisitor.java:22) at com.facebook.presto.sql.planner.QueryPlanner.planQueryBody(QueryPlanner.java:220) at com.facebook.presto.sql.planner.QueryPlanner.plan(QueryPlanner.java:113) at com.facebook.presto.sql.planner.RelationPlanner.visitQuery(RelationPlanner.java:436) at com.facebook.presto.sql.planner.RelationPlanner.visitQuery(RelationPlanner.java:94) at com.facebook.presto.sql.tree.Query.accept(Query.java:103) at com.facebook.presto.sql.tree.AstVisitor.process(AstVisitor.java:22) at com.facebook.presto.sql.planner.LogicalPlanner.createRelationPlan(LogicalPlanner.java:358) at com.facebook.presto.sql.planner.LogicalPlanner.planStatement(LogicalPlanner.java:150) at com.facebook.presto.sql.planner.LogicalPlanner.plan(LogicalPlanner.java:112) at com.facebook.presto.sql.planner.LogicalPlanner.plan(LogicalPlanner.java:107) at com.facebook.presto.execution.SqlQueryExecution.doAnalyzeQuery(SqlQueryExecution.java:291) at com.facebook.presto.execution.SqlQueryExecution.analyzeQuery(SqlQueryExecution.java:270) at com.facebook.presto.execution.SqlQueryExecution.start(SqlQueryExecution.java:228) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) ```
8428d4d1b0c9a2639f75ac5799b2e97526ef1890
5b4e6ec8e03cf6d07db74bce0c4466c41e04c30c
https://github.com/prestodb/presto/compare/8428d4d1b0c9a2639f75ac5799b2e97526ef1890...5b4e6ec8e03cf6d07db74bce0c4466c41e04c30c
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/QueryPlanner.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/QueryPlanner.java index 9c25114f99..71f2b7c62b 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/QueryPlanner.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/QueryPlanner.java @@ -600,18 +600,22 @@ class QueryPlanner outputTranslations.addIntermediateMapping(windowFunction, parametersReplaced); Expression rewritten = subPlan.rewrite(parametersReplaced); + boolean needCoercion = rewritten instanceof Cast; + // Strip out the cast and add it back as a post-projection + if (rewritten instanceof Cast) { + rewritten = ((Cast) rewritten).getExpression(); + } + // If refers to existing symbol, don't create another PlanNode if (rewritten instanceof SymbolReference) { + if (needCoercion) { + subPlan = explicitCoercionSymbols(subPlan, subPlan.getRoot().getOutputSymbols(), ImmutableList.of(windowFunction)); + } + continue; } Symbol newSymbol = symbolAllocator.newSymbol(rewritten, analysis.getType(windowFunction)); - - boolean needCoercion = rewritten instanceof Cast; - // Strip out the cast and add it back as a post-projection - if (rewritten instanceof Cast) { - rewritten = ((Cast) rewritten).getExpression(); - } outputTranslations.put(parametersReplaced, newSymbol); WindowNode.Function function = new WindowNode.Function( diff --git a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java index 30393eb08b..45a1af2979 100644 --- a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java +++ b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java @@ -3797,6 +3797,19 @@ public abstract class AbstractTestQueries .build(); assertEquals(actual, expected); + + actual = computeActual("" + + "SELECT (MAX(x.a) OVER () - x.a) * 100.0 / MAX(x.a) OVER ()\\n" + + "FROM (VALUES 1, 2, 3, 4) x(a)"); + + expected = resultBuilder(getSession(), DOUBLE) + .row(75.0) + .row(50.0) + .row(25.0) + .row(0.0) + .build(); + + assertEquals(actual, expected); } @Test
['presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/QueryPlanner.java']
{'.java': 2}
2
2
0
0
2
13,219,306
2,628,738
367,659
2,669
720
134
16
1
2,310
90
586
37
0
2
1970-01-01T00:24:35
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
183
prestodb/presto/6977/6954
prestodb
presto
https://github.com/prestodb/presto/issues/6954
https://github.com/prestodb/presto/pull/6977
https://github.com/prestodb/presto/pull/6977
1
fixes
Query optimizer generates incorrect plans for some logical expressions
Reproduce with: ``` select (a=8 or b=2) and (a=8 or c=3) or (b=9) from (values (1, 2, 3)) as t (a, b, c); ``` `(a=8 or b=2) and (a=8 or c=3)` should become `a=8 or (b=2 and c=3)`. The query optimizer turns it into `a=8 and (b=2 and c=3)`
3730c09b8c9124356b43c4b5547b3f6af8f3d61f
f02780d30faded0c52343f39077bd962d9efbf96
https://github.com/prestodb/presto/compare/3730c09b8c9124356b43c4b5547b3f6af8f3d61f...f02780d30faded0c52343f39077bd962d9efbf96
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/SimplifyExpressions.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/SimplifyExpressions.java index 76c9e65ad1..6d318c880e 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/SimplifyExpressions.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/SimplifyExpressions.java @@ -59,6 +59,7 @@ import static com.facebook.presto.util.ImmutableCollectors.toImmutableList; import static java.util.Collections.emptyList; import static java.util.Collections.emptySet; import static java.util.Objects.requireNonNull; +import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; public class SimplifyExpressions @@ -212,11 +213,29 @@ public class SimplifyExpressions @Override public Expression rewriteLogicalBinaryExpression(LogicalBinaryExpression node, NodeContext context, ExpressionTreeRewriter<NodeContext> treeRewriter) { - List<Expression> predicates = extractPredicates(node.getType(), node).stream() - .map(expression -> treeRewriter.rewrite(expression, NodeContext.NOT_ROOT_NODE)) - .collect(toImmutableList()); + Expression expression = combinePredicates( + node.getType(), + extractPredicates(node.getType(), node).stream() + .map(subExpression -> treeRewriter.rewrite(subExpression, NodeContext.NOT_ROOT_NODE)) + .collect(toImmutableList())); + + if (!(expression instanceof LogicalBinaryExpression)) { + return expression; + } + + Expression simplified = extractCommonPredicates((LogicalBinaryExpression) expression); + + // Prefer AND LogicalBinaryExpression at the root if possible + if (context.isRootNode() && simplified instanceof LogicalBinaryExpression && ((LogicalBinaryExpression) simplified).getType() == OR) { + return distributeIfPossible((LogicalBinaryExpression) simplified); + } + + return simplified; + } - List<List<Expression>> subPredicates = getSubPredicates(predicates); + private static Expression extractCommonPredicates(LogicalBinaryExpression node) + { + List<List<Expression>> subPredicates = getSubPredicates(node); Set<Expression> commonPredicates = ImmutableSet.copyOf(subPredicates.stream() .map(ExtractCommonPredicatesExpressionRewriter::filterDeterministicPredicates) @@ -234,26 +253,63 @@ public class SimplifyExpressions .collect(toImmutableList()); Expression combinedUncorrelatedPredicates = combinePredicates(node.getType(), uncorrelatedPredicates); - // Do not simplify top level conjuncts if it would result in top level disjuncts - // Conjuncts are easier to process when pushing down predicates. - if (context.isRootNode() && flippedNodeType == OR && !combinedUncorrelatedPredicates.equals(FALSE_LITERAL)) { - return combinePredicates(node.getType(), predicates); - } - return combinePredicates(flippedNodeType, ImmutableList.<Expression>builder() .addAll(commonPredicates) .add(combinedUncorrelatedPredicates) .build()); } - private static List<List<Expression>> getSubPredicates(List<Expression> predicates) + private static List<List<Expression>> getSubPredicates(LogicalBinaryExpression expression) { - return predicates.stream() + return extractPredicates(expression.getType(), expression).stream() .map(predicate -> predicate instanceof LogicalBinaryExpression ? extractPredicates((LogicalBinaryExpression) predicate) : ImmutableList.of(predicate)) .collect(toImmutableList()); } + /** + * Applies the boolean distributive property. + * + * For example: + * ( A & B ) | ( C & D ) => ( A | C ) & ( A | D ) & ( B | C ) & ( B | D ) + * + * Returns the original expression if the expression is non-deterministic or if the distribution will + * expand the expression by too much. + */ + private static Expression distributeIfPossible(LogicalBinaryExpression expression) + { + if (!DeterminismEvaluator.isDeterministic(expression)) { + // Do not distribute boolean expressions if there are any non-deterministic elements + // TODO: This can be optimized further if non-deterministic elements are not repeated + return expression; + } + List<Set<Expression>> subPredicates = getSubPredicates(expression).stream() + .map(ImmutableSet::copyOf) + .collect(toList()); + + int originalBaseExpressions = subPredicates.stream() + .mapToInt(Set::size) + .sum(); + int newBaseExpressions = subPredicates.stream() + .mapToInt(Set::size) + .reduce(Math::multiplyExact) + .getAsInt() * subPredicates.size(); + if (newBaseExpressions > originalBaseExpressions * 2) { + // Do not distribute boolean expressions if it would create 2x more base expressions + // (e.g. A, B, C, D from the above example). This is just an arbitrary heuristic to + // avoid cross product expression explosion. + return expression; + } + + Set<List<Expression>> crossProduct = Sets.cartesianProduct(subPredicates); + + return combinePredicates( + expression.getType().flip(), + crossProduct.stream() + .map(expressions -> combinePredicates(expression.getType(), expressions)) + .collect(toImmutableList())); + } + private static Set<Expression> filterDeterministicPredicates(List<Expression> predicates) { return predicates.stream() diff --git a/presto-main/src/test/java/com/facebook/presto/sql/planner/optimizations/TestSimplifyExpressions.java b/presto-main/src/test/java/com/facebook/presto/sql/planner/optimizations/TestSimplifyExpressions.java index 07a68a85b7..c647f36e10 100644 --- a/presto-main/src/test/java/com/facebook/presto/sql/planner/optimizations/TestSimplifyExpressions.java +++ b/presto-main/src/test/java/com/facebook/presto/sql/planner/optimizations/TestSimplifyExpressions.java @@ -65,8 +65,10 @@ public class TestSimplifyExpressions } @Test - public void testExtractsCommonPredicate() + public void testExtractCommonPredicates() { + assertSimplifies("X AND Y", "X AND Y"); + assertSimplifies("X OR Y", "X OR Y"); assertSimplifies("X AND X", "X"); assertSimplifies("X OR X", "X"); assertSimplifies("(X OR Y) AND (X OR Y)", "X OR Y"); @@ -83,9 +85,18 @@ public class TestSimplifyExpressions assertSimplifies("((X OR V) AND V) OR ((X OR V) AND V)", "V"); assertSimplifies("((X OR V) AND X) OR ((X OR V) AND V)", "X OR V"); - assertSimplifies("((X OR V) AND Z) OR ((X OR V) AND V)", "(((X OR V) AND Z) OR V)"); + assertSimplifies("((X OR V) AND Z) OR ((X OR V) AND V)", "(X OR V) AND (Z OR V)"); assertSimplifies("X AND ((Y AND Z) OR (Y AND V) OR (Y AND X))", "X AND Y AND (Z OR V OR X)"); assertSimplifies("(A AND B AND C AND D) OR (A AND B AND E) OR (A AND F)", "A AND ((B AND C AND D) OR (B AND E) OR F)"); + + assertSimplifies("((A AND B) OR (A AND C)) AND D", "A AND (B OR C) AND D"); + assertSimplifies("((A OR B) AND (A OR C)) OR D", "(A OR B OR D) AND (A OR C OR D)"); + assertSimplifies("(((A AND B) OR (A AND C)) AND D) OR E", "(A OR E) AND (B OR C OR E) AND (D OR E)"); + assertSimplifies("(((A OR B) AND (A OR C)) OR D) AND E", "(A OR (B AND C) OR D) AND E"); + + assertSimplifies("(A AND B) OR (C AND D)", "(A OR C) AND (A OR D) AND (B OR C) AND (B OR D)"); + // No distribution since it would add too many new terms + assertSimplifies("(A AND B) OR (C AND D) OR (E AND F)", "(A AND B) OR (C AND D) OR (E AND F)"); } private static void assertSimplifies(String expression, String expected)
['presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/SimplifyExpressions.java', 'presto-main/src/test/java/com/facebook/presto/sql/planner/optimizations/TestSimplifyExpressions.java']
{'.java': 2}
2
2
0
0
2
13,615,089
2,703,759
377,698
2,705
4,289
746
80
1
245
49
112
7
0
1
1970-01-01T00:24:42
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
189
prestodb/presto/6350/6330
prestodb
presto
https://github.com/prestodb/presto/issues/6330
https://github.com/prestodb/presto/pull/6350
https://github.com/prestodb/presto/pull/6350
1
fixes
Planning bug when creating bucketed table
This query: ``` sql CREATE TABLE t WITH ( bucketed_by=array['k'], bucket_count=64) AS (SELECT '' a, '' b, 0 k) ``` fails with: ``` java.lang.IllegalArgumentException: Input symbols do not match output symbols at com.google.common.base.Preconditions.checkArgument(Preconditions.java:122) at com.facebook.presto.sql.planner.plan.ExchangeNode.<init>(ExchangeNode.java:82) at com.facebook.presto.sql.planner.plan.ExchangeNode.partitionedExchange(ExchangeNode.java:130) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.visitTableWriter(AddExchanges.java:636) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.visitTableWriter(AddExchanges.java:187) at com.facebook.presto.sql.planner.plan.TableWriterNode.accept(TableWriterNode.java:128) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.planChild(AddExchanges.java:1231) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.visitTableFinish(AddExchanges.java:791) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.visitTableFinish(AddExchanges.java:187) at com.facebook.presto.sql.planner.plan.TableFinishNode.accept(TableFinishNode.java:80) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.planChild(AddExchanges.java:1231) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.visitOutput(AddExchanges.java:236) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.visitOutput(AddExchanges.java:187) at com.facebook.presto.sql.planner.plan.OutputNode.accept(OutputNode.java:81) at com.facebook.presto.sql.planner.optimizations.AddExchanges.optimize(AddExchanges.java:149) at com.facebook.presto.sql.planner.LogicalPlanner.plan(LogicalPlanner.java:105) at com.facebook.presto.execution.SqlQueryExecution.doAnalyzeQuery(SqlQueryExecution.java:281) at com.facebook.presto.execution.SqlQueryExecution.analyzeQuery(SqlQueryExecution.java:260) at com.facebook.presto.execution.SqlQueryExecution.start(SqlQueryExecution.java:224) at com.facebook.presto.execution.QueuedExecution.lambda$start$1(QueuedExecution.java:62) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) ```
5b9ff8c6970fd8a5f79285262992356f56a1749e
d6ce487e2ea9b540cd16381351ed81a9fb8b4da7
https://github.com/prestodb/presto/compare/5b9ff8c6970fd8a5f79285262992356f56a1749e...d6ce487e2ea9b540cd16381351ed81a9fb8b4da7
diff --git a/presto-hive/src/test/java/com/facebook/presto/hive/TestHiveIntegrationSmokeTest.java b/presto-hive/src/test/java/com/facebook/presto/hive/TestHiveIntegrationSmokeTest.java index 11e80aeab0..ad08eb1289 100644 --- a/presto-hive/src/test/java/com/facebook/presto/hive/TestHiveIntegrationSmokeTest.java +++ b/presto-hive/src/test/java/com/facebook/presto/hive/TestHiveIntegrationSmokeTest.java @@ -550,6 +550,7 @@ public class TestHiveIntegrationSmokeTest public void testCreatePartitionedBucketedTableAsFewRows() throws Exception { + // go through all storage formats to make sure the empty buckets are correctly created for (TestingHiveStorageFormat storageFormat : getAllTestingHiveStorageFormat()) { testCreatePartitionedBucketedTableAsFewRows(storageFormat.getSession(), storageFormat.getFormat()); } @@ -614,11 +615,11 @@ public class TestHiveIntegrationSmokeTest "WITH (" + "format = '" + storageFormat + "', " + "partitioned_by = ARRAY[ 'orderstatus' ], " + - "bucketed_by = ARRAY[ 'custkey' ], " + + "bucketed_by = ARRAY[ 'custkey', 'custkey2' ], " + "bucket_count = 11 " + ") " + "AS " + - "SELECT custkey, comment, orderstatus " + + "SELECT custkey, custkey AS custkey2, comment, orderstatus " + "FROM tpch.tiny.orders"; assertUpdate( @@ -650,15 +651,15 @@ public class TestHiveIntegrationSmokeTest "WITH (" + "format = '" + storageFormat + "', " + "partitioned_by = ARRAY[ 'orderstatus' ], " + - "bucketed_by = ARRAY[ 'custkey' ], " + + "bucketed_by = ARRAY[ 'custkey', 'custkey2' ], " + "bucket_count = 11 " + ") " + "AS " + - "SELECT custkey, comment, orderstatus " + + "SELECT custkey, custkey AS custkey2, comment, orderstatus " + "FROM tpch.tiny.orders " + "WHERE length(comment) % 2 = 0 " + "UNION ALL " + - "SELECT custkey, comment, orderstatus " + + "SELECT custkey, custkey AS custkey2, comment, orderstatus " + "FROM tpch.tiny.orders " + "WHERE length(comment) % 2 = 1"; @@ -687,22 +688,22 @@ public class TestHiveIntegrationSmokeTest assertEquals(columnMetadata.getComment(), annotateColumnComment(Optional.empty(), partitionKey)); } - assertEquals(tableMetadata.getMetadata().getProperties().get(BUCKETED_BY_PROPERTY), ImmutableList.of("custkey")); + assertEquals(tableMetadata.getMetadata().getProperties().get(BUCKETED_BY_PROPERTY), ImmutableList.of("custkey", "custkey2")); assertEquals(tableMetadata.getMetadata().getProperties().get(BUCKET_COUNT_PROPERTY), 11); List<?> partitions = getPartitions(tableName); assertEquals(partitions.size(), 3); - assertQuery("SELECT * from " + tableName, "SELECT custkey, comment, orderstatus FROM orders"); + assertQuery("SELECT * from " + tableName, "SELECT custkey, custkey, comment, orderstatus FROM orders"); for (int i = 1; i <= 30; i++) { assertQuery( - format("SELECT * from " + tableName + " where custkey = %d", i), - format("SELECT custkey, comment, orderstatus FROM orders where custkey = %d", i)); + format("SELECT * from " + tableName + " where custkey = %d and custkey2 = %d", i, i), + format("SELECT custkey, custkey, comment, orderstatus FROM orders where custkey = %d", i)); } try { - assertUpdate("INSERT INTO " + tableName + " VALUES (1, 'comment', 'O')", 1); + assertUpdate("INSERT INTO " + tableName + " VALUES (1, 1, 'comment', 'O')", 1); fail("expected failure"); } catch (Exception e) { @@ -714,6 +715,7 @@ public class TestHiveIntegrationSmokeTest public void testInsertPartitionedBucketedTableFewRows() throws Exception { + // go through all storage formats to make sure the empty buckets are correctly created for (TestingHiveStorageFormat storageFormat : getAllTestingHiveStorageFormat()) { testInsertPartitionedBucketedTableFewRows(storageFormat.getSession(), storageFormat.getFormat()); } @@ -801,12 +803,13 @@ public class TestHiveIntegrationSmokeTest assertUpdate("" + "CREATE TABLE " + tableName + " (" + " custkey bigint," + + " custkey2 bigint," + " comment varchar," + " orderstatus varchar)" + "WITH (" + "format = '" + storageFormat + "', " + "partitioned_by = ARRAY[ 'orderstatus' ], " + - "bucketed_by = ARRAY[ 'custkey' ], " + + "bucketed_by = ARRAY[ 'custkey', 'custkey2' ], " + "bucket_count = 11)"); ImmutableList<String> orderStatusList = ImmutableList.of("F", "O", "P"); @@ -817,7 +820,7 @@ public class TestHiveIntegrationSmokeTest getSession().withSystemProperty("task_writer_count", "4"), format( "INSERT INTO " + tableName + " " + - "SELECT custkey, comment, orderstatus " + + "SELECT custkey, custkey AS custkey2, comment, orderstatus " + "FROM tpch.tiny.orders " + "WHERE orderstatus = '%s'", orderStatus), @@ -845,12 +848,13 @@ public class TestHiveIntegrationSmokeTest assertUpdate("" + "CREATE TABLE " + tableName + " (" + " custkey bigint," + + " custkey2 bigint," + " comment varchar," + " orderstatus varchar)" + "WITH (" + "format = '" + storageFormat + "', " + "partitioned_by = ARRAY[ 'orderstatus' ], " + - "bucketed_by = ARRAY[ 'custkey' ], " + + "bucketed_by = ARRAY[ 'custkey', 'custkey2' ], " + "bucket_count = 11)"); ImmutableList<String> orderStatusList = ImmutableList.of("F", "O", "P"); @@ -861,11 +865,11 @@ public class TestHiveIntegrationSmokeTest getSession().withSystemProperty("task_writer_count", "4"), format( "INSERT INTO " + tableName + " " + - "SELECT custkey, comment, orderstatus " + + "SELECT custkey, custkey AS custkey2, comment, orderstatus " + "FROM tpch.tiny.orders " + "WHERE orderstatus = '%s' and length(comment) %% 2 = 0 " + "UNION ALL " + - "SELECT custkey, comment, orderstatus " + + "SELECT custkey, custkey AS custkey2, comment, orderstatus " + "FROM tpch.tiny.orders " + "WHERE orderstatus = '%s' and length(comment) %% 2 = 1", orderStatus, orderStatus), diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/UnaliasSymbolReferences.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/UnaliasSymbolReferences.java index 8142dbaf18..5111377733 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/UnaliasSymbolReferences.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/UnaliasSymbolReferences.java @@ -544,7 +544,7 @@ public class UnaliasSymbolReferences node.getColumnNames(), node.getOutputSymbols(), canonicalize(node.getSampleWeightSymbol()), - node.getPartitioningScheme().map(this::canonicalizePartitionFunctionBinding)); + node.getPartitioningScheme().map(partitioningScheme -> canonicalizePartitionFunctionBinding(partitioningScheme, source))); } @Override @@ -658,11 +658,20 @@ public class UnaliasSymbolReferences return builder.build(); } - private PartitioningScheme canonicalizePartitionFunctionBinding(PartitioningScheme scheme) + private PartitioningScheme canonicalizePartitionFunctionBinding(PartitioningScheme scheme, PlanNode source) { + Set<Symbol> addedOutputs = new HashSet<>(); + ImmutableList.Builder<Symbol> outputs = ImmutableList.builder(); + for (Symbol symbol : source.getOutputSymbols()) { + Symbol canonicalOutput = canonicalize(symbol); + if (addedOutputs.add(canonicalOutput)) { + outputs.add(canonicalOutput); + } + } + return new PartitioningScheme( scheme.getPartitioning().translate(this::canonicalize), - canonicalize(scheme.getOutputLayout()), + outputs.build(), canonicalize(scheme.getHashColumn()), scheme.isReplicateNulls(), scheme.getBucketToPartition());
['presto-hive/src/test/java/com/facebook/presto/hive/TestHiveIntegrationSmokeTest.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/UnaliasSymbolReferences.java']
{'.java': 2}
2
2
0
0
2
13,256,621
2,635,918
368,656
2,675
966
158
15
1
2,435
78
598
39
0
2
1970-01-01T00:24:36
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
188
prestodb/presto/6411/6407
prestodb
presto
https://github.com/prestodb/presto/issues/6407
https://github.com/prestodb/presto/pull/6411
https://github.com/prestodb/presto/pull/6411
1
fix
Incorrect result when using MAP in IN expression
In the latest master: ``` presto:tiny> select x from (values 2) t(x) where map(array[1], array[x]) in (values map(array[1],array[2])); x --- (0 rows) ```
0306af4a6f9e5238f8904ee97a16ffcc669a8dc9
2fd1fa2c6957d59b0f260e3d5a7802d271cd875e
https://github.com/prestodb/presto/compare/0306af4a6f9e5238f8904ee97a16ffcc669a8dc9...2fd1fa2c6957d59b0f260e3d5a7802d271cd875e
diff --git a/presto-main/src/main/java/com/facebook/presto/operator/scalar/ArrayHashCodeOperator.java b/presto-main/src/main/java/com/facebook/presto/operator/scalar/ArrayHashCodeOperator.java index d10332cc90..a9f074a062 100644 --- a/presto-main/src/main/java/com/facebook/presto/operator/scalar/ArrayHashCodeOperator.java +++ b/presto-main/src/main/java/com/facebook/presto/operator/scalar/ArrayHashCodeOperator.java @@ -45,11 +45,11 @@ public final class ArrayHashCodeOperator @TypeParameter("T") Type type, @SqlType("array(T)") Block block) { - int hash = 0; + long hash = 0; for (int i = 0; i < block.getPositionCount(); i++) { checkElementNotNull(block.isNull(i), ARRAY_NULL_ELEMENT_MSG); try { - hash = (int) CombineHashFunction.getHash(hash, (long) hashFunction.invoke(readNativeValue(type, block, i))); + hash = CombineHashFunction.getHash(hash, (long) hashFunction.invoke(readNativeValue(type, block, i))); } catch (Throwable t) { Throwables.propagateIfInstanceOf(t, Error.class); @@ -69,11 +69,11 @@ public final class ArrayHashCodeOperator @TypeParameter("T") Type type, @SqlType("array(T)") Block block) { - int hash = 0; + long hash = 0; for (int i = 0; i < block.getPositionCount(); i++) { checkElementNotNull(block.isNull(i), ARRAY_NULL_ELEMENT_MSG); try { - hash = (int) CombineHashFunction.getHash(hash, (long) hashFunction.invokeExact(type.getLong(block, i))); + hash = CombineHashFunction.getHash(hash, (long) hashFunction.invokeExact(type.getLong(block, i))); } catch (Throwable t) { Throwables.propagateIfInstanceOf(t, Error.class); @@ -93,11 +93,11 @@ public final class ArrayHashCodeOperator @TypeParameter("T") Type type, @SqlType("array(T)") Block block) { - int hash = 0; + long hash = 0; for (int i = 0; i < block.getPositionCount(); i++) { checkElementNotNull(block.isNull(i), ARRAY_NULL_ELEMENT_MSG); try { - hash = (int) CombineHashFunction.getHash(hash, (long) hashFunction.invokeExact(type.getBoolean(block, i))); + hash = CombineHashFunction.getHash(hash, (long) hashFunction.invokeExact(type.getBoolean(block, i))); } catch (Throwable t) { Throwables.propagateIfInstanceOf(t, Error.class); @@ -117,11 +117,11 @@ public final class ArrayHashCodeOperator @TypeParameter("T") Type type, @SqlType("array(T)") Block block) { - int hash = 0; + long hash = 0; for (int i = 0; i < block.getPositionCount(); i++) { checkElementNotNull(block.isNull(i), ARRAY_NULL_ELEMENT_MSG); try { - hash = (int) CombineHashFunction.getHash(hash, (long) hashFunction.invokeExact(type.getSlice(block, i))); + hash = CombineHashFunction.getHash(hash, (long) hashFunction.invokeExact(type.getSlice(block, i))); } catch (Throwable t) { Throwables.propagateIfInstanceOf(t, Error.class); @@ -141,11 +141,11 @@ public final class ArrayHashCodeOperator @TypeParameter("T") Type type, @SqlType("array(T)") Block block) { - int hash = 0; + long hash = 0; for (int i = 0; i < block.getPositionCount(); i++) { checkElementNotNull(block.isNull(i), ARRAY_NULL_ELEMENT_MSG); try { - hash = (int) CombineHashFunction.getHash(hash, (long) hashFunction.invokeExact(type.getDouble(block, i))); + hash = CombineHashFunction.getHash(hash, (long) hashFunction.invokeExact(type.getDouble(block, i))); } catch (Throwable t) { Throwables.propagateIfInstanceOf(t, Error.class); diff --git a/presto-main/src/main/java/com/facebook/presto/type/ArrayType.java b/presto-main/src/main/java/com/facebook/presto/type/ArrayType.java index f6e8aca6ff..c9d5d4ad70 100644 --- a/presto-main/src/main/java/com/facebook/presto/type/ArrayType.java +++ b/presto-main/src/main/java/com/facebook/presto/type/ArrayType.java @@ -89,10 +89,10 @@ public class ArrayType public long hash(Block block, int position) { Block array = getObject(block, position); - int hash = 0; + long hash = 0; for (int i = 0; i < array.getPositionCount(); i++) { checkElementNotNull(array.isNull(i), ARRAY_NULL_ELEMENT_MSG); - hash = (int) CombineHashFunction.getHash(hash, elementType.hash(array, i)); + hash = CombineHashFunction.getHash(hash, elementType.hash(array, i)); } return hash; } diff --git a/presto-main/src/main/java/com/facebook/presto/type/MapType.java b/presto-main/src/main/java/com/facebook/presto/type/MapType.java index 76fd439ca3..ab3baad727 100644 --- a/presto-main/src/main/java/com/facebook/presto/type/MapType.java +++ b/presto-main/src/main/java/com/facebook/presto/type/MapType.java @@ -89,7 +89,7 @@ public class MapType public long hash(Block block, int position) { Block mapBlock = getObject(block, position); - int result = 0; + long result = 0; for (int i = 0; i < mapBlock.getPositionCount(); i += 2) { result += hashPosition(keyType, mapBlock, i); diff --git a/presto-main/src/test/java/com/facebook/presto/operator/scalar/AbstractTestFunctions.java b/presto-main/src/test/java/com/facebook/presto/operator/scalar/AbstractTestFunctions.java index 7c2c9e1945..f9f2b300b9 100644 --- a/presto-main/src/test/java/com/facebook/presto/operator/scalar/AbstractTestFunctions.java +++ b/presto-main/src/test/java/com/facebook/presto/operator/scalar/AbstractTestFunctions.java @@ -19,6 +19,7 @@ import com.facebook.presto.metadata.Metadata; import com.facebook.presto.metadata.SqlFunction; import com.facebook.presto.spi.ErrorCodeSupplier; import com.facebook.presto.spi.PrestoException; +import com.facebook.presto.spi.function.OperatorType; import com.facebook.presto.spi.type.DecimalParseResult; import com.facebook.presto.spi.type.Decimals; import com.facebook.presto.spi.type.SqlDecimal; @@ -32,6 +33,7 @@ import java.math.BigInteger; import java.util.List; import static com.facebook.presto.SessionTestUtils.TEST_SESSION; +import static com.facebook.presto.metadata.FunctionRegistry.mangleOperatorName; import static com.facebook.presto.spi.StandardErrorCode.INVALID_CAST_ARGUMENT; import static com.facebook.presto.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT; import static com.facebook.presto.spi.StandardErrorCode.NUMERIC_VALUE_OUT_OF_RANGE; @@ -65,6 +67,11 @@ public abstract class AbstractTestFunctions functionAssertions.assertFunction(projection, expectedType, expected); } + protected void assertOperator(OperatorType operator, String value, Type expectedType, Object expected) + { + functionAssertions.assertFunction(format("\\"%s\\"(%s)", mangleOperatorName(operator), value), expectedType, expected); + } + protected void assertDecimalFunction(String statement, SqlDecimal expectedResult) { assertFunction(statement, diff --git a/presto-main/src/test/java/com/facebook/presto/type/TestArrayOperators.java b/presto-main/src/test/java/com/facebook/presto/type/TestArrayOperators.java index cd3c122c65..eb82bbc6ca 100644 --- a/presto-main/src/test/java/com/facebook/presto/type/TestArrayOperators.java +++ b/presto-main/src/test/java/com/facebook/presto/type/TestArrayOperators.java @@ -17,8 +17,11 @@ import com.facebook.presto.operator.scalar.AbstractTestFunctions; import com.facebook.presto.spi.ErrorCode; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.block.Block; +import com.facebook.presto.spi.block.BlockBuilder; import com.facebook.presto.spi.block.BlockBuilderStatus; +import com.facebook.presto.spi.block.InterleavedBlockBuilder; import com.facebook.presto.spi.type.SqlTimestamp; +import com.facebook.presto.spi.type.Type; import com.facebook.presto.sql.analyzer.SemanticErrorCode; import com.facebook.presto.sql.analyzer.SemanticException; import com.google.common.collect.ImmutableList; @@ -39,6 +42,7 @@ import static com.facebook.presto.block.BlockSerdeUtil.writeBlock; import static com.facebook.presto.spi.StandardErrorCode.INVALID_CAST_ARGUMENT; import static com.facebook.presto.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT; import static com.facebook.presto.spi.StandardErrorCode.NOT_SUPPORTED; +import static com.facebook.presto.spi.function.OperatorType.HASH_CODE; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.BooleanType.BOOLEAN; import static com.facebook.presto.spi.type.DoubleType.DOUBLE; @@ -50,6 +54,7 @@ import static com.facebook.presto.sql.analyzer.SemanticErrorCode.AMBIGUOUS_FUNCT import static com.facebook.presto.sql.analyzer.SemanticErrorCode.FUNCTION_NOT_FOUND; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.TYPE_MISMATCH; import static com.facebook.presto.type.JsonType.JSON; +import static com.facebook.presto.type.TypeJsonUtils.appendToBlockBuilder; import static com.facebook.presto.type.UnknownType.UNKNOWN; import static com.facebook.presto.util.StructuralTestUtil.arrayBlockOf; import static java.lang.Double.NEGATIVE_INFINITY; @@ -935,6 +940,20 @@ public class TestArrayOperators assertFunction("flatten(ARRAY [NULL, ARRAY [MAP (ARRAY [3, 4], ARRAY [3, 4])]])", new ArrayType(new MapType(INTEGER, INTEGER)), ImmutableList.of(ImmutableMap.of(3, 3, 4, 4))); } + @Test + public void testArrayHashOperator() + { + assertArrayHashOperator("ARRAY[1, 2]", INTEGER, ImmutableList.of(1, 2)); + assertArrayHashOperator("ARRAY[true, false]", BOOLEAN, ImmutableList.of(true, false)); + + // test with ARRAY[ MAP( ARRAY[1], ARRAY[2] ) ] + MapType mapType = new MapType(INTEGER, INTEGER); + BlockBuilder mapBuilder = new InterleavedBlockBuilder(ImmutableList.of(INTEGER, INTEGER), new BlockBuilderStatus(), 2); + INTEGER.writeLong(mapBuilder, 1); + INTEGER.writeLong(mapBuilder, 2); + assertArrayHashOperator("ARRAY[MAP(ARRAY[1], ARRAY[2])]", mapType, ImmutableList.of(mapBuilder.build())); + } + public void assertInvalidFunction(String projection, ErrorCode errorCode) { try { @@ -946,6 +965,19 @@ public class TestArrayOperators } } + private void assertArrayHashOperator(String inputArray, Type elementType, List<Object> elements) + { + ArrayType arrayType = new ArrayType(elementType); + BlockBuilder arrayArrayBuilder = arrayType.createBlockBuilder(new BlockBuilderStatus(), 1); + BlockBuilder arrayBuilder = elementType.createBlockBuilder(new BlockBuilderStatus(), elements.size()); + for (Object element : elements) { + appendToBlockBuilder(elementType, element, arrayBuilder); + } + arrayType.writeObject(arrayArrayBuilder, arrayBuilder.build()); + + assertOperator(HASH_CODE, inputArray, BIGINT, arrayType.hash(arrayArrayBuilder.build(), 0)); + } + private SqlTimestamp sqlTimestamp(long millisUtc) { return new SqlTimestamp(millisUtc, TEST_SESSION.getTimeZoneKey()); diff --git a/presto-main/src/test/java/com/facebook/presto/type/TestMapOperators.java b/presto-main/src/test/java/com/facebook/presto/type/TestMapOperators.java index e7a7ce7b70..c93d93f4ad 100644 --- a/presto-main/src/test/java/com/facebook/presto/type/TestMapOperators.java +++ b/presto-main/src/test/java/com/facebook/presto/type/TestMapOperators.java @@ -15,6 +15,7 @@ package com.facebook.presto.type; import com.facebook.presto.operator.scalar.AbstractTestFunctions; import com.facebook.presto.spi.block.Block; +import com.facebook.presto.spi.block.BlockBuilder; import com.facebook.presto.spi.block.BlockBuilderStatus; import com.facebook.presto.spi.block.InterleavedBlockBuilder; import com.facebook.presto.spi.function.ScalarFunction; @@ -31,10 +32,12 @@ import io.airlift.slice.Slice; import org.testng.annotations.Test; import java.util.HashMap; +import java.util.List; import java.util.Map; import static com.facebook.presto.SessionTestUtils.TEST_SESSION; import static com.facebook.presto.block.BlockSerdeUtil.writeBlock; +import static com.facebook.presto.spi.function.OperatorType.HASH_CODE; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.BooleanType.BOOLEAN; import static com.facebook.presto.spi.type.DoubleType.DOUBLE; @@ -44,9 +47,12 @@ import static com.facebook.presto.spi.type.VarbinaryType.VARBINARY; import static com.facebook.presto.spi.type.VarcharType.VARCHAR; import static com.facebook.presto.spi.type.VarcharType.createVarcharType; import static com.facebook.presto.type.JsonType.JSON; +import static com.facebook.presto.type.TypeJsonUtils.appendToBlockBuilder; import static com.facebook.presto.type.UnknownType.UNKNOWN; import static com.facebook.presto.util.StructuralTestUtil.arrayBlockOf; import static com.facebook.presto.util.StructuralTestUtil.mapBlockOf; +import static com.google.common.base.Preconditions.checkArgument; +import static io.airlift.slice.Slices.utf8Slice; import static java.lang.Double.doubleToLongBits; import static java.nio.charset.StandardCharsets.UTF_8; import static org.testng.Assert.assertEquals; @@ -449,4 +455,30 @@ public class TestMapOperators assertInvalidCast("CAST(MAP(ARRAY[1, 2], ARRAY[6, 9]) AS MAP<boolean, bigint>)", "duplicate keys"); } + + @Test + public void testMapHashOperator() + { + assertMapHashOperator("MAP(ARRAY[1], ARRAY[2])", INTEGER, INTEGER, ImmutableList.of(1, 2)); + assertMapHashOperator("MAP(ARRAY[1, 2147483647], ARRAY[2147483647, 2])", INTEGER, INTEGER, ImmutableList.of(1, 2147483647, 2147483647, 2)); + assertMapHashOperator("MAP(ARRAY[8589934592], ARRAY[2])", BIGINT, INTEGER, ImmutableList.of(8589934592L, 2)); + assertMapHashOperator("MAP(ARRAY[true], ARRAY[false])", BOOLEAN, BOOLEAN, ImmutableList.of(true, false)); + assertMapHashOperator("MAP(ARRAY['123'], ARRAY['456'])", VARCHAR, VARCHAR, ImmutableList.of(utf8Slice("123"), utf8Slice("456"))); + } + + private void assertMapHashOperator(String inputString, Type keyType, Type valueType, List<Object> elements) + { + checkArgument(elements.size() % 2 == 0, "the size of elements should be even number"); + MapType mapType = new MapType(keyType, valueType); + BlockBuilder mapArrayBuilder = mapType.createBlockBuilder(new BlockBuilderStatus(), 1); + BlockBuilder mapBuilder = new InterleavedBlockBuilder(ImmutableList.of(keyType, valueType), new BlockBuilderStatus(), elements.size()); + for (int i = 0; i < elements.size(); i += 2) { + appendToBlockBuilder(keyType, elements.get(i), mapBuilder); + appendToBlockBuilder(valueType, elements.get(i + 1), mapBuilder); + } + mapType.writeObject(mapArrayBuilder, mapBuilder.build()); + long hashResult = mapType.hash(mapArrayBuilder.build(), 0); + + assertOperator(HASH_CODE, inputString, BIGINT, hashResult); + } } diff --git a/presto-main/src/test/java/com/facebook/presto/type/TestRowOperators.java b/presto-main/src/test/java/com/facebook/presto/type/TestRowOperators.java index 7dfc6a807a..5161d6ca40 100644 --- a/presto-main/src/test/java/com/facebook/presto/type/TestRowOperators.java +++ b/presto-main/src/test/java/com/facebook/presto/type/TestRowOperators.java @@ -16,6 +16,9 @@ package com.facebook.presto.type; import com.facebook.presto.operator.scalar.AbstractTestFunctions; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.StandardErrorCode; +import com.facebook.presto.spi.block.BlockBuilder; +import com.facebook.presto.spi.block.BlockBuilderStatus; +import com.facebook.presto.spi.block.InterleavedBlockBuilder; import com.facebook.presto.spi.type.SqlTimestamp; import com.facebook.presto.spi.type.Type; import com.facebook.presto.sql.analyzer.SemanticException; @@ -24,8 +27,11 @@ import com.google.common.collect.ImmutableMap; import org.testng.annotations.Test; import java.util.Arrays; +import java.util.List; +import java.util.Optional; import static com.facebook.presto.SessionTestUtils.TEST_SESSION; +import static com.facebook.presto.spi.function.OperatorType.HASH_CODE; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.BooleanType.BOOLEAN; import static com.facebook.presto.spi.type.DoubleType.DOUBLE; @@ -33,6 +39,8 @@ import static com.facebook.presto.spi.type.IntegerType.INTEGER; import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature; import static com.facebook.presto.spi.type.VarcharType.VARCHAR; import static com.facebook.presto.type.JsonType.JSON; +import static com.facebook.presto.type.TypeJsonUtils.appendToBlockBuilder; +import static com.google.common.base.Preconditions.checkArgument; import static java.lang.String.format; import static org.testng.Assert.assertEquals; import static org.testng.Assert.fail; @@ -203,4 +211,25 @@ public class TestRowOperators assertFunction("ROW(1, 2) = ROW(1, 2)", BOOLEAN, true); assertFunction("ROW(2, 1) != ROW(1, 2)", BOOLEAN, true); } + + @Test + public void testRowHashOperator() + { + assertRowHashOperator("ROW(1, 2)", ImmutableList.of(INTEGER, INTEGER), ImmutableList.of(1, 2)); + assertRowHashOperator("ROW(true, 2)", ImmutableList.of(BOOLEAN, INTEGER), ImmutableList.of(true, 2)); + } + + private void assertRowHashOperator(String inputString, List<Type> types, List<Object> elements) + { + checkArgument(types.size() == elements.size(), "types and elements must have the same size"); + RowType rowType = new RowType(types, Optional.empty()); + BlockBuilder rowArrayBuilder = rowType.createBlockBuilder(new BlockBuilderStatus(), 1); + BlockBuilder rowBuilder = new InterleavedBlockBuilder(types, new BlockBuilderStatus(), types.size()); + for (int i = 0; i < types.size(); i++) { + appendToBlockBuilder(types.get(i), elements.get(i), rowBuilder); + } + rowType.writeObject(rowArrayBuilder, rowBuilder.build()); + + assertOperator(HASH_CODE, inputString, BIGINT, rowType.hash(rowArrayBuilder.build(), 0)); + } } diff --git a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java index cb3d73e359..c2d21db432 100644 --- a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java +++ b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java @@ -2790,6 +2790,9 @@ public abstract class AbstractTestQueries assertQuery( "SELECT CASE WHEN false THEN 1 IN (VALUES 2) END", "SELECT NULL"); + assertQuery( + "SELECT x FROM (VALUES 2) t(x) where MAP(ARRAY[8589934592], ARRAY[x]) IN (VALUES MAP(ARRAY[8589934592],ARRAY[2]))", + "SELECT 2"); } @Test
['presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java', 'presto-main/src/test/java/com/facebook/presto/operator/scalar/AbstractTestFunctions.java', 'presto-main/src/main/java/com/facebook/presto/type/ArrayType.java', 'presto-main/src/test/java/com/facebook/presto/type/TestArrayOperators.java', 'presto-main/src/main/java/com/facebook/presto/operator/scalar/ArrayHashCodeOperator.java', 'presto-main/src/test/java/com/facebook/presto/type/TestRowOperators.java', 'presto-main/src/test/java/com/facebook/presto/type/TestMapOperators.java', 'presto-main/src/main/java/com/facebook/presto/type/MapType.java']
{'.java': 8}
8
8
0
0
8
13,232,162
2,630,525
367,911
2,670
1,712
384
26
3
157
23
53
10
0
1
1970-01-01T00:24:37
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
187
prestodb/presto/6427/6379
prestodb
presto
https://github.com/prestodb/presto/issues/6379
https://github.com/prestodb/presto/pull/6427
https://github.com/prestodb/presto/pull/6427
1
fixes
Incorrect results when GROUPING SETS refer to columns derived from same column
This query: ``` sql WITH t (v) AS (VALUES 1, 2), u (v1, v2) AS (SELECT v v1, v v2 FROM t) SELECT v1, v2 FROM u GROUP BY GROUPING SETS ((v1), (v2)) ``` incorrectly produces: ``` v1 | v2 ----+---- 1 | 1 2 | 2 1 | 1 2 | 2 (4 rows) ``` The expected result is: ``` v1 | v2 ------+------ 1 | NULL 2 | NULL NULL | 1 NULL | 2 (4 rows) ```
fa726a95f9f279df415275ae66b90ad8252dae07
8548ba813f2d426911062e59efa079ed296d44a6
https://github.com/prestodb/presto/compare/fa726a95f9f279df415275ae66b90ad8252dae07...8548ba813f2d426911062e59efa079ed296d44a6
diff --git a/presto-main/src/main/java/com/facebook/presto/operator/GroupIdOperator.java b/presto-main/src/main/java/com/facebook/presto/operator/GroupIdOperator.java index 18653de108..30588fe289 100644 --- a/presto-main/src/main/java/com/facebook/presto/operator/GroupIdOperator.java +++ b/presto-main/src/main/java/com/facebook/presto/operator/GroupIdOperator.java @@ -22,14 +22,11 @@ import com.facebook.presto.spi.type.Type; import com.facebook.presto.sql.planner.plan.PlanNodeId; import com.google.common.collect.ImmutableList; -import java.util.BitSet; -import java.util.Collection; +import java.util.Arrays; import java.util.List; -import java.util.Set; +import java.util.Map; import static com.facebook.presto.spi.type.BigintType.BIGINT; -import static com.facebook.presto.util.ImmutableCollectors.toImmutableSet; -import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static java.util.Objects.requireNonNull; @@ -42,9 +39,7 @@ public class GroupIdOperator private final int operatorId; private final PlanNodeId planNodeId; private final List<Type> outputTypes; - private final List<List<Integer>> groupingSetChannels; - private final List<Integer> groupingChannels; - private final List<Integer> copyChannels; + private final List<Map<Integer, Integer>> groupingSetMappings; private boolean closed; @@ -52,16 +47,12 @@ public class GroupIdOperator int operatorId, PlanNodeId planNodeId, List<? extends Type> outputTypes, - List<List<Integer>> groupingSetChannels, - List<Integer> groupingChannels, - List<Integer> copyChannels) + List<Map<Integer, Integer>> groupingSetMappings) { this.operatorId = operatorId; this.planNodeId = requireNonNull(planNodeId, "planNodeId is null"); this.outputTypes = ImmutableList.copyOf(requireNonNull(outputTypes)); - this.groupingSetChannels = ImmutableList.copyOf(requireNonNull(groupingSetChannels)); - this.groupingChannels = ImmutableList.copyOf(requireNonNull(groupingChannels)); - this.copyChannels = ImmutableList.copyOf(requireNonNull(copyChannels)); + this.groupingSetMappings = ImmutableList.copyOf(requireNonNull(groupingSetMappings)); } @Override @@ -76,48 +67,35 @@ public class GroupIdOperator checkState(!closed, "Factory is already closed"); OperatorContext operatorContext = driverContext.addOperatorContext(operatorId, planNodeId, GroupIdOperator.class.getSimpleName()); - Set<Integer> allGroupingColumns = groupingSetChannels.stream() - .flatMap(Collection::stream) - .collect(toImmutableSet()); - - // create an array of bitset for fast lookup of which columns are part of a given grouping set - // will have a 'true' for every channel that should be set to null for each grouping set - BitSet[] groupingSetNullChannels = new BitSet[groupingSetChannels.size()]; - for (int i = 0; i < groupingSetChannels.size(); i++) { - groupingSetNullChannels[i] = new BitSet(groupingChannels.size() + copyChannels.size()); - // first set all grouping columns to true - for (int groupingColumn : allGroupingColumns) { - groupingSetNullChannels[i].set(groupingColumn, true); - } - // then set all the columns in this grouping set to false - for (int nonNullGroupingColumn : groupingSetChannels.get(i)) { - groupingSetNullChannels[i].set(nonNullGroupingColumn, false); + // create an int array for fast lookup of input columns for every grouping set + int[][] groupingSetInputs = new int[groupingSetMappings.size()][outputTypes.size() - 1]; + for (int i = 0; i < groupingSetMappings.size(); i++) { + // -1 means the output column is null + Arrays.fill(groupingSetInputs[i], -1); + + // anything else is an input column to copy + for (int outputChannel : groupingSetMappings.get(i).keySet()) { + groupingSetInputs[i][outputChannel] = groupingSetMappings.get(i).get(outputChannel); } } - // create null blocks for every grouping channel - Block[] nullBlocks = new Block[groupingChannels.size()]; - for (int i = 0; i < groupingChannels.size(); i++) { + // it's easier to create null blocks for every output column even though we only null out some grouping column outputs + Block[] nullBlocks = new Block[outputTypes.size()]; + for (int i = 0; i < outputTypes.size(); i++) { nullBlocks[i] = outputTypes.get(i).createBlockBuilder(new BlockBuilderStatus(), 1) .appendNull() .build(); } // create groupid blocks for every group - Block[] groupIdBlocks = new Block[groupingSetNullChannels.length]; - for (int i = 0; i < groupingSetNullChannels.length; i++) { + Block[] groupIdBlocks = new Block[groupingSetMappings.size()]; + for (int i = 0; i < groupingSetMappings.size(); i++) { BlockBuilder builder = BIGINT.createBlockBuilder(new BlockBuilderStatus(), 1); BIGINT.writeLong(builder, i); groupIdBlocks[i] = builder.build(); } - // create array of input channels for every grouping channel - int[] groupInputs = groupingChannels.stream().mapToInt(Integer::intValue).toArray(); - - // create array of input channels for every copy channel - int[] copyInputs = copyChannels.stream().mapToInt(Integer::intValue).toArray(); - - return new GroupIdOperator(operatorContext, outputTypes, groupingSetNullChannels, nullBlocks, groupIdBlocks, groupInputs, copyInputs); + return new GroupIdOperator(operatorContext, outputTypes, groupingSetInputs, nullBlocks, groupIdBlocks); } @Override @@ -129,17 +107,15 @@ public class GroupIdOperator @Override public OperatorFactory duplicate() { - return new GroupIdOperatorFactory(operatorId, planNodeId, outputTypes, groupingSetChannels, groupingChannels, copyChannels); + return new GroupIdOperatorFactory(operatorId, planNodeId, outputTypes, groupingSetMappings); } } private final OperatorContext operatorContext; private final List<Type> types; - private final BitSet[] groupingSetNullChannels; + private final int[][] groupingSetInputs; private final Block[] nullBlocks; private final Block[] groupIdBlocks; - private final int[] groupInputs; - private final int[] copyInputs; private Page currentPage = null; private int currentGroupingSet = 0; @@ -148,20 +124,15 @@ public class GroupIdOperator public GroupIdOperator( OperatorContext operatorContext, List<Type> types, - BitSet[] groupingSetNullChannels, + int[][] groupingSetInputs, Block[] nullBlocks, - Block[] groupIdBlocks, - int[] groupInputs, - int[] copyInputs) + Block[] groupIdBlocks) { this.operatorContext = requireNonNull(operatorContext, "operatorContext is null"); - this.types = requireNonNull(types, "types is null"); - this.groupingSetNullChannels = requireNonNull(groupingSetNullChannels, "groupingSetNullChannels is null"); - this.nullBlocks = requireNonNull(nullBlocks); - this.groupIdBlocks = requireNonNull(groupIdBlocks); - checkArgument(groupIdBlocks.length == groupingSetNullChannels.length, "groupIdBlocks and groupingSetNullChannels must have the same length"); - this.groupInputs = requireNonNull(groupInputs); - this.copyInputs = requireNonNull(copyInputs); + this.types = ImmutableList.copyOf(requireNonNull(types, "types is null")); + this.groupingSetInputs = requireNonNull(groupingSetInputs, "groupingSetInputs is null"); + this.nullBlocks = requireNonNull(nullBlocks, "nullBlocks is null"); + this.groupIdBlocks = requireNonNull(groupIdBlocks, "groupIdBlocks is null"); } @Override @@ -218,21 +189,17 @@ public class GroupIdOperator // generate 'n' pages for every input page, where n is the number of grouping sets Block[] outputBlocks = new Block[types.size()]; - for (int i = 0; i < groupInputs.length; i++) { - if (groupingSetNullChannels[currentGroupingSet].get(groupInputs[i])) { + for (int i = 0; i < groupingSetInputs[currentGroupingSet].length; i++) { + if (groupingSetInputs[currentGroupingSet][i] == -1) { outputBlocks[i] = new RunLengthEncodedBlock(nullBlocks[i], currentPage.getPositionCount()); } else { - outputBlocks[i] = currentPage.getBlock(groupInputs[i]); + outputBlocks[i] = currentPage.getBlock(groupingSetInputs[currentGroupingSet][i]); } } - for (int i = 0; i < copyInputs.length; i++) { - outputBlocks[groupInputs.length + i] = currentPage.getBlock(copyInputs[i]); - } - outputBlocks[outputBlocks.length - 1] = new RunLengthEncodedBlock(groupIdBlocks[currentGroupingSet], currentPage.getPositionCount()); - currentGroupingSet = (currentGroupingSet + 1) % groupingSetNullChannels.length; + currentGroupingSet = (currentGroupingSet + 1) % groupingSetInputs.length; Page outputPage = new Page(currentPage.getPositionCount(), outputBlocks); if (currentGroupingSet == 0) { diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/LocalExecutionPlanner.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/LocalExecutionPlanner.java index 24acf28fe5..b3a4d5344a 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/LocalExecutionPlanner.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/LocalExecutionPlanner.java @@ -832,42 +832,50 @@ public class LocalExecutionPlanner public PhysicalOperation visitGroupId(GroupIdNode node, LocalExecutionPlanContext context) { PhysicalOperation source = node.getSource().accept(this, context); - ImmutableMap.Builder<Symbol, Integer> newLayout = ImmutableMap.builder(); + Map<Symbol, Integer> newLayout = new HashMap<>(); ImmutableList.Builder<Type> outputTypes = ImmutableList.builder(); int outputChannel = 0; - ImmutableList.Builder<Integer> groupingChannels = ImmutableList.builder(); - for (Symbol inputSymbol : node.getDistinctGroupingColumns()) { - int inputChannel = source.getLayout().get(inputSymbol); - newLayout.put(inputSymbol, outputChannel++); - outputTypes.add(source.getTypes().get(inputChannel)); - groupingChannels.add(inputChannel); + for (Symbol output : node.getGroupingSets().stream().flatMap(Collection::stream).collect(Collectors.toSet())) { + newLayout.put(output, outputChannel++); + outputTypes.add(source.getTypes().get(source.getLayout().get(node.getGroupingSetMappings().get(output)))); } - ImmutableList.Builder<Integer> copyChannels = ImmutableList.builder(); - for (Symbol inputSymbol : node.getIdentityMappings().keySet()) { - int inputChannel = source.getLayout().get(inputSymbol); - newLayout.put(node.getIdentityMappings().get(inputSymbol), outputChannel++); + Map<Symbol, Integer> argumentMappings = new HashMap<>(); + for (Symbol output : node.getArgumentMappings().keySet()) { + int inputChannel = source.getLayout().get(node.getArgumentMappings().get(output)); + + newLayout.put(output, outputChannel++); outputTypes.add(source.getTypes().get(inputChannel)); - copyChannels.add(inputChannel); + argumentMappings.put(output, inputChannel); + } + + // for every grouping set, create a mapping of all output to input channels (including arguments) + ImmutableList.Builder<Map<Integer, Integer>> mappings = ImmutableList.builder(); + for (List<Symbol> groupingSet : node.getGroupingSets()) { + ImmutableMap.Builder<Integer, Integer> setMapping = ImmutableMap.builder(); + + for (Symbol output : groupingSet) { + setMapping.put(newLayout.get(output), source.getLayout().get(node.getGroupingSetMappings().get(output))); + } + + for (Symbol output : argumentMappings.keySet()) { + setMapping.put(newLayout.get(output), argumentMappings.get(output)); + } + + mappings.add(setMapping.build()); } newLayout.put(node.getGroupIdSymbol(), outputChannel); outputTypes.add(BIGINT); - List<List<Integer>> groupingSetChannels = node.getGroupingSets().stream() - .map(groupingSet -> getChannelsForSymbols(groupingSet, source.getLayout())) - .collect(toImmutableList()); - OperatorFactory groupIdOperatorFactory = new GroupIdOperator.GroupIdOperatorFactory(context.getNextOperatorId(), node.getId(), outputTypes.build(), - groupingSetChannels, - groupingChannels.build(), - copyChannels.build()); + mappings.build()); - return new PhysicalOperation(groupIdOperatorFactory, newLayout.build(), source); + return new PhysicalOperation(groupIdOperatorFactory, newLayout, source); } @Override diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/PlanPrinter.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/PlanPrinter.java index b22f3d5665..84092bcff7 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/PlanPrinter.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/PlanPrinter.java @@ -523,7 +523,23 @@ public class PlanPrinter @Override public Void visitGroupId(GroupIdNode node, Integer indent) { - print(indent, "- GroupId%s => [%s]", node.getGroupingSets(), formatOutputs(node.getOutputSymbols())); + // grouping sets are easier to understand in terms of inputs + List<List<Symbol>> inputGroupingSetSymbols = node.getGroupingSets().stream() + .map(set -> set.stream() + .map(symbol -> node.getGroupingSetMappings().get(symbol)) + .collect(Collectors.toList())) + .collect(Collectors.toList()); + + print(indent, "- GroupId%s => [%s]", inputGroupingSetSymbols, formatOutputs(node.getOutputSymbols())); + printStats(indent + 2, node.getId()); + + for (Map.Entry<Symbol, Symbol> mapping : node.getGroupingSetMappings().entrySet()) { + print(indent + 2, "%s := %s", mapping.getKey(), mapping.getValue()); + } + for (Map.Entry<Symbol, Symbol> argument : node.getArgumentMappings().entrySet()) { + print(indent + 2, "%s := %s", argument.getKey(), argument.getValue()); + } + return processChildren(node, indent + 1); } diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/QueryPlanner.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/QueryPlanner.java index 3c5978bedf..323048bc9f 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/QueryPlanner.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/QueryPlanner.java @@ -60,6 +60,7 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; +import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; @@ -383,47 +384,81 @@ class QueryPlanner // 2. Aggregate - // 2.a. Rewrite group by expressions in terms of pre-projected inputs - TranslationMap translations = new TranslationMap(subPlan.getRelationPlan(), analysis); - ImmutableList.Builder<List<Symbol>> groupingSetsSymbolsBuilder = ImmutableList.builder(); + // 2.a. Rewrite aggregate arguments + TranslationMap argumentTranslations = new TranslationMap(subPlan.getRelationPlan(), analysis); + ImmutableMap.Builder<Symbol, Symbol> argumentMappingBuilder = ImmutableMap.builder(); + for (Expression argument : arguments) { + Expression parametersReplaced = ExpressionTreeRewriter.rewriteWith(new ParameterRewriter(analysis.getParameters(), analysis), argument); + argumentTranslations.addIntermediateMapping(argument, parametersReplaced); + Symbol input = subPlan.translate(parametersReplaced); + + if (!argumentTranslations.containsSymbol(parametersReplaced)) { + Symbol output = symbolAllocator.newSymbol(parametersReplaced, analysis.getTypeWithCoercions(parametersReplaced), "arg"); + argumentMappingBuilder.put(output, input); + argumentTranslations.put(parametersReplaced, output); + } + } + Map<Symbol, Symbol> argumentMappings = argumentMappingBuilder.build(); + + // 2.b. Rewrite grouping columns + TranslationMap groupingTranslations = new TranslationMap(subPlan.getRelationPlan(), analysis); + Map<Symbol, Symbol> groupingSetMappings = new HashMap<>(); + List<List<Symbol>> groupingSymbols = new ArrayList<>(); + for (List<Expression> groupingSet : groupingSets) { - ImmutableList.Builder<Symbol> groupingColumns = ImmutableList.builder(); + ImmutableList.Builder<Symbol> symbols = ImmutableList.builder(); for (Expression expression : groupingSet) { - Expression rewritten = ExpressionTreeRewriter.rewriteWith(new ParameterRewriter(analysis.getParameters(), analysis), expression); - translations.addIntermediateMapping(expression, rewritten); - Symbol symbol = subPlan.translate(rewritten); - groupingColumns.add(symbol); - translations.put(rewritten, symbol); + Expression parametersReplaced = ExpressionTreeRewriter.rewriteWith(new ParameterRewriter(analysis.getParameters(), analysis), expression); + groupingTranslations.addIntermediateMapping(expression, parametersReplaced); + Symbol input = subPlan.translate(expression); + + Symbol output; + if (!groupingTranslations.containsSymbol(parametersReplaced)) { + output = symbolAllocator.newSymbol(parametersReplaced, analysis.getTypeWithCoercions(expression), "gid"); + groupingTranslations.put(parametersReplaced, output); + } + else { + output = groupingTranslations.get(parametersReplaced); + } + + groupingSetMappings.put(output, input); + symbols.add(output); } - groupingSetsSymbolsBuilder.add(groupingColumns.build()); + groupingSymbols.add(symbols.build()); } - // 2.b. Add a groupIdNode and groupIdSymbol if there are multiple grouping sets + // 2.c. Generate GroupIdNode (multiple grouping sets) or ProjectNode (single grouping set) Optional<Symbol> groupIdSymbol = Optional.empty(); - List<List<Symbol>> groupingSetsSymbols = groupingSetsSymbolsBuilder.build(); if (groupingSets.size() > 1) { - ImmutableMap.Builder<Symbol, Symbol> identityMapping = ImmutableMap.builder(); - for (Expression argument : ImmutableSet.copyOf(arguments)) { - Symbol output = symbolAllocator.newSymbol(argument, analysis.getTypeWithCoercions(argument), "id"); - identityMapping.put(subPlan.translate(argument), output); + groupIdSymbol = Optional.of(symbolAllocator.newSymbol("groupId", BIGINT)); + GroupIdNode groupId = new GroupIdNode(idAllocator.getNextId(), subPlan.getRoot(), groupingSymbols, groupingSetMappings, argumentMappings, groupIdSymbol.get()); + subPlan = new PlanBuilder(groupingTranslations, groupId, analysis.getParameters()); + } + else { + Map<Symbol, Expression> projections = new HashMap<>(); + for (Symbol output : argumentMappings.keySet()) { + projections.putIfAbsent(output, argumentMappings.get(output).toSymbolReference()); + } - // relies on the fact that group by expressions have already been re-written, and will not be affected by this mapping change - subPlan.getTranslations().put(argument, output); + for (Symbol output : groupingSetMappings.keySet()) { + projections.putIfAbsent(output, groupingSetMappings.get(output).toSymbolReference()); } - groupIdSymbol = Optional.of(symbolAllocator.newSymbol("groupId", BIGINT)); - GroupIdNode groupId = new GroupIdNode(idAllocator.getNextId(), subPlan.getRoot(), groupingSetsSymbols, identityMapping.build(), groupIdSymbol.get()); - subPlan = subPlan.withNewRoot(groupId); + ProjectNode project = new ProjectNode(idAllocator.getNextId(), subPlan.getRoot(), projections); + subPlan = new PlanBuilder(groupingTranslations, project, analysis.getParameters()); } - // 2.c. Rewrite aggregates in terms of pre-projected inputs + TranslationMap aggregationTranslations = new TranslationMap(subPlan.getRelationPlan(), analysis); + aggregationTranslations.copyMappingsFrom(groupingTranslations); + + // 2.d. Rewrite aggregates ImmutableMap.Builder<Symbol, FunctionCall> aggregationAssignments = ImmutableMap.builder(); ImmutableMap.Builder<Symbol, Signature> functions = ImmutableMap.builder(); boolean needPostProjectionCoercion = false; for (FunctionCall aggregate : analysis.getAggregates(node)) { Expression parametersReplaced = ExpressionTreeRewriter.rewriteWith(new ParameterRewriter(analysis.getParameters(), analysis), aggregate); - translations.addIntermediateMapping(aggregate, parametersReplaced); - Expression rewritten = subPlan.rewrite(parametersReplaced); + aggregationTranslations.addIntermediateMapping(aggregate, parametersReplaced); + Expression rewritten = argumentTranslations.rewrite(parametersReplaced); Symbol newSymbol = symbolAllocator.newSymbol(rewritten, analysis.getType(aggregate)); // TODO: this is a hack, because we apply coercions to the output of expressions, rather than the arguments to expressions. @@ -433,12 +468,12 @@ class QueryPlanner needPostProjectionCoercion = true; } aggregationAssignments.put(newSymbol, (FunctionCall) rewritten); - translations.put(parametersReplaced, newSymbol); + aggregationTranslations.put(parametersReplaced, newSymbol); functions.put(newSymbol, analysis.getFunctionSignature(aggregate)); } - // 2.d. Mark distinct rows for each aggregate that has DISTINCT + // 2.e. Mark distinct rows for each aggregate that has DISTINCT // Map from aggregate function arguments to marker symbols, so that we can reuse the markers, if two aggregates have the same argument Map<Set<Expression>, Symbol> argumentMarkers = new HashMap<>(); // Map from aggregate functions to marker symbols @@ -446,7 +481,7 @@ class QueryPlanner for (FunctionCall aggregate : Iterables.filter(analysis.getAggregates(node), FunctionCall::isDistinct)) { Set<Expression> args = ImmutableSet.copyOf(aggregate.getArguments()); Symbol marker = argumentMarkers.get(args); - Symbol aggregateSymbol = translations.get(aggregate); + Symbol aggregateSymbol = aggregationTranslations.get(aggregate); if (marker == null) { if (args.size() == 1) { marker = symbolAllocator.newSymbol(getOnlyElement(args), BOOLEAN, "distinct"); @@ -462,14 +497,14 @@ class QueryPlanner for (Map.Entry<Set<Expression>, Symbol> entry : argumentMarkers.entrySet()) { ImmutableList.Builder<Symbol> builder = ImmutableList.builder(); - builder.addAll(groupingSetsSymbols.stream() + builder.addAll(groupingSymbols.stream() .flatMap(Collection::stream) .distinct() .collect(Collectors.toList())); groupIdSymbol.ifPresent(builder::add); for (Expression expression : entry.getKey()) { - builder.add(subPlan.translate(expression)); + builder.add(argumentTranslations.get(expression)); } subPlan = subPlan.withNewRoot( new MarkDistinctNode( @@ -486,12 +521,12 @@ class QueryPlanner aggregationAssignments.build(), functions.build(), masks, - groupingSetsSymbols, + groupingSymbols, AggregationNode.Step.SINGLE, Optional.empty(), groupIdSymbol); - subPlan = new PlanBuilder(translations, aggregationNode, analysis.getParameters()); + subPlan = new PlanBuilder(aggregationTranslations, aggregationNode, analysis.getParameters()); // 3. Post-projection // Add back the implicit casts that we removed in 2.a diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/SymbolExtractor.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/SymbolExtractor.java index 61c18e2263..129fee725e 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/SymbolExtractor.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/SymbolExtractor.java @@ -113,7 +113,8 @@ public final class SymbolExtractor node.getSource().accept(this, context); builder.add(node.getGroupIdSymbol()); - builder.addAll(node.getIdentityMappings().values()); + builder.addAll(node.getGroupingSetMappings().keySet()); + builder.addAll(node.getArgumentMappings().keySet()); return null; } diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/AddExchanges.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/AddExchanges.java index a444ff1d20..86bac59425 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/AddExchanges.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/AddExchanges.java @@ -312,15 +312,13 @@ public class AddExchanges private Function<Symbol, Optional<Symbol>> translateGroupIdSymbols(GroupIdNode node) { - Map<Symbol, Symbol> invertedMappings = ImmutableBiMap.copyOf(node.getIdentityMappings()).inverse(); - List<Symbol> commonGroupingColumns = node.getCommonGroupingColumns(); return symbol -> { - if (invertedMappings.containsKey(symbol)) { - return Optional.of(invertedMappings.get(symbol)); + if (node.getArgumentMappings().containsKey(symbol)) { + return Optional.of(node.getArgumentMappings().get(symbol)); } - if (commonGroupingColumns.contains(symbol)) { - return Optional.of(symbol); + if (node.getCommonGroupingColumns().contains(symbol)) { + return Optional.of(node.getGroupingSetMappings().get(symbol)); } return Optional.empty(); diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PredicatePushDown.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PredicatePushDown.java index 2753a999b2..3495784790 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PredicatePushDown.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PredicatePushDown.java @@ -30,7 +30,6 @@ import com.facebook.presto.sql.planner.Symbol; import com.facebook.presto.sql.planner.SymbolAllocator; import com.facebook.presto.sql.planner.plan.AggregationNode; import com.facebook.presto.sql.planner.plan.AssignUniqueId; -import com.facebook.presto.sql.planner.plan.ChildReplacer; import com.facebook.presto.sql.planner.plan.ExchangeNode; import com.facebook.presto.sql.planner.plan.FilterNode; import com.facebook.presto.sql.planner.plan.GroupIdNode; @@ -221,26 +220,25 @@ public class PredicatePushDown { checkState(!DependencyExtractor.extractUnique(context.get()).contains(node.getGroupIdSymbol()), "groupId symbol cannot be referenced in predicate"); - List<Symbol> commonGroupingSymbols = node.getCommonGroupingColumns(); + Map<Symbol, SymbolReference> commonGroupingSymbolMapping = node.getGroupingSetMappings().entrySet().stream() + .filter(entry -> node.getCommonGroupingColumns().contains(entry.getKey())) + .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().toSymbolReference())); + Predicate<Expression> pushdownEligiblePredicate = conjunct -> DependencyExtractor.extractUnique(conjunct).stream() - .allMatch(commonGroupingSymbols::contains); + .allMatch(commonGroupingSymbolMapping.keySet()::contains); Map<Boolean, List<Expression>> conjuncts = extractConjuncts(context.get()).stream().collect(Collectors.partitioningBy(pushdownEligiblePredicate)); - // Push down conjuncts from the inherited predicate that apply to the common grouping columns, or don't apply to any grouping columns - PlanNode rewrittenSource = context.rewrite(node.getSource(), combineConjuncts(conjuncts.get(true))); - - PlanNode output = node; - if (rewrittenSource != node.getSource()) { - output = ChildReplacer.replaceChildren(node, ImmutableList.of(rewrittenSource)); - } + // Push down conjuncts from the inherited predicate that apply to common grouping symbols + PlanNode rewrittenNode = context.defaultRewrite(node, + ExpressionTreeRewriter.rewriteWith(new ExpressionSymbolInliner(commonGroupingSymbolMapping), combineConjuncts(conjuncts.get(true)))); // All other conjuncts, if any, will be in the filter node. if (!conjuncts.get(false).isEmpty()) { - output = new FilterNode(idAllocator.getNextId(), output, combineConjuncts(conjuncts.get(false))); + rewrittenNode = new FilterNode(idAllocator.getNextId(), rewrittenNode, combineConjuncts(conjuncts.get(false))); } - return output; + return rewrittenNode; } @Override diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PropertyDerivations.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PropertyDerivations.java index 0d8aa9d9a5..8c8f3537df 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PropertyDerivations.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PropertyDerivations.java @@ -76,7 +76,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; -import java.util.function.Function; import static com.facebook.presto.SystemSessionProperties.planWithTableNodePartitioning; import static com.facebook.presto.spi.predicate.TupleDomain.extractFixedValues; @@ -222,23 +221,22 @@ class PropertyDerivations @Override public ActualProperties visitGroupId(GroupIdNode node, List<ActualProperties> inputProperties) { - return Iterables.getOnlyElement(inputProperties).translate(translateGroupIdSymbols(node)); - } - - private Function<Symbol, Optional<Symbol>> translateGroupIdSymbols(GroupIdNode node) - { - List<Symbol> commonGroupingColumns = node.getCommonGroupingColumns(); - return symbol -> { - if (node.getIdentityMappings().containsKey(symbol)) { - return Optional.of(node.getIdentityMappings().get(symbol)); + Map<Symbol, Symbol> inputToOutputMappings = new HashMap<>(); + for (Map.Entry<Symbol, Symbol> setMapping : node.getGroupingSetMappings().entrySet()) { + if (node.getCommonGroupingColumns().contains(setMapping.getKey())) { + // TODO: Add support for translating a property on a single column to multiple columns + // when GroupIdNode is copying a single input grouping column into multiple output grouping columns (i.e. aliases), this is basically picking one arbitrarily + inputToOutputMappings.putIfAbsent(setMapping.getValue(), setMapping.getKey()); } + } - if (commonGroupingColumns.contains(symbol)) { - return Optional.of(symbol); - } + // TODO: Add support for translating a property on a single column to multiple columns + // this is deliberately placed after the grouping columns, because preserving properties has a bigger perf impact + for (Map.Entry<Symbol, Symbol> argumentMapping : node.getArgumentMappings().entrySet()) { + inputToOutputMappings.putIfAbsent(argumentMapping.getValue(), argumentMapping.getKey()); + } - return Optional.empty(); - }; + return Iterables.getOnlyElement(inputProperties).translate(column -> Optional.ofNullable(inputToOutputMappings.get(column))); } @Override diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PruneUnreferencedOutputs.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PruneUnreferencedOutputs.java index 9658c59f7f..41eb36742b 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PruneUnreferencedOutputs.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PruneUnreferencedOutputs.java @@ -68,15 +68,16 @@ import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.Collection; +import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.stream.Collectors; import static com.facebook.presto.util.ImmutableCollectors.toImmutableList; import static com.facebook.presto.util.ImmutableCollectors.toImmutableSet; -import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Predicates.in; import static com.google.common.collect.Iterables.concat; import static java.util.Objects.requireNonNull; @@ -408,23 +409,31 @@ public class PruneUnreferencedOutputs @Override public PlanNode visitGroupId(GroupIdNode node, RewriteContext<Set<Symbol>> context) { - checkState(node.getDistinctGroupingColumns().stream().allMatch(column -> context.get().contains(column))); + ImmutableSet.Builder<Symbol> expectedInputs = ImmutableSet.builder(); - ImmutableMap.Builder<Symbol, Symbol> identityMappingBuilder = ImmutableMap.builder(); - for (Map.Entry<Symbol, Symbol> entry : node.getIdentityMappings().entrySet()) { - if (context.get().contains(entry.getValue())) { - identityMappingBuilder.put(entry); - } - } + Map<Symbol, Symbol> newArgumentMappings = node.getArgumentMappings().entrySet().stream() + .filter(entry -> context.get().contains(entry.getKey())) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + expectedInputs.addAll(newArgumentMappings.values()); + + ImmutableList.Builder<List<Symbol>> newGroupingSets = ImmutableList.builder(); + Map<Symbol, Symbol> newGroupingMapping = new HashMap<>(); - Map<Symbol, Symbol> identityMapping = identityMappingBuilder.build(); + for (List<Symbol> groupingSet : node.getGroupingSets()) { + ImmutableList.Builder<Symbol> newGroupingSet = ImmutableList.builder(); - PlanNode source = context.rewrite(node.getSource(), ImmutableSet.<Symbol>builder() - .addAll(identityMapping.keySet()) - .addAll(node.getDistinctGroupingColumns()) - .build()); + for (Symbol output : groupingSet) { + if (context.get().contains(output)) { + newGroupingSet.add(output); + newGroupingMapping.putIfAbsent(output, node.getGroupingSetMappings().get(output)); + expectedInputs.add(node.getGroupingSetMappings().get(output)); + } + } + newGroupingSets.add(newGroupingSet.build()); + } - return new GroupIdNode(node.getId(), source, node.getGroupingSets(), identityMapping, node.getGroupIdSymbol()); + PlanNode source = context.rewrite(node.getSource(), expectedInputs.build()); + return new GroupIdNode(node.getId(), source, newGroupingSets.build(), newGroupingMapping, newArgumentMappings, node.getGroupIdSymbol()); } @Override diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/StreamPropertyDerivations.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/StreamPropertyDerivations.java index 62c639e66f..c0977978f1 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/StreamPropertyDerivations.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/StreamPropertyDerivations.java @@ -307,23 +307,22 @@ final class StreamPropertyDerivations @Override public StreamProperties visitGroupId(GroupIdNode node, List<StreamProperties> inputProperties) { - return Iterables.getOnlyElement(inputProperties).translate(translateGroupIdSymbols(node)); - } - - private Function<Symbol, Optional<Symbol>> translateGroupIdSymbols(GroupIdNode node) - { - List<Symbol> commonGroupingColumns = node.getCommonGroupingColumns(); - return symbol -> { - if (node.getIdentityMappings().containsKey(symbol)) { - return Optional.of(node.getIdentityMappings().get(symbol)); + Map<Symbol, Symbol> inputToOutputMappings = new HashMap<>(); + for (Map.Entry<Symbol, Symbol> setMapping : node.getGroupingSetMappings().entrySet()) { + if (node.getCommonGroupingColumns().contains(setMapping.getKey())) { + // TODO: Add support for translating a property on a single column to multiple columns + // when GroupIdNode is copying a single input grouping column into multiple output grouping columns (i.e. aliases), this is basically picking one arbitrarily + inputToOutputMappings.putIfAbsent(setMapping.getValue(), setMapping.getKey()); } + } - if (commonGroupingColumns.contains(symbol)) { - return Optional.of(symbol); - } + // TODO: Add support for translating a property on a single column to multiple columns + // this is deliberately placed after the grouping columns, because preserving properties has a bigger perf impact + for (Map.Entry<Symbol, Symbol> argumentMapping : node.getArgumentMappings().entrySet()) { + inputToOutputMappings.putIfAbsent(argumentMapping.getValue(), argumentMapping.getKey()); + } - return Optional.empty(); - }; + return Iterables.getOnlyElement(inputProperties).translate(column -> Optional.ofNullable(inputToOutputMappings.get(column))); } @Override diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/UnaliasSymbolReferences.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/UnaliasSymbolReferences.java index 3761439cae..153bd13229 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/UnaliasSymbolReferences.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/UnaliasSymbolReferences.java @@ -81,7 +81,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; -import java.util.stream.Collectors; import static com.facebook.presto.util.ImmutableCollectors.toImmutableList; import static com.facebook.presto.util.ImmutableCollectors.toImmutableSet; @@ -157,16 +156,31 @@ public class UnaliasSymbolReferences public PlanNode visitGroupId(GroupIdNode node, RewriteContext<Void> context) { PlanNode source = context.rewrite(node.getSource()); - List<List<Symbol>> groupingSetsSymbols = node.getGroupingSets().stream() - .map(this::canonicalize) - .collect(Collectors.toList()); - ImmutableMap.Builder<Symbol, Symbol> newPassthroughMap = ImmutableMap.builder(); - for (Symbol inputSymbol : node.getIdentityMappings().keySet()) { - newPassthroughMap.put(canonicalize(inputSymbol), canonicalize(node.getIdentityMappings().get(inputSymbol))); + Map<Symbol, Symbol> newGroupingMappings = new HashMap<>(); + ImmutableList.Builder<List<Symbol>> newGroupingSets = ImmutableList.builder(); + + for (List<Symbol> groupingSet : node.getGroupingSets()) { + ImmutableList.Builder<Symbol> newGroupingSet = ImmutableList.builder(); + for (Symbol output : groupingSet) { + newGroupingMappings.putIfAbsent(canonicalize(output), canonicalize(node.getGroupingSetMappings().get(output))); + newGroupingSet.add(canonicalize(output)); + } + newGroupingSets.add(newGroupingSet.build()); + } + + Map<Symbol, Symbol> newArgumentMappings = new HashMap<>(); + for (Symbol output : node.getArgumentMappings().keySet()) { + Symbol canonicalOutput = canonicalize(output); + if (newArgumentMappings.containsKey(canonicalOutput)) { + map(output, canonicalOutput); + } + else { + newArgumentMappings.put(canonicalOutput, canonicalize(node.getArgumentMappings().get(output))); + } } - return new GroupIdNode(node.getId(), source, groupingSetsSymbols, newPassthroughMap.build(), canonicalize(node.getGroupIdSymbol())); + return new GroupIdNode(node.getId(), source, newGroupingSets.build(), newGroupingMappings, newArgumentMappings, canonicalize(node.getGroupIdSymbol())); } @Override diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/plan/ChildReplacer.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/plan/ChildReplacer.java index 41f8c140f5..a760186471 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/plan/ChildReplacer.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/plan/ChildReplacer.java @@ -169,7 +169,7 @@ public class ChildReplacer @Override public PlanNode visitGroupId(GroupIdNode node, List<PlanNode> newChildren) { - return new GroupIdNode(node.getId(), Iterables.getOnlyElement(newChildren), node.getGroupingSets(), node.getIdentityMappings(), node.getGroupIdSymbol()); + return new GroupIdNode(node.getId(), Iterables.getOnlyElement(newChildren), node.getGroupingSets(), node.getGroupingSetMappings(), node.getArgumentMappings(), node.getGroupIdSymbol()); } @Override diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/plan/GroupIdNode.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/plan/GroupIdNode.java index daf3560ced..1dc5bb48d4 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/plan/GroupIdNode.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/plan/GroupIdNode.java @@ -19,6 +19,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Sets; import javax.annotation.concurrent.Immutable; @@ -27,39 +28,53 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Collectors; +import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; -import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toSet; @Immutable public class GroupIdNode extends PlanNode { private final PlanNode source; + + // in terms of output symbols private final List<List<Symbol>> groupingSets; - private final Map<Symbol, Symbol> identityMappings; + + // from output to input symbols + private final Map<Symbol, Symbol> groupingSetMappings; + private final Map<Symbol, Symbol> argumentMappings; + private final Symbol groupIdSymbol; @JsonCreator public GroupIdNode(@JsonProperty("id") PlanNodeId id, @JsonProperty("source") PlanNode source, @JsonProperty("groupingSets") List<List<Symbol>> groupingSets, - @JsonProperty("identityMappings") Map<Symbol, Symbol> identityMappings, + @JsonProperty("groupingSetMappings") Map<Symbol, Symbol> groupingSetMappings, + @JsonProperty("argumentMappings") Map<Symbol, Symbol> argumentMappings, @JsonProperty("groupIdSymbol") Symbol groupIdSymbol) { super(id); this.source = requireNonNull(source); this.groupingSets = ImmutableList.copyOf(requireNonNull(groupingSets)); - this.identityMappings = ImmutableMap.copyOf(requireNonNull(identityMappings)); + this.groupingSetMappings = ImmutableMap.copyOf(requireNonNull(groupingSetMappings)); + this.argumentMappings = ImmutableMap.copyOf(requireNonNull(argumentMappings)); this.groupIdSymbol = requireNonNull(groupIdSymbol); + + checkArgument(Sets.intersection(groupingSetMappings.keySet(), argumentMappings.keySet()).isEmpty(), "argument outputs and grouping outputs must be a disjoint set"); } @Override public List<Symbol> getOutputSymbols() { return ImmutableList.<Symbol>builder() - .addAll(getDistinctGroupingColumns()) - .addAll(identityMappings.values()) + .addAll(groupingSets.stream() + .flatMap(Collection::stream) + .collect(toSet())) + .addAll(argumentMappings.keySet()) .add(groupIdSymbol) .build(); } @@ -76,14 +91,6 @@ public class GroupIdNode return source; } - public Set<Symbol> getInputSymbols() - { - return ImmutableSet.<Symbol>builder() - .addAll(identityMappings.keySet()) - .addAll(getDistinctGroupingColumns()) - .build(); - } - @JsonProperty public List<List<Symbol>> getGroupingSets() { @@ -91,26 +98,15 @@ public class GroupIdNode } @JsonProperty - public Map<Symbol, Symbol> getIdentityMappings() + public Map<Symbol, Symbol> getGroupingSetMappings() { - return identityMappings; + return groupingSetMappings; } - public List<Symbol> getDistinctGroupingColumns() + @JsonProperty + public Map<Symbol, Symbol> getArgumentMappings() { - return groupingSets.stream() - .flatMap(Collection::stream) - .distinct() - .collect(toList()); - } - - public List<Symbol> getCommonGroupingColumns() - { - Set<Symbol> intersection = new HashSet<>(groupingSets.get(0)); - for (int i = 1; i < getGroupingSets().size(); i++) { - intersection.retainAll(groupingSets.get(i)); - } - return ImmutableList.copyOf(intersection); + return argumentMappings; } @JsonProperty @@ -124,4 +120,26 @@ public class GroupIdNode { return visitor.visitGroupId(this, context); } + + public Set<Symbol> getInputSymbols() + { + return ImmutableSet.<Symbol>builder() + .addAll(argumentMappings.values()) + .addAll(groupingSets.stream() + .map(set -> set.stream() + .map(groupingSetMappings::get).collect(Collectors.toList())) + .flatMap(Collection::stream) + .collect(toSet())) + .build(); + } + + // returns the common grouping columns in terms of output symbols + public Set<Symbol> getCommonGroupingColumns() + { + Set<Symbol> intersection = new HashSet<>(groupingSets.get(0)); + for (int i = 1; i < groupingSets.size(); i++) { + intersection.retainAll(groupingSets.get(i)); + } + return ImmutableSet.copyOf(intersection); + } } diff --git a/presto-main/src/main/java/com/facebook/presto/util/GraphvizPrinter.java b/presto-main/src/main/java/com/facebook/presto/util/GraphvizPrinter.java index eb7703171e..c5b7677248 100644 --- a/presto-main/src/main/java/com/facebook/presto/util/GraphvizPrinter.java +++ b/presto-main/src/main/java/com/facebook/presto/util/GraphvizPrinter.java @@ -332,11 +332,14 @@ public final class GraphvizPrinter @Override public Void visitGroupId(GroupIdNode node, Void context) { - List<String> groupingSets = node.getGroupingSets().stream() - .map(groupingSet -> "(" + Joiner.on(", ").join(groupingSet) + ")") + // grouping sets are easier to understand in terms of inputs + List<String> inputGroupingSetSymbols = node.getGroupingSets().stream() + .map(set -> "(" + Joiner.on(", ").join(set.stream() + .map(symbol -> node.getGroupingSetMappings().get(symbol)) + .collect(Collectors.toList())) + ")") .collect(Collectors.toList()); - printNode(node, "GroupId", Joiner.on(", ").join(groupingSets), NODE_COLORS.get(NodeType.AGGREGATE)); + printNode(node, "GroupId", Joiner.on(", ").join(inputGroupingSetSymbols), NODE_COLORS.get(NodeType.AGGREGATE)); return node.getSource().accept(this, context); } diff --git a/presto-main/src/test/java/com/facebook/presto/operator/TestGroupIdOperator.java b/presto-main/src/test/java/com/facebook/presto/operator/TestGroupIdOperator.java index e366afa8bc..53efa7593c 100644 --- a/presto-main/src/test/java/com/facebook/presto/operator/TestGroupIdOperator.java +++ b/presto-main/src/test/java/com/facebook/presto/operator/TestGroupIdOperator.java @@ -19,6 +19,7 @@ import com.facebook.presto.spi.Page; import com.facebook.presto.sql.planner.plan.PlanNodeId; import com.facebook.presto.testing.MaterializedResult; import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @@ -72,9 +73,7 @@ public class TestGroupIdOperator new GroupIdOperatorFactory(0, new PlanNodeId("test"), ImmutableList.of(VARCHAR, BOOLEAN, BIGINT, BIGINT, BIGINT), - ImmutableList.of(ImmutableList.of(1, 2), ImmutableList.of(3)), - ImmutableList.of(1, 2, 3), - ImmutableList.of(0)); + ImmutableList.of(ImmutableMap.of(0, 1, 1, 2, 3, 0), ImmutableMap.of(2, 3, 3, 0))); MaterializedResult expected = resultBuilder(driverContext.getSession(), VARCHAR, BOOLEAN, BIGINT, BIGINT, BIGINT) .row("400", true, null, 100L, 0L) diff --git a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java index bfbd609fb5..adbff45529 100644 --- a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java +++ b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java @@ -1516,6 +1516,19 @@ public abstract class AbstractTestQueries "SELECT SUM(CAST(quantity AS BIGINT)) FROM lineitem WHERE quantity < 0"); } + @Test + public void testGroupingSetsAliasedGroupingColumns() + throws Exception + { + assertQuery("SELECT lna, lnb, SUM(quantity) " + + "FROM (SELECT linenumber lna, linenumber lnb, CAST(quantity AS BIGINT) quantity FROM lineitem) " + + "GROUP BY GROUPING SETS ((lna, lnb), (lna), (lnb), ())", + "SELECT linenumber, linenumber, SUM(CAST(quantity AS BIGINT)) FROM lineitem GROUP BY linenumber UNION ALL " + + "SELECT linenumber, NULL, SUM(CAST(quantity AS BIGINT)) FROM lineitem GROUP BY linenumber UNION ALL " + + "SELECT NULL, linenumber, SUM(CAST(quantity AS BIGINT)) FROM lineitem GROUP BY linenumber UNION ALL " + + "SELECT NULL, NULL, SUM(CAST(quantity AS BIGINT)) FROM lineitem"); + } + @Test public void testGroupingSetMixedExpressionAndColumn() throws Exception
['presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/StreamPropertyDerivations.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/plan/ChildReplacer.java', 'presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java', 'presto-main/src/main/java/com/facebook/presto/util/GraphvizPrinter.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/LocalExecutionPlanner.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PropertyDerivations.java', 'presto-main/src/test/java/com/facebook/presto/operator/TestGroupIdOperator.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/QueryPlanner.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/SymbolExtractor.java', 'presto-main/src/main/java/com/facebook/presto/operator/GroupIdOperator.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PruneUnreferencedOutputs.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/AddExchanges.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PredicatePushDown.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/plan/GroupIdNode.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/PlanPrinter.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/UnaliasSymbolReferences.java']
{'.java': 16}
16
16
0
0
16
13,206,161
2,625,166
367,003
2,655
33,178
6,037
506
14
375
80
171
35
0
3
1970-01-01T00:24:37
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
186
prestodb/presto/6571/6554
prestodb
presto
https://github.com/prestodb/presto/issues/6554
https://github.com/prestodb/presto/pull/6571
https://github.com/prestodb/presto/pull/6571
1
fixes
Invalid plan for query involving an aggregation subquery joined to a partitioned table
Given this hive table: ```sql CREATE TABLE t (a bigint, ds varchar) WITH (partitioned_by = array['ds']) ``` The following query fails with an exception during planning: ```sql SELECT * FROM ( SELECT count(*) FROM tpch.tiny.orders HAVING count(DISTINCT custkey) > 1 ) CROSS JOIN t ``` ``` java.lang.IllegalArgumentException: Output layout ([count_20]) don't include all partition columns ([custkey]) at com.google.common.base.Preconditions.checkArgument(Preconditions.java:145) at com.facebook.presto.sql.planner.PartitioningScheme.<init>(PartitioningScheme.java:70) at com.facebook.presto.sql.planner.PartitioningScheme.<init>(PartitioningScheme.java:50) at com.facebook.presto.sql.planner.optimizations.PartialAggregationPushDown$Rewriter.visitExchange(PartialAggregationPushDown.java:165) at com.facebook.presto.sql.planner.optimizations.PartialAggregationPushDown$Rewriter.visitExchange(PartialAggregationPushDown.java:69) at com.facebook.presto.sql.planner.plan.ExchangeNode.accept(ExchangeNode.java:208) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.rewrite(SimplePlanRewriter.java:85) at com.facebook.presto.sql.planner.optimizations.PartialAggregationPushDown$Rewriter.visitExchange(PartialAggregationPushDown.java:155) at com.facebook.presto.sql.planner.optimizations.PartialAggregationPushDown$Rewriter.visitExchange(PartialAggregationPushDown.java:69) at com.facebook.presto.sql.planner.plan.ExchangeNode.accept(ExchangeNode.java:208) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.rewrite(SimplePlanRewriter.java:85) at com.facebook.presto.sql.planner.optimizations.PartialAggregationPushDown$Rewriter.visitAggregation(PartialAggregationPushDown.java:126) at com.facebook.presto.sql.planner.optimizations.PartialAggregationPushDown$Rewriter.visitAggregation(PartialAggregationPushDown.java:69) at com.facebook.presto.sql.planner.plan.AggregationNode.accept(AggregationNode.java:185) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.rewrite(SimplePlanRewriter.java:85) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.lambda$defaultRewrite$0(SimplePlanRewriter.java:74) at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) at java.util.Iterator.forEachRemaining(Iterator.java:116) at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.defaultRewrite(SimplePlanRewriter.java:75) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.defaultRewrite(SimplePlanRewriter.java:64) at com.facebook.presto.sql.planner.optimizations.PartialAggregationPushDown$Rewriter.visitExchange(PartialAggregationPushDown.java:141) at com.facebook.presto.sql.planner.optimizations.PartialAggregationPushDown$Rewriter.visitExchange(PartialAggregationPushDown.java:69) at com.facebook.presto.sql.planner.plan.ExchangeNode.accept(ExchangeNode.java:208) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.rewrite(SimplePlanRewriter.java:85) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.lambda$defaultRewrite$0(SimplePlanRewriter.java:74) at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) at java.util.Iterator.forEachRemaining(Iterator.java:116) at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.defaultRewrite(SimplePlanRewriter.java:75) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter.visitPlan(SimplePlanRewriter.java:39) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter.visitPlan(SimplePlanRewriter.java:23) at com.facebook.presto.sql.planner.plan.PlanVisitor.visitFilter(PlanVisitor.java:35) at com.facebook.presto.sql.planner.plan.FilterNode.accept(FilterNode.java:71) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.rewrite(SimplePlanRewriter.java:85) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.lambda$defaultRewrite$0(SimplePlanRewriter.java:74) at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) at java.util.Iterator.forEachRemaining(Iterator.java:116) at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.defaultRewrite(SimplePlanRewriter.java:75) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter.visitPlan(SimplePlanRewriter.java:39) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter.visitPlan(SimplePlanRewriter.java:23) at com.facebook.presto.sql.planner.plan.PlanVisitor.visitJoin(PlanVisitor.java:90) at com.facebook.presto.sql.planner.plan.JoinNode.accept(JoinNode.java:170) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.rewrite(SimplePlanRewriter.java:85) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.lambda$defaultRewrite$0(SimplePlanRewriter.java:74) at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) at java.util.Iterator.forEachRemaining(Iterator.java:116) at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.defaultRewrite(SimplePlanRewriter.java:75) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter.visitPlan(SimplePlanRewriter.java:39) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter.visitPlan(SimplePlanRewriter.java:23) at com.facebook.presto.sql.planner.plan.PlanVisitor.visitOutput(PlanVisitor.java:50) at com.facebook.presto.sql.planner.plan.OutputNode.accept(OutputNode.java:81) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter.rewriteWith(SimplePlanRewriter.java:33) at com.facebook.presto.sql.planner.optimizations.PartialAggregationPushDown.optimize(PartialAggregationPushDown.java:66) at com.facebook.presto.sql.planner.LogicalPlanner.plan(LogicalPlanner.java:118) at com.facebook.presto.sql.planner.LogicalPlanner.plan(LogicalPlanner.java:109) at com.facebook.presto.execution.SqlQueryExecution.doAnalyzeQuery(SqlQueryExecution.java:288) at com.facebook.presto.execution.SqlQueryExecution.analyzeQuery(SqlQueryExecution.java:267) at com.facebook.presto.execution.SqlQueryExecution.start(SqlQueryExecution.java:225) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) ```
3e33358e1348b5c9ccd9b2ff26a01762072f7bfb
468a314ae91bd255de04a5e80e81e66670afb355
https://github.com/prestodb/presto/compare/3e33358e1348b5c9ccd9b2ff26a01762072f7bfb...468a314ae91bd255de04a5e80e81e66670afb355
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/PlanOptimizers.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/PlanOptimizers.java index 4f2d90fae8..38a9ee4633 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/PlanOptimizers.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/PlanOptimizers.java @@ -132,7 +132,8 @@ public class PlanOptimizers // Optimizers above this do not need to care about aggregations with the type other than SINGLE // This optimizer must be run after all exchange-related optimizers - builder.add(new PartialAggregationPushDown(metadata)); + builder.add(new PartialAggregationPushDown(metadata.getFunctionRegistry())); + builder.add(new PruneIdentityProjections()); // DO NOT add optimizers that change the plan shape (computations) after this point diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PartialAggregationPushDown.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PartialAggregationPushDown.java index 582843ce79..740a83e69e 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PartialAggregationPushDown.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PartialAggregationPushDown.java @@ -15,10 +15,10 @@ package com.facebook.presto.sql.planner.optimizations; import com.facebook.presto.Session; import com.facebook.presto.metadata.FunctionRegistry; -import com.facebook.presto.metadata.Metadata; import com.facebook.presto.metadata.Signature; import com.facebook.presto.operator.aggregation.InternalAggregationFunction; import com.facebook.presto.spi.type.Type; +import com.facebook.presto.sql.planner.Partitioning; import com.facebook.presto.sql.planner.PartitioningScheme; import com.facebook.presto.sql.planner.PlanNodeIdAllocator; import com.facebook.presto.sql.planner.Symbol; @@ -26,38 +26,38 @@ import com.facebook.presto.sql.planner.SymbolAllocator; import com.facebook.presto.sql.planner.plan.AggregationNode; import com.facebook.presto.sql.planner.plan.ExchangeNode; import com.facebook.presto.sql.planner.plan.PlanNode; +import com.facebook.presto.sql.planner.plan.ProjectNode; import com.facebook.presto.sql.planner.plan.SimplePlanRewriter; import com.facebook.presto.sql.tree.Expression; import com.facebook.presto.sql.tree.FunctionCall; import com.facebook.presto.sql.tree.QualifiedName; -import com.facebook.presto.sql.tree.SymbolReference; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Optional; +import java.util.stream.Collectors; import static com.facebook.presto.sql.planner.plan.AggregationNode.Step.FINAL; import static com.facebook.presto.sql.planner.plan.AggregationNode.Step.PARTIAL; -import static com.facebook.presto.sql.planner.plan.AggregationNode.Step.SINGLE; -import static com.facebook.presto.sql.planner.plan.ExchangeNode.Type.REPLICATE; -import static com.google.common.base.Preconditions.checkState; +import static com.facebook.presto.sql.planner.plan.ExchangeNode.Type.GATHER; +import static com.facebook.presto.sql.planner.plan.ExchangeNode.Type.REPARTITION; +import static com.google.common.base.Verify.verify; import static java.util.Objects.requireNonNull; -import static java.util.stream.Collectors.toList; public class PartialAggregationPushDown implements PlanOptimizer { private final FunctionRegistry functionRegistry; - public PartialAggregationPushDown(Metadata metadata) + public PartialAggregationPushDown(FunctionRegistry registry) { - requireNonNull(metadata, "metadata is null"); + requireNonNull(registry, "registry is null"); - this.functionRegistry = metadata.getFunctionRegistry(); + this.functionRegistry = registry; } @Override @@ -67,7 +67,7 @@ public class PartialAggregationPushDown } private class Rewriter - extends SimplePlanRewriter<AggregationNode> + extends SimplePlanRewriter<Void> { private final SymbolAllocator allocator; private final PlanNodeIdAllocator idAllocator; @@ -79,17 +79,125 @@ public class PartialAggregationPushDown } @Override - public PlanNode visitAggregation(AggregationNode node, RewriteContext<AggregationNode> context) + public PlanNode visitAggregation(AggregationNode node, RewriteContext<Void> context) { + PlanNode child = node.getSource(); + + if (!(child instanceof ExchangeNode)) { + return context.defaultRewrite(node); + } + + // partial aggregation can only be pushed through exchange that doesn't change + // the cardinality of the stream (i.e., gather or repartition) + ExchangeNode exchange = (ExchangeNode) child; + if ((exchange.getType() != GATHER && exchange.getType() != REPARTITION) || + exchange.getPartitioningScheme().isReplicateNulls()) { + return context.defaultRewrite(node); + } + + if (exchange.getType() == REPARTITION) { + // if partitioning columns are not a subset of grouping keys, + // we can't push this through + List<Symbol> partitioningColumns = exchange.getPartitioningScheme() + .getPartitioning() + .getArguments() + .stream() + .filter(Partitioning.ArgumentBinding::isVariable) + .map(Partitioning.ArgumentBinding::getColumn) + .collect(Collectors.toList()); + + if (!node.getGroupingKeys().containsAll(partitioningColumns)) { + return context.defaultRewrite(node); + } + } + + // currently, we only support plans that don't use pre-computed hash functions + if (node.getHashSymbol().isPresent() || exchange.getPartitioningScheme().getHashColumn().isPresent()) { + return context.defaultRewrite(node); + } + boolean decomposable = node.getFunctions().values().stream() .map(functionRegistry::getAggregateFunctionImplementation) .allMatch(InternalAggregationFunction::isDecomposable); - checkState(node.getStep() == SINGLE, "aggregation should be SINGLE, but it is %s", node.getStep()); - checkState(context.get() == null, "context is not null: %s", context); - if (!decomposable || !allowPushThrough(node.getSource())) { + + if (!decomposable) { return context.defaultRewrite(node); } + switch (node.getStep()) { + case SINGLE: + // Split it into a FINAL on top of a PARTIAL and + // reprocess the resulting plan to push the partial + // below the exchange (see case below). + return context.rewrite(split(node)); + case PARTIAL: + // Push it underneath each branch of the exchange + // and reprocess in case it can be pushed further down + // (e.g., if there are local/remote exchanges stacked) + return context.rewrite(pushPartial(node, exchange)); + default: + return context.defaultRewrite(node); + } + } + + private PlanNode pushPartial(AggregationNode partial, ExchangeNode exchange) + { + List<PlanNode> partials = new ArrayList<>(); + for (int i = 0; i < exchange.getSources().size(); i++) { + PlanNode source = exchange.getSources().get(i); + + if (!exchange.getOutputSymbols().equals(exchange.getInputs().get(i))) { + // Add an identity projection to preserve the inputs to the aggregation, if necessary. + // This allows us to avoid having to rewrite the symbols in the aggregation node below. + ImmutableMap.Builder<Symbol, Expression> assignments = ImmutableMap.builder(); + for (int outputIndex = 0; outputIndex < exchange.getOutputSymbols().size(); outputIndex++) { + Symbol output = exchange.getOutputSymbols().get(outputIndex); + Symbol input = exchange.getInputs().get(i).get(outputIndex); + assignments.put(output, input.toSymbolReference()); + } + + source = new ProjectNode(idAllocator.getNextId(), source, assignments.build()); + } + + // Since this exchange source is now guaranteed to have the same symbols as the inputs to the the partial + // aggregation, we can build a new AggregationNode without any further symbol rewrites + partials.add(new AggregationNode( + idAllocator.getNextId(), + source, + partial.getAggregations(), + partial.getFunctions(), + partial.getMasks(), + partial.getGroupingSets(), + partial.getStep(), + partial.getHashSymbol(), + partial.getGroupIdSymbol())); + } + + for (PlanNode node : partials) { + verify(partial.getOutputSymbols().equals(node.getOutputSymbols())); + } + + // Since this exchange source is now guaranteed to have the same symbols as the inputs to the the partial + // aggregation, we don't need to rewrite symbols in the partitioning function + PartitioningScheme partitioning = new PartitioningScheme( + exchange.getPartitioningScheme().getPartitioning(), + partial.getOutputSymbols(), + exchange.getPartitioningScheme().getHashColumn(), + exchange.getPartitioningScheme().isReplicateNulls(), + exchange.getPartitioningScheme().getBucketToPartition()); + + return new ExchangeNode( + idAllocator.getNextId(), + exchange.getType(), + exchange.getScope(), + partitioning, + partials, + ImmutableList.copyOf(Collections.nCopies(partials.size(), partial.getOutputSymbols()))); + } + + private PlanNode split(AggregationNode node) + { + // otherwise, add a partial and final with an exchange in between Map<Symbol, Symbol> masks = node.getMasks(); Map<Symbol, FunctionCall> finalCalls = new HashMap<>(); @@ -98,8 +206,9 @@ public class PartialAggregationPushDown Map<Symbol, Symbol> intermediateMask = new HashMap<>(); for (Map.Entry<Symbol, FunctionCall> entry : node.getAggregations().entrySet()) { Signature signature = node.getFunctions().get(entry.getKey()); + InternalAggregationFunction function = functionRegistry.getAggregateFunctionImplementation(signature); - Symbol intermediateSymbol = generateIntermediateSymbol(signature); + Symbol intermediateSymbol = allocator.newSymbol(signature.getName(), function.getIntermediateType()); intermediateCalls.put(intermediateSymbol, entry.getValue()); intermediateFunctions.put(intermediateSymbol, signature); if (masks.containsKey(entry.getKey())) { @@ -110,7 +219,7 @@ public class PartialAggregationPushDown finalCalls.put(entry.getKey(), new FunctionCall(QualifiedName.of(signature.getName()), ImmutableList.of(intermediateSymbol.toSymbolReference()))); } - AggregationNode partial = new AggregationNode( + PlanNode partial = new AggregationNode( idAllocator.getNextId(), node.getSource(), intermediateCalls, @@ -123,7 +232,7 @@ public class PartialAggregationPushDown return new AggregationNode( node.getId(), - context.rewrite(node.getSource(), partial), + partial, finalCalls, node.getFunctions(), ImmutableMap.of(), @@ -132,181 +241,5 @@ public class PartialAggregationPushDown node.getHashSymbol(), node.getGroupIdSymbol()); } - - @Override - public PlanNode visitExchange(ExchangeNode node, RewriteContext<AggregationNode> context) - { - AggregationNode partial = context.get(); - if (partial == null) { - return context.defaultRewrite(node); - } - - List<PlanNode> newChildren = new ArrayList<>(); - List<List<Symbol>> inputs = new ArrayList<>(); - - boolean allowPushThroughChildren = node.getSources().stream().allMatch(this::allowPushThrough); - for (int i = 0; i < node.getSources().size(); i++) { - PlanNode currentSource = node.getSources().get(i); - Map<Symbol, Symbol> exchangeMap = buildExchangeMap(node.getOutputSymbols(), node.getInputs().get(i)); - AggregationWithLayout childPartial = generateNewPartial(partial, currentSource, exchangeMap); - inputs.add(childPartial.getLayout()); - PlanNode child; - if (allowPushThroughChildren) { - child = context.rewrite(currentSource, childPartial.getAggregationNode()); - } - else { - child = context.defaultRewrite(childPartial.getAggregationNode()); - } - newChildren.add(child); - } - PartitioningScheme partitioningScheme = new PartitioningScheme( - node.getPartitioningScheme().getPartitioning(), - partial.getOutputSymbols(), - partial.getHashSymbol()); - return new ExchangeNode( - node.getId(), - node.getType(), - node.getScope(), - partitioningScheme, - newChildren, - inputs); - } - - private boolean allowPushThrough(PlanNode node) - { - if (node instanceof ExchangeNode) { - ExchangeNode exchangeNode = (ExchangeNode) node; - return exchangeNode.getType() != REPLICATE && !exchangeNode.getPartitioningScheme().isReplicateNulls(); - } - return false; - } - - private Symbol generateIntermediateSymbol(Signature signature) - { - InternalAggregationFunction function = functionRegistry.getAggregateFunctionImplementation(signature); - return allocator.newSymbol(signature.getName(), function.getIntermediateType()); - } - - private Map<Symbol, Symbol> buildExchangeMap(List<Symbol> exchangeOutput, List<Symbol> sourceOutput) - { - checkState(exchangeOutput.size() == sourceOutput.size(), "exchange output length doesn't match source output length"); - Map<Symbol, Symbol> assignments = new HashMap<>(); - for (int i = 0; i < exchangeOutput.size(); i++) { - Symbol output = exchangeOutput.get(i); - Symbol input = sourceOutput.get(i); - if (!assignments.containsKey(output)) { - assignments.put(output, input); - } - else { - checkState(assignments.get(output).equals(input), - "Different input symbols (%s vs %s) for same output symbol (%s)", - input, - assignments.get(output), - output); - } - } - - return ImmutableMap.copyOf(assignments); - } - - private List<Expression> replaceArguments(List<Expression> arguments, Map<Symbol, Symbol> exchangeMap) - { - Map<SymbolReference, SymbolReference> symbolReferenceSymbolMap = new HashMap<>(); - for (Map.Entry<Symbol, Symbol> entry : exchangeMap.entrySet()) { - symbolReferenceSymbolMap.put(entry.getKey().toSymbolReference(), entry.getValue().toSymbolReference()); - } - return arguments.stream() - .map(expression -> { - if (symbolReferenceSymbolMap.containsKey(expression)) { - return symbolReferenceSymbolMap.get(expression); - } - return expression; - }) - .collect(toList()); - } - - // generate new partial aggregation for each exchange branch with renamed symbols - private AggregationWithLayout generateNewPartial(AggregationNode node, PlanNode source, Map<Symbol, Symbol> exchangeMap) - { - checkState(!node.getHashSymbol().isPresent(), "PartialAggregationPushDown optimizer must run before HashGenerationOptimizer"); - - // Store the symbol mapping from old aggregation output to new aggregation output - Map<Symbol, Symbol> layoutMap = new HashMap<>(); - - Map<Symbol, FunctionCall> functionCallMap = new HashMap<>(); - Map<Symbol, Signature> signatureMap = new HashMap<>(); - Map<Symbol, Symbol> mask = new HashMap<>(); - for (Map.Entry<Symbol, FunctionCall> entry : node.getAggregations().entrySet()) { - Signature signature = node.getFunctions().get(entry.getKey()); - Symbol symbol = generateIntermediateSymbol(signature); - - signatureMap.put(symbol, node.getFunctions().get(entry.getKey())); - - List<Expression> arguments = replaceArguments(entry.getValue().getArguments(), exchangeMap); - functionCallMap.put(symbol, new FunctionCall(entry.getValue().getName(), Optional.empty(), entry.getValue().getFilter(), false, arguments)); - if (node.getMasks().containsKey(entry.getKey())) { - mask.put(symbol, exchangeMap.get(node.getMasks().get(entry.getKey()))); - } - - layoutMap.put(entry.getKey(), symbol); - } - - // put group by keys in map - for (Symbol groupBySymbol : node.getGroupingKeys()) { - Symbol newGroupBySymbol = exchangeMap.get(groupBySymbol); - layoutMap.put(groupBySymbol, newGroupBySymbol); - } - - // translate grouping sets - ImmutableList.Builder<List<Symbol>> groupingSets = ImmutableList.builder(); - for (List<Symbol> symbols : node.getGroupingSets()) { - ImmutableList.Builder<Symbol> symbolList = ImmutableList.builder(); - for (Symbol symbol : symbols) { - Symbol translated = exchangeMap.get(symbol); - symbolList.add(translated); - } - groupingSets.add(symbolList.build()); - } - - AggregationNode partial = new AggregationNode( - idAllocator.getNextId(), - source, - functionCallMap, - signatureMap, - mask, - groupingSets.build(), - PARTIAL, - node.getHashSymbol(), - node.getGroupIdSymbol().map(exchangeMap::get)); - - // generate the output layout according to the order of pre-pushed aggregation's output - List<Symbol> layout = node.getOutputSymbols().stream() - .map(layoutMap::get) - .collect(toList()); - - return new AggregationWithLayout(partial, layout); - } - } - - private static class AggregationWithLayout - { - private final AggregationNode aggregationNode; - private final List<Symbol> layout; - - public AggregationWithLayout(AggregationNode aggregationNode, List<Symbol> layout) - { - this.aggregationNode = requireNonNull(aggregationNode, "aggregationNode is null"); - this.layout = ImmutableList.copyOf(requireNonNull(layout, "layout is null")); - } - - public AggregationNode getAggregationNode() - { - return aggregationNode; - } - - public List<Symbol> getLayout() - { - return layout; - } } }
['presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PartialAggregationPushDown.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/PlanOptimizers.java']
{'.java': 2}
2
2
0
0
2
13,354,938
2,653,984
370,733
2,675
16,321
2,795
324
2
8,364
225
1,961
105
0
3
1970-01-01T00:24:38
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
185
prestodb/presto/6802/6801
prestodb
presto
https://github.com/prestodb/presto/issues/6801
https://github.com/prestodb/presto/pull/6802
https://github.com/prestodb/presto/pull/6802
1
fixes
Error executing prepared statement when complex join criteria contains parameter
A query like this: ```sql SELECT * FROM (VALUES 1) t(a) JOIN (VALUES 2) u(a) ON t.a + u.a < ?; ``` Fails to execute with "EXECUTE ... USING ..." with: ``` com.facebook.presto.sql.analyzer.SemanticException: line 1:67: query takes no parameters at com.facebook.presto.sql.analyzer.ExpressionAnalyzer$Visitor.visitParameter(ExpressionAnalyzer.java:896) at com.facebook.presto.sql.analyzer.ExpressionAnalyzer$Visitor.visitParameter(ExpressionAnalyzer.java:254) at com.facebook.presto.sql.tree.Parameter.accept(Parameter.java:48) at com.facebook.presto.sql.tree.StackableAstVisitor.process(StackableAstVisitor.java:26) at com.facebook.presto.sql.analyzer.ExpressionAnalyzer$Visitor.process(ExpressionAnalyzer.java:273) at com.facebook.presto.sql.analyzer.ExpressionAnalyzer$Visitor.getOperator(ExpressionAnalyzer.java:1130) at com.facebook.presto.sql.analyzer.ExpressionAnalyzer$Visitor.visitComparisonExpression(ExpressionAnalyzer.java:423) at com.facebook.presto.sql.analyzer.ExpressionAnalyzer$Visitor.visitComparisonExpression(ExpressionAnalyzer.java:254) at com.facebook.presto.sql.tree.ComparisonExpression.accept(ComparisonExpression.java:68) at com.facebook.presto.sql.tree.StackableAstVisitor.process(StackableAstVisitor.java:26) at com.facebook.presto.sql.analyzer.ExpressionAnalyzer$Visitor.process(ExpressionAnalyzer.java:273) at com.facebook.presto.sql.analyzer.ExpressionAnalyzer.analyze(ExpressionAnalyzer.java:230) at com.facebook.presto.sql.analyzer.ExpressionAnalyzer.analyzeExpressions(ExpressionAnalyzer.java:1391) at com.facebook.presto.sql.analyzer.ExpressionAnalyzer.analyzeExpressionsWithSymbols(ExpressionAnalyzer.java:1344) at com.facebook.presto.sql.analyzer.ExpressionAnalyzer.getExpressionTypes(ExpressionAnalyzer.java:1310) at com.facebook.presto.sql.analyzer.ExpressionAnalyzer.getExpressionTypes(ExpressionAnalyzer.java:1298) at com.facebook.presto.sql.analyzer.ExpressionAnalyzer.getExpressionTypes(ExpressionAnalyzer.java:1286) at com.facebook.presto.sql.planner.optimizations.DesugaringOptimizer$Rewriter.desugar(DesugaringOptimizer.java:118) at com.facebook.presto.sql.planner.optimizations.DesugaringOptimizer$Rewriter.visitFilter(DesugaringOptimizer.java:92) at com.facebook.presto.sql.planner.optimizations.DesugaringOptimizer$Rewriter.visitFilter(DesugaringOptimizer.java:64) at com.facebook.presto.sql.planner.plan.FilterNode.accept(FilterNode.java:71) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.rewrite(SimplePlanRewriter.java:85) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.rewrite(SimplePlanRewriter.java:96) at com.facebook.presto.sql.planner.optimizations.DesugaringOptimizer$Rewriter.visitProject(DesugaringOptimizer.java:83) at com.facebook.presto.sql.planner.optimizations.DesugaringOptimizer$Rewriter.visitProject(DesugaringOptimizer.java:64) at com.facebook.presto.sql.planner.plan.ProjectNode.accept(ProjectNode.java:81) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.rewrite(SimplePlanRewriter.java:85) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.rewrite(SimplePlanRewriter.java:96) at com.facebook.presto.sql.planner.optimizations.DesugaringOptimizer$Rewriter.visitProject(DesugaringOptimizer.java:83) at com.facebook.presto.sql.planner.optimizations.DesugaringOptimizer$Rewriter.visitProject(DesugaringOptimizer.java:64) at com.facebook.presto.sql.planner.plan.ProjectNode.accept(ProjectNode.java:81) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.rewrite(SimplePlanRewriter.java:85) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.rewrite(SimplePlanRewriter.java:96) at com.facebook.presto.sql.planner.optimizations.DesugaringOptimizer$Rewriter.visitProject(DesugaringOptimizer.java:83) at com.facebook.presto.sql.planner.optimizations.DesugaringOptimizer$Rewriter.visitProject(DesugaringOptimizer.java:64) at com.facebook.presto.sql.planner.plan.ProjectNode.accept(ProjectNode.java:81) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.rewrite(SimplePlanRewriter.java:85) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.rewrite(SimplePlanRewriter.java:96) at com.facebook.presto.sql.planner.optimizations.DesugaringOptimizer$Rewriter.visitProject(DesugaringOptimizer.java:83) at com.facebook.presto.sql.planner.optimizations.DesugaringOptimizer$Rewriter.visitProject(DesugaringOptimizer.java:64) at com.facebook.presto.sql.planner.plan.ProjectNode.accept(ProjectNode.java:81) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.rewrite(SimplePlanRewriter.java:85) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.lambda$defaultRewrite$0(SimplePlanRewriter.java:74) at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) at java.util.Iterator.forEachRemaining(Iterator.java:116) at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.defaultRewrite(SimplePlanRewriter.java:75) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter.visitPlan(SimplePlanRewriter.java:39) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter.visitPlan(SimplePlanRewriter.java:23) at com.facebook.presto.sql.planner.plan.PlanVisitor.visitOutput(PlanVisitor.java:50) at com.facebook.presto.sql.planner.plan.OutputNode.accept(OutputNode.java:81) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter.rewriteWith(SimplePlanRewriter.java:28) at com.facebook.presto.sql.planner.optimizations.DesugaringOptimizer.optimize(DesugaringOptimizer.java:61) at com.facebook.presto.sql.planner.LogicalPlanner.plan(LogicalPlanner.java:120) at com.facebook.presto.testing.LocalQueryRunner.createPlan(LocalQueryRunner.java:676) at com.facebook.presto.testing.LocalQueryRunner.createPlan(LocalQueryRunner.java:642) at com.facebook.presto.testing.LocalQueryRunner.createPlan(LocalQueryRunner.java:629) at com.facebook.presto.testing.LocalQueryRunner.createDrivers(LocalQueryRunner.java:539) at com.facebook.presto.testing.LocalQueryRunner.executeInternal(LocalQueryRunner.java:500) at com.facebook.presto.testing.LocalQueryRunner.lambda$execute$2(LocalQueryRunner.java:473) at com.facebook.presto.transaction.TransactionBuilder.execute(TransactionBuilder.java:149) at com.facebook.presto.testing.LocalQueryRunner.inTransaction(LocalQueryRunner.java:485) at com.facebook.presto.testing.LocalQueryRunner.execute(LocalQueryRunner.java:473) at com.facebook.presto.tests.AbstractTestQueryFramework.computeActual(AbstractTestQueryFramework.java:88) at com.facebook.presto.tests.TestLocalQueries.testExecuteUsingx(TestLocalQueries.java:46) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85) at org.testng.internal.Invoker.invokeMethod(Invoker.java:696) at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:882) at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1189) at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:124) at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108) at org.testng.TestRunner.privateRun(TestRunner.java:767) at org.testng.TestRunner.run(TestRunner.java:617) at org.testng.SuiteRunner.runTest(SuiteRunner.java:348) at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:343) at org.testng.SuiteRunner.privateRun(SuiteRunner.java:305) at org.testng.SuiteRunner.run(SuiteRunner.java:254) at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224) at org.testng.TestNG.runSuitesLocally(TestNG.java:1149) at org.testng.TestNG.run(TestNG.java:1057) at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72) at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:127) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) ```
8f8fe148afc6cafe752f7bba37ea71edfb913631
42a76b91e4de121d7dfaf072eca4eab0e5ac27c5
https://github.com/prestodb/presto/compare/8f8fe148afc6cafe752f7bba37ea71edfb913631...42a76b91e4de121d7dfaf072eca4eab0e5ac27c5
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/RelationPlanner.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/RelationPlanner.java index cf374dc82b..8c10f859f5 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/RelationPlanner.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/RelationPlanner.java @@ -332,6 +332,7 @@ class RelationPlanner rootPlanBuilder = subqueryPlanner.handleSubqueries(rootPlanBuilder, complexJoinExpressions, node); for (Expression expression : complexJoinExpressions) { + expression = ExpressionTreeRewriter.rewriteWith(new ParameterRewriter(analysis.getParameters(), analysis), expression); postInnerJoinConditions.add(rootPlanBuilder.rewrite(expression)); } root = rootPlanBuilder.getRoot(); diff --git a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java index 16dbf46cd7..d2ff43afab 100644 --- a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java +++ b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java @@ -7478,6 +7478,18 @@ public abstract class AbstractTestQueries "VALUES (2, 4), (3, 8), (4, 4)"); } + @Test + public void testExecuteUsingComplexJoinCriteria() + { + String query = "SELECT * FROM (VALUES 1) t(a) JOIN (VALUES 2) u(a) ON t.a + u.a < ?"; + Session session = Session.builder(getSession()) + .addPreparedStatement("my_query", query) + .build(); + assertQuery(session, + "EXECUTE my_query USING 5", + "VALUES (1, 2)"); + } + @Test public void testExecuteUsingWithSubquery() {
['presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/RelationPlanner.java']
{'.java': 2}
2
2
0
0
2
13,532,506
2,687,805
374,956
2,696
136
23
1
1
9,191
238
2,110
109
0
2
1970-01-01T00:24:41
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
184
prestodb/presto/6877/6875
prestodb
presto
https://github.com/prestodb/presto/issues/6875
https://github.com/prestodb/presto/pull/6877
https://github.com/prestodb/presto/pull/6877
1
fixes
Bad error when aggregation function is used in lambda expression
```sql SELECT transform(ARRAY[1], x -> max(x)) ``` fails with: ``` java.lang.IllegalArgumentException: function must be of type com.facebook.presto.metadata.SqlScalarFunction, not com.facebook.presto.operator.aggregation.MaxAggregationFunction at com.google.common.base.Preconditions.checkArgument(Preconditions.java:145) at com.facebook.presto.util.Types.checkType(Types.java:28) at com.facebook.presto.metadata.FunctionRegistry$2.load(FunctionRegistry.java:348) at com.facebook.presto.metadata.FunctionRegistry$2.load(FunctionRegistry.java:342) at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3527) at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2319) at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2282) at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2197) at com.google.common.cache.LocalCache.get(LocalCache.java:3937) at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3941) at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4824) at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4830) at com.facebook.presto.metadata.FunctionRegistry.getScalarFunctionImplementation(FunctionRegistry.java:862) at com.facebook.presto.sql.relational.optimizer.ExpressionOptimizer$Visitor.visitCall(ExpressionOptimizer.java:146) at com.facebook.presto.sql.relational.optimizer.ExpressionOptimizer$Visitor.visitCall(ExpressionOptimizer.java:72) at com.facebook.presto.sql.relational.CallExpression.accept(CallExpression.java:88) at com.facebook.presto.sql.relational.optimizer.ExpressionOptimizer$Visitor.visitLambda(ExpressionOptimizer.java:191) at com.facebook.presto.sql.relational.optimizer.ExpressionOptimizer$Visitor.visitLambda(ExpressionOptimizer.java:72) at com.facebook.presto.sql.relational.LambdaDefinitionExpression.accept(LambdaDefinitionExpression.java:93) at com.facebook.presto.sql.relational.optimizer.ExpressionOptimizer$Visitor.lambda$visitCall$3(ExpressionOptimizer.java:151) at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) at java.util.Iterator.forEachRemaining(Iterator.java:116) at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499) at com.facebook.presto.sql.relational.optimizer.ExpressionOptimizer$Visitor.visitCall(ExpressionOptimizer.java:152) at com.facebook.presto.sql.relational.optimizer.ExpressionOptimizer$Visitor.visitCall(ExpressionOptimizer.java:72) at com.facebook.presto.sql.relational.CallExpression.accept(CallExpression.java:88) at com.facebook.presto.sql.relational.optimizer.ExpressionOptimizer.optimize(ExpressionOptimizer.java:69) at com.facebook.presto.sql.relational.SqlToRowExpressionTranslator.translate(SqlToRowExpressionTranslator.java:146) at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.toRowExpression(LocalExecutionPlanner.java:1119) at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.lambda$visitScanFilterAndProject$5(LocalExecutionPlanner.java:1023) at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374) at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499) at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitScanFilterAndProject(LocalExecutionPlanner.java:1024) at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitProject(LocalExecutionPlanner.java:951) at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitProject(LocalExecutionPlanner.java:536) at com.facebook.presto.sql.planner.plan.ProjectNode.accept(ProjectNode.java:81) at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitOutput(LocalExecutionPlanner.java:575) at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitOutput(LocalExecutionPlanner.java:536) at com.facebook.presto.sql.planner.plan.OutputNode.accept(OutputNode.java:81) at com.facebook.presto.sql.planner.LocalExecutionPlanner.plan(LocalExecutionPlanner.java:351) at com.facebook.presto.sql.planner.LocalExecutionPlanner.plan(LocalExecutionPlanner.java:290) at com.facebook.presto.execution.SqlTaskExecution.<init>(SqlTaskExecution.java:161) at com.facebook.presto.execution.SqlTaskExecution.createSqlTaskExecution(SqlTaskExecution.java:120) at com.facebook.presto.execution.SqlTaskExecutionFactory.create(SqlTaskExecutionFactory.java:70) at com.facebook.presto.execution.SqlTask.updateTask(SqlTask.java:315) at com.facebook.presto.execution.SqlTaskManager.updateTask(SqlTaskManager.java:324) at com.facebook.presto.server.TaskResource.createOrUpdateTask(TaskResource.java:125) at sun.reflect.GeneratedMethodAccessor154.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161) at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99) at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102) at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) at org.glassfish.jersey.internal.Errors.process(Errors.java:315) at org.glassfish.jersey.internal.Errors.process(Errors.java:297) at org.glassfish.jersey.internal.Errors.process(Errors.java:267) at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317) at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305) at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154) at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473) at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228) at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:845) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1689) at io.airlift.http.server.TraceTokenFilter.doFilter(TraceTokenFilter.java:63) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676) at io.airlift.http.server.TimingFilter.doFilter(TimingFilter.java:52) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676) at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:581) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143) at org.eclipse.jetty.server.handler.gzip.GzipHandler.handle(GzipHandler.java:395) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1182) at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511) at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:119) at org.eclipse.jetty.server.handler.StatisticsHandler.handle(StatisticsHandler.java:169) at org.eclipse.jetty.server.handler.HandlerList.handle(HandlerList.java:52) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134) at org.eclipse.jetty.server.Server.handle(Server.java:523) at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320) at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251) at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273) at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95) at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93) at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303) at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148) at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671) at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589) at java.lang.Thread.run(Thread.java:745) ```
cbdadcf70b0f55cbe844a31d4a2b32c9eb59063b
cd9c9354d2b6496176f81b33ad388ba5ca3f9a9e
https://github.com/prestodb/presto/compare/cbdadcf70b0f55cbe844a31d4a2b32c9eb59063b...cd9c9354d2b6496176f81b33ad388ba5ca3f9a9e
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/analyzer/AggregateExtractor.java b/presto-main/src/main/java/com/facebook/presto/sql/analyzer/AggregateExtractor.java index 3cca1c8353..488bc316e4 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/analyzer/AggregateExtractor.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/analyzer/AggregateExtractor.java @@ -13,7 +13,7 @@ */ package com.facebook.presto.sql.analyzer; -import com.facebook.presto.metadata.Metadata; +import com.facebook.presto.metadata.FunctionRegistry; import com.facebook.presto.sql.tree.DefaultExpressionTraversalVisitor; import com.facebook.presto.sql.tree.FunctionCall; import com.google.common.collect.ImmutableList; @@ -25,21 +25,19 @@ import static java.util.Objects.requireNonNull; class AggregateExtractor extends DefaultExpressionTraversalVisitor<Void, Void> { - private final Metadata metadata; + private final FunctionRegistry functionRegistry; private final ImmutableList.Builder<FunctionCall> aggregates = ImmutableList.builder(); - public AggregateExtractor(Metadata metadata) + public AggregateExtractor(FunctionRegistry functionRegistry) { - requireNonNull(metadata, "metadata is null"); - - this.metadata = metadata; + this.functionRegistry = requireNonNull(functionRegistry, "functionRegistry is null"); } @Override protected Void visitFunctionCall(FunctionCall node, Void context) { - if (metadata.isAggregationFunction(node.getName()) && !node.getWindow().isPresent()) { + if (functionRegistry.isAggregationFunction(node.getName()) && !node.getWindow().isPresent()) { aggregates.add(node); return null; } diff --git a/presto-main/src/main/java/com/facebook/presto/sql/analyzer/AggregationAnalyzer.java b/presto-main/src/main/java/com/facebook/presto/sql/analyzer/AggregationAnalyzer.java index 510424e048..a025d8a802 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/analyzer/AggregationAnalyzer.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/analyzer/AggregationAnalyzer.java @@ -278,7 +278,7 @@ class AggregationAnalyzer protected Boolean visitFunctionCall(FunctionCall node, Void context) { if (!node.getWindow().isPresent() && metadata.isAggregationFunction(node.getName())) { - AggregateExtractor aggregateExtractor = new AggregateExtractor(metadata); + AggregateExtractor aggregateExtractor = new AggregateExtractor(metadata.getFunctionRegistry()); WindowFunctionExtractor windowExtractor = new WindowFunctionExtractor(); for (Expression argument : node.getArguments()) { diff --git a/presto-main/src/main/java/com/facebook/presto/sql/analyzer/Analyzer.java b/presto-main/src/main/java/com/facebook/presto/sql/analyzer/Analyzer.java index 947ae045d9..0b8aefaf31 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/analyzer/Analyzer.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/analyzer/Analyzer.java @@ -14,6 +14,7 @@ package com.facebook.presto.sql.analyzer; import com.facebook.presto.Session; +import com.facebook.presto.metadata.FunctionRegistry; import com.facebook.presto.metadata.Metadata; import com.facebook.presto.security.AccessControl; import com.facebook.presto.sql.parser.SqlParser; @@ -68,9 +69,9 @@ public class Analyzer return analysis; } - static void verifyNoAggregatesOrWindowFunctions(Metadata metadata, Expression predicate, String clause) + static void verifyNoAggregatesOrWindowFunctions(FunctionRegistry functionRegistry, Expression predicate, String clause) { - AggregateExtractor extractor = new AggregateExtractor(metadata); + AggregateExtractor extractor = new AggregateExtractor(functionRegistry); extractor.process(predicate, null); WindowFunctionExtractor windowExtractor = new WindowFunctionExtractor(); @@ -79,7 +80,7 @@ public class Analyzer List<FunctionCall> found = ImmutableList.copyOf(Iterables.concat(extractor.getAggregates(), windowExtractor.getWindowFunctions())); if (!found.isEmpty()) { - throw new SemanticException(CANNOT_HAVE_AGGREGATIONS_OR_WINDOWS, predicate, "%s clause cannot contain aggregations or window functions: %s", clause, found); + throw new SemanticException(CANNOT_HAVE_AGGREGATIONS_OR_WINDOWS, predicate, "%s cannot contain aggregations or window functions: %s", clause, found); } } } diff --git a/presto-main/src/main/java/com/facebook/presto/sql/analyzer/ExpressionAnalyzer.java b/presto-main/src/main/java/com/facebook/presto/sql/analyzer/ExpressionAnalyzer.java index 2a09ff69d9..a225c9497d 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/analyzer/ExpressionAnalyzer.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/analyzer/ExpressionAnalyzer.java @@ -121,6 +121,7 @@ import static com.facebook.presto.spi.type.TinyintType.TINYINT; import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature; import static com.facebook.presto.spi.type.VarbinaryType.VARBINARY; import static com.facebook.presto.spi.type.VarcharType.VARCHAR; +import static com.facebook.presto.sql.analyzer.Analyzer.verifyNoAggregatesOrWindowFunctions; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.EXPRESSION_NOT_CONSTANT; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.INVALID_LITERAL; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.INVALID_PARAMETER_USAGE; @@ -783,6 +784,7 @@ public class ExpressionAnalyzer for (Expression expression : node.getArguments()) { if (expression instanceof LambdaExpression) { LambdaExpression lambdaExpression = (LambdaExpression) expression; + verifyNoAggregatesOrWindowFunctions(functionRegistry, lambdaExpression.getBody(), "Lambda expression"); // captures are not supported for now, use empty tuple descriptor Expression lambdaBody = lambdaExpression.getBody(); diff --git a/presto-main/src/main/java/com/facebook/presto/sql/analyzer/StatementAnalyzer.java b/presto-main/src/main/java/com/facebook/presto/sql/analyzer/StatementAnalyzer.java index 608bf8378d..4470a22e2b 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/analyzer/StatementAnalyzer.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/analyzer/StatementAnalyzer.java @@ -944,7 +944,7 @@ class StatementAnalyzer analysis.addCoercion(expression, BOOLEAN, false); } - Analyzer.verifyNoAggregatesOrWindowFunctions(metadata, expression, "JOIN"); + Analyzer.verifyNoAggregatesOrWindowFunctions(metadata.getFunctionRegistry(), expression, "JOIN clause"); // expressionInterpreter/optimizer only understands a subset of expression types // TODO: remove this when the new expression tree is implemented @@ -1514,7 +1514,7 @@ class StatementAnalyzer groupByExpression = groupingColumn; } - Analyzer.verifyNoAggregatesOrWindowFunctions(metadata, groupByExpression, "GROUP BY"); + Analyzer.verifyNoAggregatesOrWindowFunctions(metadata.getFunctionRegistry(), groupByExpression, "GROUP BY clause"); Type type = analysis.getType(groupByExpression); if (!type.isComparable()) { throw new SemanticException(TYPE_MISMATCH, node, "%s is not comparable, and therefore cannot be used in GROUP BY", type); @@ -1631,7 +1631,7 @@ class StatementAnalyzer public void analyzeWhere(Node node, Scope scope, Expression predicate) { - Analyzer.verifyNoAggregatesOrWindowFunctions(metadata, predicate, "WHERE"); + Analyzer.verifyNoAggregatesOrWindowFunctions(metadata.getFunctionRegistry(), predicate, "WHERE clause"); ExpressionAnalysis expressionAnalysis = analyzeExpression(predicate, scope); analysis.recordSubqueries(node, expressionAnalysis); @@ -1664,7 +1664,7 @@ class StatementAnalyzer Set<Expression> columnReferences, List<Expression> expressions) { - AggregateExtractor extractor = new AggregateExtractor(metadata); + AggregateExtractor extractor = new AggregateExtractor(metadata.getFunctionRegistry()); for (Expression expression : expressions) { extractor.process(expression); } @@ -1690,7 +1690,7 @@ class StatementAnalyzer private boolean hasAggregates(QuerySpecification node) { - AggregateExtractor extractor = new AggregateExtractor(metadata); + AggregateExtractor extractor = new AggregateExtractor(metadata.getFunctionRegistry()); node.getSelect() .getSelectItems().stream() diff --git a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java index 5d2e0b5a37..900c96af74 100644 --- a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java +++ b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java @@ -203,6 +203,12 @@ public abstract class AbstractTestQueries assertQuery("SELECT apply((SELECT 10), i -> i * i)", "SELECT 100"); } + @Test + public void testLambdaWithAggregation() + { + assertQueryFails("SELECT transform(ARRAY[1], x -> max(x))", ".* Lambda expression cannot contain aggregations or window functions: .*"); + } + @Test public void testNonDeterministicFilter() {
['presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java', 'presto-main/src/main/java/com/facebook/presto/sql/analyzer/AggregateExtractor.java', 'presto-main/src/main/java/com/facebook/presto/sql/analyzer/StatementAnalyzer.java', 'presto-main/src/main/java/com/facebook/presto/sql/analyzer/ExpressionAnalyzer.java', 'presto-main/src/main/java/com/facebook/presto/sql/analyzer/AggregationAnalyzer.java', 'presto-main/src/main/java/com/facebook/presto/sql/analyzer/Analyzer.java']
{'.java': 6}
6
6
0
0
6
13,567,463
2,694,583
375,974
2,702
2,868
499
33
5
10,316
243
2,227
120
0
2
1970-01-01T00:24:41
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
182
prestodb/presto/7037/7036
prestodb
presto
https://github.com/prestodb/presto/issues/7036
https://github.com/prestodb/presto/pull/7037
https://github.com/prestodb/presto/pull/7037
1
fixes
Try/Lambda fails codegen when two identical instances appears in a single expression
These following queries fails: ``` SELECT try(1/x)+try(1/x) FROM (VALUES 2) t(x) ``` Stack trace: ``` com.facebook.presto.spi.PrestoException: Compiler failed and interpreter is disabled at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitScanFilterAndProject(LocalExecutionPlanner.java:1056) at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitProject(LocalExecutionPlanner.java:950) at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitProject(LocalExecutionPlanner.java:538) at com.facebook.presto.sql.planner.plan.ProjectNode.accept(ProjectNode.java:91) at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitOutput(LocalExecutionPlanner.java:577) at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitOutput(LocalExecutionPlanner.java:538) at com.facebook.presto.sql.planner.plan.OutputNode.accept(OutputNode.java:81) at com.facebook.presto.sql.planner.LocalExecutionPlanner.plan(LocalExecutionPlanner.java:353) at com.facebook.presto.sql.planner.LocalExecutionPlanner.plan(LocalExecutionPlanner.java:292) at com.facebook.presto.execution.SqlTaskExecution.<init>(SqlTaskExecution.java:161) at com.facebook.presto.execution.SqlTaskExecution.createSqlTaskExecution(SqlTaskExecution.java:120) at com.facebook.presto.execution.SqlTaskExecutionFactory.create(SqlTaskExecutionFactory.java:70) at com.facebook.presto.execution.SqlTask.updateTask(SqlTask.java:315) at com.facebook.presto.execution.SqlTaskManager.updateTask(SqlTaskManager.java:324) at com.facebook.presto.server.TaskResource.createOrUpdateTask(TaskResource.java:125) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161) at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99) at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102) at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) at org.glassfish.jersey.internal.Errors.process(Errors.java:315) at org.glassfish.jersey.internal.Errors.process(Errors.java:297) at org.glassfish.jersey.internal.Errors.process(Errors.java:267) at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317) at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305) at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154) at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473) at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228) at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:845) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1689) at io.airlift.http.server.TraceTokenFilter.doFilter(TraceTokenFilter.java:63) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676) at io.airlift.http.server.TimingFilter.doFilter(TimingFilter.java:52) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676) at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:581) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143) at org.eclipse.jetty.server.handler.gzip.GzipHandler.handle(GzipHandler.java:395) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1182) at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511) at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:119) at org.eclipse.jetty.server.handler.StatisticsHandler.handle(StatisticsHandler.java:169) at org.eclipse.jetty.server.handler.HandlerList.handle(HandlerList.java:52) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134) at org.eclipse.jetty.server.Server.handle(Server.java:523) at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320) at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251) at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273) at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95) at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93) at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303) at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148) at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671) at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589) at java.lang.Thread.run(Thread.java:745) Caused by: com.google.common.util.concurrent.UncheckedExecutionException: java.lang.IllegalArgumentException: Multiple entries with same key: $operator$DIVIDE(1, #0)=public java.lang.Long project_0_try_1(com.facebook.presto.spi.ConnectorSession session, com.facebook.presto.spi.block.Block block_0, int position) and $operator$DIVIDE(1, #0)=public java.lang.Long project_0_try_0(com.facebook.presto.spi.ConnectorSession session, com.facebook.presto.spi.block.Block block_0, int position) at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2203) at com.google.common.cache.LocalCache.get(LocalCache.java:3937) at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3941) at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4824) at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4830) at com.facebook.presto.sql.gen.ExpressionCompiler.compilePageProcessor(ExpressionCompiler.java:99) at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitScanFilterAndProject(LocalExecutionPlanner.java:1043) ... 69 more Caused by: java.lang.IllegalArgumentException: Multiple entries with same key: $operator$DIVIDE(1, #0)=public java.lang.Long project_0_try_1(com.facebook.presto.spi.ConnectorSession session, com.facebook.presto.spi.block.Block block_0, int position) and $operator$DIVIDE(1, #0)=public java.lang.Long project_0_try_0(com.facebook.presto.spi.ConnectorSession session, com.facebook.presto.spi.block.Block block_0, int position) at com.google.common.collect.ImmutableMap.checkNoConflict(ImmutableMap.java:150) at com.google.common.collect.RegularImmutableMap.checkNoConflictInBucket(RegularImmutableMap.java:104) at com.google.common.collect.RegularImmutableMap.<init>(RegularImmutableMap.java:70) at com.google.common.collect.ImmutableMap$Builder.build(ImmutableMap.java:254) at com.facebook.presto.sql.gen.PageProcessorCompiler.generateMethodsForLambdaAndTry(PageProcessorCompiler.java:798) at com.facebook.presto.sql.gen.PageProcessorCompiler.generateProjectMethod(PageProcessorCompiler.java:845) at com.facebook.presto.sql.gen.PageProcessorCompiler.generateMethods(PageProcessorCompiler.java:110) at com.facebook.presto.sql.gen.ExpressionCompiler.compileProcessor(ExpressionCompiler.java:134) at com.facebook.presto.sql.gen.ExpressionCompiler.compile(ExpressionCompiler.java:114) at com.facebook.presto.sql.gen.ExpressionCompiler.access$300(ExpressionCompiler.java:46) at com.facebook.presto.sql.gen.ExpressionCompiler$1.load(ExpressionCompiler.java:57) at com.facebook.presto.sql.gen.ExpressionCompiler$1.load(ExpressionCompiler.java:52) at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3527) at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2319) at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2282) at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2197) ... 75 more ```
618e68d7df6db4be45236cfb36c2e17392e8f227
8f94c916cd437ca2dce31a7c77c575bd0f78894b
https://github.com/prestodb/presto/compare/618e68d7df6db4be45236cfb36c2e17392e8f227...8f94c916cd437ca2dce31a7c77c575bd0f78894b
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/gen/CursorProcessorCompiler.java b/presto-main/src/main/java/com/facebook/presto/sql/gen/CursorProcessorCompiler.java index cdce084cef..0a2bf8d345 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/gen/CursorProcessorCompiler.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/gen/CursorProcessorCompiler.java @@ -42,10 +42,12 @@ import com.facebook.presto.sql.relational.VariableReferenceExpression; import com.google.common.base.VerifyException; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; import com.google.common.primitives.Primitives; import io.airlift.slice.Slice; import java.util.List; +import java.util.Set; import static com.facebook.presto.bytecode.Access.PUBLIC; import static com.facebook.presto.bytecode.Access.a; @@ -187,14 +189,13 @@ public class CursorProcessorCompiler RowExpression projection, String methodPrefix) { - List<RowExpression> lambdaAndTryExpressions = extractLambdaAndTryExpressions(projection); + Set<RowExpression> lambdaAndTryExpressions = ImmutableSet.copyOf(extractLambdaAndTryExpressions(projection)); ImmutableMap.Builder<CallExpression, MethodDefinition> tryMethodMap = ImmutableMap.builder(); ImmutableMap.Builder<LambdaDefinitionExpression, FieldDefinition> lambdaFieldMap = ImmutableMap.builder(); - for (int i = 0; i < lambdaAndTryExpressions.size(); i++) { - RowExpression expression = lambdaAndTryExpressions.get(i); - + int counter = 0; + for (RowExpression expression : lambdaAndTryExpressions) { if (expression instanceof CallExpression) { CallExpression tryExpression = (CallExpression) expression; verify(!Signatures.TRY.equals(tryExpression.getSignature().getName())); @@ -217,7 +218,7 @@ public class CursorProcessorCompiler MethodDefinition tryMethod = defineTryMethod( innerExpressionVisitor, containerClassDefinition, - methodPrefix + "_try_" + i, + methodPrefix + "_try_" + counter, inputParameters, Primitives.wrap(tryExpression.getType().getJavaType()), tryExpression, @@ -227,7 +228,7 @@ public class CursorProcessorCompiler } else if (expression instanceof LambdaDefinitionExpression) { LambdaDefinitionExpression lambdaExpression = (LambdaDefinitionExpression) expression; - String fieldName = methodPrefix + "_lambda_" + i; + String fieldName = methodPrefix + "_lambda_" + counter; PreGeneratedExpressions preGeneratedExpressions = new PreGeneratedExpressions(tryMethodMap.build(), lambdaFieldMap.build()); FieldDefinition methodHandleField = LambdaBytecodeGenerator.preGenerateLambdaExpression( lambdaExpression, @@ -242,6 +243,7 @@ public class CursorProcessorCompiler else { throw new VerifyException(format("unexpected expression: %s", expression.toString())); } + counter++; } return new PreGeneratedExpressions(tryMethodMap.build(), lambdaFieldMap.build()); diff --git a/presto-main/src/main/java/com/facebook/presto/sql/gen/JoinFilterFunctionCompiler.java b/presto-main/src/main/java/com/facebook/presto/sql/gen/JoinFilterFunctionCompiler.java index e2674c36bf..779f34e164 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/gen/JoinFilterFunctionCompiler.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/gen/JoinFilterFunctionCompiler.java @@ -41,6 +41,7 @@ import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; import com.google.common.primitives.Primitives; import it.unimi.dsi.fastutil.longs.LongArrayList; @@ -49,6 +50,7 @@ import javax.inject.Inject; import java.lang.reflect.Constructor; import java.util.List; import java.util.Objects; +import java.util.Set; import static com.facebook.presto.bytecode.Access.FINAL; import static com.facebook.presto.bytecode.Access.PRIVATE; @@ -206,13 +208,12 @@ public class JoinFilterFunctionCompiler int leftBlocksSize, RowExpression filter) { - List<RowExpression> lambdaAndTryExpressions = extractLambdaAndTryExpressions(filter); + Set<RowExpression> lambdaAndTryExpressions = ImmutableSet.copyOf(extractLambdaAndTryExpressions(filter)); ImmutableMap.Builder<CallExpression, MethodDefinition> tryMethodMap = ImmutableMap.builder(); ImmutableMap.Builder<LambdaDefinitionExpression, FieldDefinition> lambdaFieldMap = ImmutableMap.builder(); - for (int i = 0; i < lambdaAndTryExpressions.size(); i++) { - RowExpression expression = lambdaAndTryExpressions.get(i); - + int counter = 0; + for (RowExpression expression : lambdaAndTryExpressions) { if (expression instanceof CallExpression) { CallExpression tryExpression = (CallExpression) expression; verify(!Signatures.TRY.equals(tryExpression.getSignature().getName())); @@ -241,7 +242,7 @@ public class JoinFilterFunctionCompiler MethodDefinition tryMethod = defineTryMethod( innerExpressionVisitor, containerClassDefinition, - "try_" + i, + "try_" + counter, inputParameters, Primitives.wrap(tryExpression.getType().getJavaType()), tryExpression, @@ -254,7 +255,7 @@ public class JoinFilterFunctionCompiler PreGeneratedExpressions preGeneratedExpressions = new PreGeneratedExpressions(tryMethodMap.build(), lambdaFieldMap.build()); FieldDefinition methodHandleField = LambdaBytecodeGenerator.preGenerateLambdaExpression( lambdaExpression, - "lambda_" + i, + "lambda_" + counter, containerClassDefinition, preGeneratedExpressions, callSiteBinder, @@ -265,6 +266,7 @@ public class JoinFilterFunctionCompiler else { throw new VerifyException(format("unexpected expression: %s", expression.toString())); } + counter++; } return new PreGeneratedExpressions(tryMethodMap.build(), lambdaFieldMap.build()); diff --git a/presto-main/src/main/java/com/facebook/presto/sql/gen/PageProcessorCompiler.java b/presto-main/src/main/java/com/facebook/presto/sql/gen/PageProcessorCompiler.java index dc3d308f1a..c88d29e35a 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/gen/PageProcessorCompiler.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/gen/PageProcessorCompiler.java @@ -49,12 +49,14 @@ import com.facebook.presto.sql.relational.Signatures; import com.google.common.base.VerifyException; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; import com.google.common.primitives.Primitives; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.TreeSet; import java.util.stream.IntStream; @@ -738,13 +740,12 @@ public class PageProcessorCompiler RowExpression projection, String methodPrefix) { - List<RowExpression> lambdaAndTryExpressions = extractLambdaAndTryExpressions(projection); + Set<RowExpression> lambdaAndTryExpressions = ImmutableSet.copyOf(extractLambdaAndTryExpressions(projection)); ImmutableMap.Builder<CallExpression, MethodDefinition> tryMethodMap = ImmutableMap.builder(); ImmutableMap.Builder<LambdaDefinitionExpression, FieldDefinition> lambdaFieldMap = ImmutableMap.builder(); - for (int i = 0; i < lambdaAndTryExpressions.size(); i++) { - RowExpression expression = lambdaAndTryExpressions.get(i); - + int counter = 0; + for (RowExpression expression : lambdaAndTryExpressions) { if (expression instanceof CallExpression) { CallExpression tryExpression = (CallExpression) expression; verify(!Signatures.TRY.equals(tryExpression.getSignature().getName())); @@ -769,7 +770,7 @@ public class PageProcessorCompiler MethodDefinition tryMethod = defineTryMethod( innerExpressionVisitor, containerClassDefinition, - methodPrefix + "_try_" + i, + methodPrefix + "_try_" + counter, inputParameters, Primitives.wrap(tryExpression.getType().getJavaType()), tryExpression, @@ -782,7 +783,7 @@ public class PageProcessorCompiler PreGeneratedExpressions preGeneratedExpressions = new PreGeneratedExpressions(tryMethodMap.build(), lambdaFieldMap.build()); FieldDefinition methodHandleField = LambdaBytecodeGenerator.preGenerateLambdaExpression( lambdaExpression, - methodPrefix + "_lambda_" + i, + methodPrefix + "_lambda_" + counter, containerClassDefinition, preGeneratedExpressions, callSiteBinder, @@ -793,6 +794,7 @@ public class PageProcessorCompiler else { throw new VerifyException(format("unexpected expression: %s", expression.toString())); } + counter++; } return new PreGeneratedExpressions(tryMethodMap.build(), lambdaFieldMap.build()); diff --git a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java index acf00efd70..2cbc0f0785 100644 --- a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java +++ b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java @@ -216,6 +216,16 @@ public abstract class AbstractTestQueries assertQueryFails("SELECT transform(ARRAY[1], x -> max(x))", ".* Lambda expression cannot contain aggregations or window functions: .*"); } + @Test + public void testTryLambdaRepeated() + { + assertQuery("SELECT x + x FROM (SELECT apply(a, i -> i * i) x FROM (VALUES 3) t(a))", "SELECT 18"); + assertQuery("SELECT apply(a, i -> i * i) + apply(a, i -> i * i) FROM (VALUES 3) t(a)", "SELECT 18"); + assertQuery("SELECT apply(a, i -> i * i), apply(a, i -> i * i) FROM (VALUES 3) t(a)", "SELECT 9, 9"); + assertQuery("SELECT try(10 / a) + try(10 / a) FROM (VALUES 5) t(a)", "SELECT 4"); + assertQuery("SELECT try(10 / a), try(10 / a) FROM (VALUES 5) t(a)", "SELECT 2, 2"); + } + @Test public void testNonDeterministicFilter() {
['presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java', 'presto-main/src/main/java/com/facebook/presto/sql/gen/JoinFilterFunctionCompiler.java', 'presto-main/src/main/java/com/facebook/presto/sql/gen/PageProcessorCompiler.java', 'presto-main/src/main/java/com/facebook/presto/sql/gen/CursorProcessorCompiler.java']
{'.java': 4}
4
4
0
0
4
13,743,389
2,728,755
381,136
2,723
2,284
442
42
3
9,549
271
2,137
111
0
2
1970-01-01T00:24:44
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
181
prestodb/presto/7424/7414
prestodb
presto
https://github.com/prestodb/presto/issues/7414
https://github.com/prestodb/presto/pull/7424
https://github.com/prestodb/presto/pull/7424
1
fixes
Broken full CI tests in presto-orc
Running full-ci in Jenkins turns up the following test failures. These can be reproduced in IntelliJ also. ``` testCharDirectSequence(com.facebook.presto.orc.TestFullOrcReader) Time elapsed: 2.737 sec <<< FAILURE! java.lang.ArrayIndexOutOfBoundsException: 11111 testStringDirectSequence(com.facebook.presto.orc.TestFullOrcReader) Time elapsed: 55.727 sec <<< FAILURE! java.lang.ArrayIndexOutOfBoundsException Results : Failed tests: TestFullOrcReader>AbstractTestOrcReader.testCharDirectSequence:308 » ArrayIndexOutOfBounds TestFullOrcReader.testStringDirectSequence » ArrayIndexOutOfBounds ```
34e31333a20d236b7896fc4e0a0b1185a241efc6
637fff3cf6de81ddfd98ff3bca9a30d35294f23d
https://github.com/prestodb/presto/compare/34e31333a20d236b7896fc4e0a0b1185a241efc6...637fff3cf6de81ddfd98ff3bca9a30d35294f23d
diff --git a/presto-main/src/test/java/com/facebook/presto/block/TestDictionaryBlock.java b/presto-main/src/test/java/com/facebook/presto/block/TestDictionaryBlock.java index 9bbfc30219..25f4dc6d0e 100644 --- a/presto-main/src/test/java/com/facebook/presto/block/TestDictionaryBlock.java +++ b/presto-main/src/test/java/com/facebook/presto/block/TestDictionaryBlock.java @@ -19,7 +19,6 @@ import com.google.common.primitives.Ints; import io.airlift.slice.Slice; import org.testng.annotations.Test; -import java.util.Arrays; import java.util.List; import static io.airlift.slice.SizeOf.SIZE_OF_INT; @@ -55,6 +54,7 @@ public class TestDictionaryBlock throws Exception { Slice[] expectedValues = createExpectedValues(10); + Slice firstExpectedValue = expectedValues[0]; DictionaryBlock dictionaryBlock = createDictionaryBlock(expectedValues, 100); List<Integer> positionsToCopy = Ints.asList(0, 10, 20, 30, 40); @@ -62,7 +62,8 @@ public class TestDictionaryBlock assertEquals(copiedBlock.getDictionary().getPositionCount(), 1); assertEquals(copiedBlock.getPositionCount(), positionsToCopy.size()); - assertBlock(copiedBlock.getDictionary(), Arrays.copyOfRange(expectedValues, 0, 1)); + assertBlock(copiedBlock.getDictionary(), new Slice[]{firstExpectedValue}); + assertBlock(copiedBlock, new Slice[]{firstExpectedValue, firstExpectedValue, firstExpectedValue, firstExpectedValue, firstExpectedValue}); } @Test diff --git a/presto-spi/src/main/java/com/facebook/presto/spi/block/AbstractInterleavedBlock.java b/presto-spi/src/main/java/com/facebook/presto/spi/block/AbstractInterleavedBlock.java index ef5b973ced..0a3f465a50 100644 --- a/presto-spi/src/main/java/com/facebook/presto/spi/block/AbstractInterleavedBlock.java +++ b/presto-spi/src/main/java/com/facebook/presto/spi/block/AbstractInterleavedBlock.java @@ -255,6 +255,11 @@ public abstract class AbstractInterleavedBlock @Override public int getRegionSizeInBytes(int position, int length) { + if (position == 0 && length == getPositionCount()) { + // Calculation of getRegionSizeInBytes is expensive in this class. + // On the other hand, getSizeInBytes result is cached or pre-computed. + return getSizeInBytes(); + } validateRange(position, length); int result = 0; for (int blockIndex = 0; blockIndex < getBlockCount(); blockIndex++) { diff --git a/presto-spi/src/main/java/com/facebook/presto/spi/block/DictionaryBlock.java b/presto-spi/src/main/java/com/facebook/presto/spi/block/DictionaryBlock.java index 38f016dd94..8b6b50b9c9 100644 --- a/presto-spi/src/main/java/com/facebook/presto/spi/block/DictionaryBlock.java +++ b/presto-spi/src/main/java/com/facebook/presto/spi/block/DictionaryBlock.java @@ -218,15 +218,21 @@ public class DictionaryBlock @Override public int getRegionSizeInBytes(int positionOffset, int length) { + if (positionOffset == 0 && length == getPositionCount()) { + // Calculation of getRegionSizeInBytes is expensive in this class. + // On the other hand, getSizeInBytes result is cached. + return getSizeInBytes(); + } + int sizeInBytes = 0; - boolean[] seen = new boolean[length]; - for (int i = positionOffset; i < length; i++) { + boolean[] seen = new boolean[dictionary.getPositionCount()]; + for (int i = positionOffset; i < positionOffset + length; i++) { int position = getId(i); - if (!seen[position - positionOffset]) { + if (!seen[position]) { if (!dictionary.isNull(position)) { sizeInBytes += dictionary.getRegionSizeInBytes(position, 1); } - seen[position - positionOffset] = true; + seen[position] = true; } } return sizeInBytes + (length * Integer.BYTES); @@ -311,6 +317,9 @@ public class DictionaryBlock public int getId(int position) { + if (position < 0 || position >= positionCount) { + throw new IllegalArgumentException("Invalid position " + position + " in block with " + positionCount + " positions"); + } return ids[position + idsOffset]; } diff --git a/presto-spi/src/main/java/com/facebook/presto/spi/block/DictionaryBlockEncoding.java b/presto-spi/src/main/java/com/facebook/presto/spi/block/DictionaryBlockEncoding.java index 099b3f1778..3bb8f3456b 100644 --- a/presto-spi/src/main/java/com/facebook/presto/spi/block/DictionaryBlockEncoding.java +++ b/presto-spi/src/main/java/com/facebook/presto/spi/block/DictionaryBlockEncoding.java @@ -81,8 +81,10 @@ public class DictionaryBlockEncoding long leastSignificantBits = sliceInput.readLong(); long sequenceId = sliceInput.readLong(); - // we always compact the dictionary before we send it - return new DictionaryBlock(positionCount, dictionaryBlock, ids, true, new DictionaryId(mostSignificantBits, leastSignificantBits, sequenceId)); + // We always compact the dictionary before we send it. However, dictionaryBlock comes from sliceInput, which may over-retain memory. + // As a result, setting dictionaryIsCompacted to true is not appropriate here. + // TODO: fix DictionaryBlock so that dictionaryIsCompacted can be set to true when the underlying block over-retains memory. + return new DictionaryBlock(positionCount, dictionaryBlock, ids, false, new DictionaryId(mostSignificantBits, leastSignificantBits, sequenceId)); } @Override diff --git a/presto-spi/src/main/java/com/facebook/presto/spi/block/SliceArrayBlock.java b/presto-spi/src/main/java/com/facebook/presto/spi/block/SliceArrayBlock.java index 62e9d7594b..9a9198ef17 100644 --- a/presto-spi/src/main/java/com/facebook/presto/spi/block/SliceArrayBlock.java +++ b/presto-spi/src/main/java/com/facebook/presto/spi/block/SliceArrayBlock.java @@ -192,6 +192,11 @@ public class SliceArrayBlock public int getRegionSizeInBytes(int positionOffset, int length) { int positionCount = getPositionCount(); + if (positionOffset == 0 && length == positionCount) { + // Calculation of getRegionSizeInBytes is expensive in this class. + // On the other hand, getSizeInBytes result is pre-computed. + return getSizeInBytes(); + } if (positionOffset < 0 || length < 0 || positionOffset + length > positionCount) { throw new IndexOutOfBoundsException("Invalid position " + positionOffset + " in block with " + positionCount + " positions"); }
['presto-spi/src/main/java/com/facebook/presto/spi/block/DictionaryBlockEncoding.java', 'presto-spi/src/main/java/com/facebook/presto/spi/block/SliceArrayBlock.java', 'presto-main/src/test/java/com/facebook/presto/block/TestDictionaryBlock.java', 'presto-spi/src/main/java/com/facebook/presto/spi/block/DictionaryBlock.java', 'presto-spi/src/main/java/com/facebook/presto/spi/block/AbstractInterleavedBlock.java']
{'.java': 5}
5
5
0
0
5
14,041,148
2,788,419
388,696
2,797
2,173
440
33
4
623
46
144
16
0
1
1970-01-01T00:24:47
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
180
prestodb/presto/8372/8316
prestodb
presto
https://github.com/prestodb/presto/issues/8316
https://github.com/prestodb/presto/pull/8372
https://github.com/prestodb/presto/pull/8372
1
fixes
Number of splits for intermediate stages in CLI shows incorrect values
There two related problems: 1) the number of running intermediate splits goes up and down throughout the execution of the query. This causes the progress bar to move forward and backward, since the chevron section of the bar depends on how many splits are running at a given point in time. 2) in cases where most leaf splits are done and the query is waiting on stragglers, intermediate stages show "0" splits running. This causes overall progress to show a misleading number, since the intermediate splits are being counted towards the total number of splits to be completed. I believe this may be happening because RUNNING state for intermediate splits no longer counts splits that are BLOCKED. We need to fix the counter so that it reflects both (i.e., splits scheduled on workers, instead of just splits being scheduled on a CPU). ``` 46:20 [32.4M rows, 3.01GB] [11.7K rows/s, 1.11MB/s] [========> ] 18% STAGES ROWS ROWS/s BYTES BYTES/s QUEUED RUN DONE 0.........R 0 0 0B 0B 0 0 0 1.......R 0 0 0B 0B 0 0 0 2.....R 56.6M 20.3K 7.1G 2.61M 0 0 0 3...R 32.4M 11.7K 3.01G 1.11M 0 1 489 ```
3f4a79d56e025405d40057ee10c59cbf853c7858
d518b756fec6b995815b0761b0e15a6bedd32b0d
https://github.com/prestodb/presto/compare/3f4a79d56e025405d40057ee10c59cbf853c7858...d518b756fec6b995815b0761b0e15a6bedd32b0d
diff --git a/presto-main/src/main/java/com/facebook/presto/operator/PipelineContext.java b/presto-main/src/main/java/com/facebook/presto/operator/PipelineContext.java index a8b39e6688..30f26ecea5 100644 --- a/presto-main/src/main/java/com/facebook/presto/operator/PipelineContext.java +++ b/presto-main/src/main/java/com/facebook/presto/operator/PipelineContext.java @@ -455,7 +455,7 @@ public class PipelineContext new Duration(totalCpuTime, NANOSECONDS).convertToMostSuccinctTimeUnit(), new Duration(totalUserTime, NANOSECONDS).convertToMostSuccinctTimeUnit(), new Duration(totalBlockedTime, NANOSECONDS).convertToMostSuccinctTimeUnit(), - fullyBlocked && (runningDrivers > 0 || runningPartitionedDrivers > 0), + fullyBlocked, blockedReasons, succinctBytes(rawInputDataSize), diff --git a/presto-main/src/main/java/com/facebook/presto/server/StatementResource.java b/presto-main/src/main/java/com/facebook/presto/server/StatementResource.java index 3e1e599f6f..684a77b642 100644 --- a/presto-main/src/main/java/com/facebook/presto/server/StatementResource.java +++ b/presto-main/src/main/java/com/facebook/presto/server/StatementResource.java @@ -625,7 +625,7 @@ public class StatementResource .setNodes(globalUniqueNodes(outputStage).size()) .setTotalSplits(queryStats.getTotalDrivers()) .setQueuedSplits(queryStats.getQueuedDrivers()) - .setRunningSplits(queryStats.getRunningDrivers()) + .setRunningSplits(queryStats.getRunningDrivers() + queryStats.getBlockedDrivers()) .setCompletedSplits(queryStats.getCompletedDrivers()) .setUserTimeMillis(queryStats.getTotalUserTime().toMillis()) .setCpuTimeMillis(queryStats.getTotalCpuTime().toMillis()) @@ -663,7 +663,7 @@ public class StatementResource .setNodes(uniqueNodes.size()) .setTotalSplits(stageStats.getTotalDrivers()) .setQueuedSplits(stageStats.getQueuedDrivers()) - .setRunningSplits(stageStats.getRunningDrivers()) + .setRunningSplits(stageStats.getRunningDrivers() + stageStats.getBlockedDrivers()) .setCompletedSplits(stageStats.getCompletedDrivers()) .setUserTimeMillis(stageStats.getTotalUserTime().toMillis()) .setCpuTimeMillis(stageStats.getTotalCpuTime().toMillis())
['presto-main/src/main/java/com/facebook/presto/server/StatementResource.java', 'presto-main/src/main/java/com/facebook/presto/operator/PipelineContext.java']
{'.java': 2}
2
2
0
0
2
15,572,763
3,102,285
429,906
3,074
467
85
6
2
1,285
194
368
15
0
1
1970-01-01T00:24:58
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
179
prestodb/presto/9057/9056
prestodb
presto
https://github.com/prestodb/presto/issues/9056
https://github.com/prestodb/presto/pull/9057
https://github.com/prestodb/presto/pull/9057
1
fixes
Running queries counter leaks queries
Queries that fail before they get to run cause the running queries counter to increment but never decrement. This is caused by 516801ab482c9189344304b97ff4e4429488dfc7, which calls queryStarted but not queryStopped.
82821985dc14c02274a54b4328136b53df123699
5f9b803e5c1f7886c7e41e35d17feb565827e397
https://github.com/prestodb/presto/compare/82821985dc14c02274a54b4328136b53df123699...5f9b803e5c1f7886c7e41e35d17feb565827e397
diff --git a/presto-main/src/main/java/com/facebook/presto/execution/SqlQueryManager.java b/presto-main/src/main/java/com/facebook/presto/execution/SqlQueryManager.java index c2fa751646..43f442ff32 100644 --- a/presto-main/src/main/java/com/facebook/presto/execution/SqlQueryManager.java +++ b/presto-main/src/main/java/com/facebook/presto/execution/SqlQueryManager.java @@ -421,6 +421,7 @@ public class SqlQueryManager queryMonitor.queryCreatedEvent(queryInfo); queryMonitor.queryCompletedEvent(queryInfo); stats.queryStarted(); + stats.queryStopped(); stats.queryFinished(queryInfo); } finally {
['presto-main/src/main/java/com/facebook/presto/execution/SqlQueryManager.java']
{'.java': 1}
1
1
0
0
1
16,577,273
3,304,657
456,943
3,256
38
5
1
1
217
29
54
2
0
0
1970-01-01T00:25:06
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
191
prestodb/presto/6208/6196
prestodb
presto
https://github.com/prestodb/presto/issues/6196
https://github.com/prestodb/presto/pull/6208
https://github.com/prestodb/presto/pull/6208
1
fixes
Deadlock in task info fetching
Hit this one in production. Suddenly all queries get queued and all clients start timing out. [Here](https://gist.githubusercontent.com/nezihyigitbasi/108b844625d69de66bd8d74e427ea876/raw/c22dc663517fa991b87c162de2b387c0e8af0d69/presto-stack) is the full stack trace. ``` Found one Java-level deadlock: ============================= "http-worker-2010473": waiting to lock monitor 0x00007f8fed4a6fb8 (object 0x00007f9615a7e020, a com.facebook.presto.execution.resourceGroups.ResourceGroup$RootResourceGroup), which is held by "ResourceGroupManager" "ResourceGroupManager": waiting to lock monitor 0x00007f91f0cc3598 (object 0x00007f9a9f000a48, a com.facebook.presto.execution.SqlStageExecution), which is held by "HttpRemoteTask-20160926_222904_08073_w6q27.1.105-2010288" "HttpRemoteTask-20160926_222904_08073_w6q27.1.105-2010288": waiting to lock monitor 0x00007f90ed8c3ee8 (object 0x00007f9a9f000870, a com.facebook.presto.server.remotetask.ContinuousTaskStatusFetcher), which is held by "ContinuousTaskStatusFetcher-20160926_222904_08073_w6q27.1.105-2009564" "ContinuousTaskStatusFetcher-20160926_222904_08073_w6q27.1.105-2009564": waiting to lock monitor 0x00007f910c0b5948 (object 0x00007f9a9f0008e0, a com.facebook.presto.server.remotetask.HttpRemoteTask), which is held by "HttpRemoteTask-20160926_222904_08073_w6q27.1.105-2010288" Java stack information for the threads listed above: =================================================== "http-worker-2010473": at com.facebook.presto.execution.resourceGroups.ResourceGroup.run(ResourceGroup.java:322) - waiting to lock <0x00007f9615a7e020> (a com.facebook.presto.execution.resourceGroups.ResourceGroup$RootResourceGroup) at com.facebook.presto.execution.resourceGroups.ResourceGroupManager.submit(ResourceGroupManager.java:89) at com.facebook.presto.execution.SqlQueryManager.createQuery(SqlQueryManager.java:348) at com.facebook.presto.server.StatementResource$Query.<init>(StatementResource.java:308) at com.facebook.presto.server.StatementResource.createQuery(StatementResource.java:171) at sun.reflect.GeneratedMethodAccessor1181.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161) at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99) at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102) at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) at org.glassfish.jersey.internal.Errors.process(Errors.java:315) at org.glassfish.jersey.internal.Errors.process(Errors.java:297) at org.glassfish.jersey.internal.Errors.process(Errors.java:267) at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317) at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305) at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154) at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473) at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228) at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:845) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1689) at io.airlift.http.server.TraceTokenFilter.doFilter(TraceTokenFilter.java:63) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676) at io.airlift.http.server.TimingFilter.doFilter(TimingFilter.java:52) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676) at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:581) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143) at org.eclipse.jetty.server.handler.gzip.GzipHandler.handle(GzipHandler.java:396) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1176) at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511) at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1106) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:119) at org.eclipse.jetty.server.handler.StatisticsHandler.handle(StatisticsHandler.java:169) at org.eclipse.jetty.server.handler.HandlerList.handle(HandlerList.java:52) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134) at org.eclipse.jetty.server.Server.handle(Server.java:518) at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:314) at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:253) at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273) at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95) at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:654) at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:572) at java.lang.Thread.run(Thread.java:745) "ResourceGroupManager": at com.facebook.presto.execution.SqlStageExecution.getMemoryReservation(SqlStageExecution.java:184) - waiting to lock <0x00007f9a9f000a48> (a com.facebook.presto.execution.SqlStageExecution) at com.facebook.presto.execution.scheduler.SqlQueryScheduler$$Lambda$792/605126606.applyAsLong(Unknown Source) at java.util.stream.ReferencePipeline$5$1.accept(ReferencePipeline.java:227) at java.util.Iterator.forEachRemaining(Iterator.java:116) at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) at java.util.stream.LongPipeline.reduce(LongPipeline.java:438) at java.util.stream.LongPipeline.sum(LongPipeline.java:396) at com.facebook.presto.execution.scheduler.SqlQueryScheduler.getTotalMemoryReservation(SqlQueryScheduler.java:310) at com.facebook.presto.execution.SqlQueryExecution.getTotalMemoryReservation(SqlQueryExecution.java:188) at com.facebook.presto.execution.resourceGroups.ResourceGroup.internalRefreshStats(ResourceGroup.java:438) - locked <0x00007f9615a7e020> (a com.facebook.presto.execution.resourceGroups.ResourceGroup$RootResourceGroup) at com.facebook.presto.execution.resourceGroups.ResourceGroup.internalRefreshStats(ResourceGroup.java:445) - locked <0x00007f9615a7e020> (a com.facebook.presto.execution.resourceGroups.ResourceGroup$RootResourceGroup) at com.facebook.presto.execution.resourceGroups.ResourceGroup$RootResourceGroup.processQueuedQueries(ResourceGroup.java:580) - locked <0x00007f9615a7e020> (a com.facebook.presto.execution.resourceGroups.ResourceGroup$RootResourceGroup) at com.facebook.presto.execution.resourceGroups.ResourceGroupManager.refreshAndStartQueries(ResourceGroupManager.java:110) at com.facebook.presto.execution.resourceGroups.ResourceGroupManager$$Lambda$140/724736957.run(Unknown Source) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) "HttpRemoteTask-20160926_222904_08073_w6q27.1.105-2010288": at com.facebook.presto.server.remotetask.ContinuousTaskStatusFetcher.updateTaskStatus(ContinuousTaskStatusFetcher.java:214) - waiting to lock <0x00007f9a9f000870> (a com.facebook.presto.server.remotetask.ContinuousTaskStatusFetcher) at com.facebook.presto.server.remotetask.HttpRemoteTask.abort(HttpRemoteTask.java:560) - locked <0x00007f9a9f0008e0> (a com.facebook.presto.server.remotetask.HttpRemoteTask) at com.facebook.presto.server.remotetask.HttpRemoteTask.abort(HttpRemoteTask.java:552) - locked <0x00007f9a9f0008e0> (a com.facebook.presto.server.remotetask.HttpRemoteTask) at com.facebook.presto.execution.SqlStageExecution$$Lambda$1037/616866428.accept(Unknown Source) at java.lang.Iterable.forEach(Iterable.java:75) at com.facebook.presto.execution.SqlStageExecution.abort(SqlStageExecution.java:179) - locked <0x00007f9a9f000a48> (a com.facebook.presto.execution.SqlStageExecution) at com.facebook.presto.execution.scheduler.SqlQueryScheduler$$Lambda$1035/234080167.accept(Unknown Source) at java.util.Iterator.forEachRemaining(Iterator.java:116) at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580) at com.facebook.presto.execution.scheduler.SqlQueryScheduler.abort(SqlQueryScheduler.java:412) at com.facebook.presto.execution.SqlQueryExecution.lambda$new$0(SqlQueryExecution.java:154) at com.facebook.presto.execution.SqlQueryExecution$$Lambda$440/1153217709.stateChanged(Unknown Source) at com.facebook.presto.execution.StateMachine.lambda$fireStateChanged$0(StateMachine.java:225) at com.facebook.presto.execution.StateMachine$$Lambda$413/743619379.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) "ContinuousTaskStatusFetcher-20160926_222904_08073_w6q27.1.105-2009564": at com.facebook.presto.server.remotetask.HttpRemoteTask.abort(HttpRemoteTask.java:557) - waiting to lock <0x00007f9a9f0008e0> (a com.facebook.presto.server.remotetask.HttpRemoteTask) at com.facebook.presto.server.remotetask.HttpRemoteTask.failTask(HttpRemoteTask.java:621) at com.facebook.presto.server.remotetask.HttpRemoteTask$$Lambda$817/1647878013.accept(Unknown Source) at com.facebook.presto.server.remotetask.ContinuousTaskStatusFetcher.updateTaskStatus(ContinuousTaskStatusFetcher.java:234) - locked <0x00007f9a9f000870> (a com.facebook.presto.server.remotetask.ContinuousTaskStatusFetcher) at com.facebook.presto.server.remotetask.ContinuousTaskStatusFetcher.success(ContinuousTaskStatusFetcher.java:168) at com.facebook.presto.server.remotetask.ContinuousTaskStatusFetcher.success(ContinuousTaskStatusFetcher.java:52) at com.facebook.presto.server.remotetask.SimpleHttpResponseHandler.onSuccess(SimpleHttpResponseHandler.java:49) at com.facebook.presto.server.remotetask.SimpleHttpResponseHandler.onSuccess(SimpleHttpResponseHandler.java:27) at com.google.common.util.concurrent.Futures$6.run(Futures.java:1319) at io.airlift.concurrent.BoundedExecutor.drainQueue(BoundedExecutor.java:77) at io.airlift.concurrent.BoundedExecutor$$Lambda$437/311179219.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Found 1 deadlock. ```
e5dbe7ca1cb519f50a7b13fc1a775e5ba966ab89
72d65cdc4485c788e13647cf2fbca9ff867fd731
https://github.com/prestodb/presto/compare/e5dbe7ca1cb519f50a7b13fc1a775e5ba966ab89...72d65cdc4485c788e13647cf2fbca9ff867fd731
diff --git a/presto-main/src/main/java/com/facebook/presto/server/remotetask/ContinuousTaskStatusFetcher.java b/presto-main/src/main/java/com/facebook/presto/server/remotetask/ContinuousTaskStatusFetcher.java index 77d8dacfeb..12bedf066c 100644 --- a/presto-main/src/main/java/com/facebook/presto/server/remotetask/ContinuousTaskStatusFetcher.java +++ b/presto-main/src/main/java/com/facebook/presto/server/remotetask/ContinuousTaskStatusFetcher.java @@ -208,7 +208,7 @@ class ContinuousTaskStatusFetcher } } - synchronized void updateTaskStatus(TaskStatus newValue) + void updateTaskStatus(TaskStatus newValue) { // change to new value if old value is not changed and new value has a newer version AtomicBoolean taskMismatch = new AtomicBoolean();
['presto-main/src/main/java/com/facebook/presto/server/remotetask/ContinuousTaskStatusFetcher.java']
{'.java': 1}
1
1
0
0
1
12,693,049
2,519,379
352,796
2,569
108
19
2
1
13,128
403
3,208
152
1
1
1970-01-01T00:24:35
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
177
prestodb/presto/2303/2301
prestodb
presto
https://github.com/prestodb/presto/issues/2301
https://github.com/prestodb/presto/pull/2303
https://github.com/prestodb/presto/pull/2303#issuecomment-72136689
1
fixes
INSERT should ignore hidden columns
When doing an `INSERT` that does not specify the column list (which is not yet supported), the column list should only be the visible columns (not hidden columns). Thus, it should be equivalent to the columns returned by `SELECT * FROM t`. For example, using the tpch connector: ``` presto:tiny> describe region; Column | Type | Null | Partition Key | Comment -----------+---------+------+---------------+--------- regionkey | bigint | true | false | name | varchar | true | false | comment | varchar | true | false | (3 rows) presto:tiny> select * from region limit 0; regionkey | name | comment -----------+------+--------- (0 rows) ``` However, the check in `StatementAnalyzer` is including the hidden `row_number` columns: ``` presto:tiny> insert into region select * from region; Query 20150129_235057_00017_b9dwj failed: Insert query has mismatched column types: Table: (bigint, varchar, varchar, bigint), Query: (bigint, varchar, varchar) ```
4802717e947e34f9384ba435bbcfb9f652fa1ff0
6d4c051ddb1f71b0b8b977a102203a7b7f6da9b1
https://github.com/prestodb/presto/compare/4802717e947e34f9384ba435bbcfb9f652fa1ff0...6d4c051ddb1f71b0b8b977a102203a7b7f6da9b1
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/analyzer/StatementAnalyzer.java b/presto-main/src/main/java/com/facebook/presto/sql/analyzer/StatementAnalyzer.java index 56dea1fa03..163872a2a1 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/analyzer/StatementAnalyzer.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/analyzer/StatementAnalyzer.java @@ -55,6 +55,7 @@ import com.facebook.presto.sql.tree.Values; import com.facebook.presto.sql.tree.With; import com.facebook.presto.sql.tree.WithQuery; import com.google.common.base.Joiner; +import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.primitives.Ints; @@ -364,7 +365,9 @@ class StatementAnalyzer analysis.setInsertTarget(targetTableHandle.get()); List<ColumnMetadata> columns = metadata.getTableMetadata(targetTableHandle.get()).getColumns(); - Iterable<Type> tableTypes = transform(columns, ColumnMetadata::getType); + Iterable<Type> tableTypes = FluentIterable.from(columns) + .filter(column -> !column.isHidden()) + .transform(ColumnMetadata::getType); Iterable<Type> queryTypes = transform(descriptor.getVisibleFields(), Field::getType); diff --git a/presto-main/src/test/java/com/facebook/presto/sql/analyzer/TestAnalyzer.java b/presto-main/src/test/java/com/facebook/presto/sql/analyzer/TestAnalyzer.java index b4baa460b0..2ac118f284 100644 --- a/presto-main/src/test/java/com/facebook/presto/sql/analyzer/TestAnalyzer.java +++ b/presto-main/src/test/java/com/facebook/presto/sql/analyzer/TestAnalyzer.java @@ -480,6 +480,22 @@ public class TestAnalyzer analyze("WITH AB AS (SELECT * FROM t1) SELECT * FROM ab"); } + @Test + public void testInsert() + throws Exception + { + analyze("INSERT INTO t1 SELECT * FROM t1"); + analyze("INSERT INTO t3 SELECT * FROM t3"); + analyze("INSERT INTO t3 SELECT a, b FROM t3"); + assertFails(MISMATCHED_SET_COLUMN_TYPES, "INSERT INTO t1 VALUES (1, 2)"); + + // ignore t5 hidden column + analyze("INSERT INTO t5 VALUES (1)"); + + // fail if hidden column provided + assertFails(MISMATCHED_SET_COLUMN_TYPES, "INSERT INTO t5 VALUES (1, 2)"); + } + @Test public void testDuplicateWithQuery() throws Exception @@ -751,7 +767,8 @@ public class TestAnalyzer metadata.createTable(SESSION, "tpch", new TableMetadata("tpch", new ConnectorTableMetadata(table3, ImmutableList.<ColumnMetadata>of( new ColumnMetadata("a", BIGINT, 0, false), - new ColumnMetadata("b", BIGINT, 1, false))))); + new ColumnMetadata("b", BIGINT, 1, false), + new ColumnMetadata("x", BIGINT, 2, false, null, true))))); // table in different catalog SchemaTableName table4 = new SchemaTableName("s2", "t4"); @@ -759,6 +776,13 @@ public class TestAnalyzer ImmutableList.<ColumnMetadata>of( new ColumnMetadata("a", BIGINT, 0, false))))); + // table with a hidden column + SchemaTableName table5 = new SchemaTableName("default", "t5"); + metadata.createTable(SESSION, "tpch", new TableMetadata("tpch", new ConnectorTableMetadata(table5, + ImmutableList.<ColumnMetadata>of( + new ColumnMetadata("a", BIGINT, 0, false), + new ColumnMetadata("b", BIGINT, 1, false, null, true))))); + // valid view referencing table in same schema String viewData1 = JsonCodec.jsonCodec(ViewDefinition.class).toJson( new ViewDefinition("select a from t1", "tpch", "default", ImmutableList.of(
['presto-main/src/main/java/com/facebook/presto/sql/analyzer/StatementAnalyzer.java', 'presto-main/src/test/java/com/facebook/presto/sql/analyzer/TestAnalyzer.java']
{'.java': 2}
2
2
0
0
2
7,396,002
1,472,703
212,584
1,567
306
53
5
1
1,027
144
242
26
0
2
1970-01-01T00:23:42
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
176
prestodb/presto/2250/2211
prestodb
presto
https://github.com/prestodb/presto/issues/2211
https://github.com/prestodb/presto/pull/2250
https://github.com/prestodb/presto/pull/2250#issuecomment-70953284
1
fixes
Bad error message for unhandled
This is caused by an uncategorized error coming from the function (which should be fixed independently), but uncategorized errors should not result in a "compiler failed" error message. ``` presto:tiny> select json_extract_scalar('', ''); Query 20150109_183146_00009_t36py failed: Compiler failed and interpreter is disabled ```
600547872b2207bbe415b4f12bd0be777f1ff870
c35a0ad1c512bdce2409d94f329ac16f5e349580
https://github.com/prestodb/presto/compare/600547872b2207bbe415b4f12bd0be777f1ff870...c35a0ad1c512bdce2409d94f329ac16f5e349580
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/LocalExecutionPlanner.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/LocalExecutionPlanner.java index 0b08a0f343..dd568e9085 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/LocalExecutionPlanner.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/LocalExecutionPlanner.java @@ -772,26 +772,26 @@ public class LocalExecutionPlanner } Map<Symbol, Integer> outputMappings = outputMappingsBuilder.build(); - try { - // compiler uses inputs instead of symbols, so rewrite the expressions first - SymbolToInputRewriter symbolToInputRewriter = new SymbolToInputRewriter(sourceLayout); - Expression rewrittenFilter = ExpressionTreeRewriter.rewriteWith(symbolToInputRewriter, filterExpression); + // compiler uses inputs instead of symbols, so rewrite the expressions first + SymbolToInputRewriter symbolToInputRewriter = new SymbolToInputRewriter(sourceLayout); + Expression rewrittenFilter = ExpressionTreeRewriter.rewriteWith(symbolToInputRewriter, filterExpression); - List<Expression> rewrittenProjections = new ArrayList<>(); - for (Expression projection : projectionExpressions) { - rewrittenProjections.add(ExpressionTreeRewriter.rewriteWith(symbolToInputRewriter, projection)); - } + List<Expression> rewrittenProjections = new ArrayList<>(); + for (Expression projection : projectionExpressions) { + rewrittenProjections.add(ExpressionTreeRewriter.rewriteWith(symbolToInputRewriter, projection)); + } - IdentityHashMap<Expression, Type> expressionTypes = getExpressionTypesFromInput( - context.getSession(), - metadata, - sqlParser, - sourceTypes, - concat(singleton(rewrittenFilter), rewrittenProjections)); + IdentityHashMap<Expression, Type> expressionTypes = getExpressionTypesFromInput( + context.getSession(), + metadata, + sqlParser, + sourceTypes, + concat(singleton(rewrittenFilter), rewrittenProjections)); - RowExpression traslatedFilter = SqlToRowExpressionTranslator.translate(rewrittenFilter, expressionTypes, metadata, session, true); - List<RowExpression> translatedProjections = SqlToRowExpressionTranslator.translate(rewrittenProjections, expressionTypes, metadata, session, true); + RowExpression traslatedFilter = SqlToRowExpressionTranslator.translate(rewrittenFilter, expressionTypes, metadata, session, true); + List<RowExpression> translatedProjections = SqlToRowExpressionTranslator.translate(rewrittenProjections, expressionTypes, metadata, session, true); + try { if (columns != null) { CursorProcessor cursorProcessor = compiler.compileCursorProcessor(traslatedFilter, translatedProjections, sourceNode.getId()); PageProcessor pageProcessor = compiler.compilePageProcessor(traslatedFilter, translatedProjections);
['presto-main/src/main/java/com/facebook/presto/sql/planner/LocalExecutionPlanner.java']
{'.java': 1}
1
1
0
0
1
7,380,033
1,469,172
212,177
1,565
2,489
410
32
1
331
43
74
7
0
1
1970-01-01T00:23:41
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
175
prestodb/presto/2139/2054
prestodb
presto
https://github.com/prestodb/presto/issues/2054
https://github.com/prestodb/presto/pull/2139
https://github.com/prestodb/presto/pull/2139#issuecomment-69245731
2
fixes
DISTINCT fails for JSON type when optimizeHashGeneration=true
``` sql SELECT DISTINCT CAST(ARRAY[1] AS JSON); ``` fails with: ``` com.facebook.presto.spi.PrestoException: Unexpected parameters (json) for function $operator$hash_code. Expected: $operator$hash_code(boolean), $operator$hash_code(bigint), $operator$hash_code(double), $operator$hash_code(varchar), $operator$hash_code(varbinary), $operator$hash_code(date), $operator$hash_code(time), $operator$hash_code(timestamp), $operator$hash_code(interval day to second), $operator$hash_code(interval year to month), $operator$hash_code(time with time zone), $operator$hash_code(timestamp with time zone) at com.facebook.presto.metadata.FunctionRegistry.resolveFunction(FunctionRegistry.java:428) at com.facebook.presto.metadata.MetadataManager.resolveFunction(MetadataManager.java:147) at com.facebook.presto.sql.analyzer.ExpressionAnalyzer$Visitor.visitFunctionCall(ExpressionAnalyzer.java:601) at com.facebook.presto.sql.analyzer.ExpressionAnalyzer$Visitor.visitFunctionCall(ExpressionAnalyzer.java:180) at com.facebook.presto.sql.tree.FunctionCall.accept(FunctionCall.java:67) at com.facebook.presto.sql.tree.AstVisitor.process(AstVisitor.java:24) at com.facebook.presto.sql.analyzer.ExpressionAnalyzer$Visitor.process(ExpressionAnalyzer.java:198) at com.facebook.presto.sql.analyzer.ExpressionAnalyzer$Visitor.visitFunctionCall(ExpressionAnalyzer.java:598) at com.facebook.presto.sql.analyzer.ExpressionAnalyzer$Visitor.visitFunctionCall(ExpressionAnalyzer.java:180) at com.facebook.presto.sql.tree.FunctionCall.accept(FunctionCall.java:67) at com.facebook.presto.sql.analyzer.ExpressionAnalyzer.analyze(ExpressionAnalyzer.java:177) at com.facebook.presto.sql.analyzer.ExpressionAnalyzer.analyzeExpressions(ExpressionAnalyzer.java:928) at com.facebook.presto.sql.analyzer.ExpressionAnalyzer.analyzeExpressionsWithInputs(ExpressionAnalyzer.java:916) at com.facebook.presto.sql.analyzer.ExpressionAnalyzer.getExpressionTypesFromInput(ExpressionAnalyzer.java:877) at com.facebook.presto.sql.analyzer.ExpressionAnalyzer.getExpressionTypesFromInput(ExpressionAnalyzer.java:867) at com.facebook.presto.sql.planner.InterpretedProjectionFunction.<init>(InterpretedProjectionFunction.java:57) at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitScanFilterAndProject(LocalExecutionPlanner.java:852) at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitProject(LocalExecutionPlanner.java:723) at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitProject(LocalExecutionPlanner.java:344) at com.facebook.presto.sql.planner.plan.ProjectNode.accept(ProjectNode.java:81) at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitAggregation(LocalExecutionPlanner.java:648) at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitAggregation(LocalExecutionPlanner.java:344) at com.facebook.presto.sql.planner.plan.AggregationNode.accept(AggregationNode.java:165) at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitOutput(LocalExecutionPlanner.java:367) at com.facebook.presto.sql.planner.LocalExecutionPlanner$Visitor.visitOutput(LocalExecutionPlanner.java:344) at com.facebook.presto.sql.planner.plan.OutputNode.accept(OutputNode.java:79) at com.facebook.presto.sql.planner.LocalExecutionPlanner.plan(LocalExecutionPlanner.java:226) at com.facebook.presto.execution.SqlTaskExecution.<init>(SqlTaskExecution.java:147) at com.facebook.presto.execution.SqlTaskExecution.createSqlTaskExecution(SqlTaskExecution.java:109) at com.facebook.presto.execution.SqlTaskExecutionFactory.create(SqlTaskExecutionFactory.java:101) at com.facebook.presto.execution.SqlTask.updateTask(SqlTask.java:219) at com.facebook.presto.execution.SqlTaskManager.updateTask(SqlTaskManager.java:223) at com.facebook.presto.server.TaskResource.createOrUpdateTask(TaskResource.java:104) at sun.reflect.GeneratedMethodAccessor142.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:151) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:171) at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:152) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:104) at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:387) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:331) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:103) at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:271) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) at org.glassfish.jersey.internal.Errors.process(Errors.java:315) at org.glassfish.jersey.internal.Errors.process(Errors.java:297) at org.glassfish.jersey.internal.Errors.process(Errors.java:267) at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:297) at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:254) at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1030) at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:373) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:381) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221) at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:769) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1667) at org.eclipse.jetty.servlets.UserAgentFilter.doFilter(UserAgentFilter.java:83) at org.eclipse.jetty.servlets.GzipFilter.doFilter(GzipFilter.java:300) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650) at io.airlift.http.server.TraceTokenFilter.doFilter(TraceTokenFilter.java:62) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650) at io.airlift.http.server.TimingFilter.doFilter(TimingFilter.java:51) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650) at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:583) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1125) at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515) at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1059) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97) at org.eclipse.jetty.server.handler.StatisticsHandler.handle(StatisticsHandler.java:159) at org.eclipse.jetty.server.handler.HandlerList.handle(HandlerList.java:52) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97) at org.eclipse.jetty.server.Server.handle(Server.java:485) at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:290) at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:248) at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:606) at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:535) at java.lang.Thread.run(Thread.java:745) ```
3c89a3fc1672ad47c9e8eff950d9d8e37ebe56a6
74c463092f277171c152c965482e0ad71cd2f88e
https://github.com/prestodb/presto/compare/3c89a3fc1672ad47c9e8eff950d9d8e37ebe56a6...74c463092f277171c152c965482e0ad71cd2f88e
diff --git a/presto-main/src/main/java/com/facebook/presto/operator/scalar/JsonOperators.java b/presto-main/src/main/java/com/facebook/presto/operator/scalar/JsonOperators.java index c2551f7bc7..e19fddd773 100644 --- a/presto-main/src/main/java/com/facebook/presto/operator/scalar/JsonOperators.java +++ b/presto-main/src/main/java/com/facebook/presto/operator/scalar/JsonOperators.java @@ -18,6 +18,7 @@ import com.facebook.presto.type.SqlType; import io.airlift.slice.Slice; import static com.facebook.presto.metadata.OperatorType.EQUAL; +import static com.facebook.presto.metadata.OperatorType.HASH_CODE; import static com.facebook.presto.metadata.OperatorType.NOT_EQUAL; public final class JsonOperators @@ -26,6 +27,13 @@ public final class JsonOperators { } + @ScalarOperator(HASH_CODE) + @SqlType(StandardTypes.BIGINT) + public static long hashCode(@SqlType(StandardTypes.JSON) Slice value) + { + return value.hashCode(); + } + @ScalarOperator(EQUAL) @SqlType(StandardTypes.BOOLEAN) public static boolean equals(@SqlType(StandardTypes.JSON) Slice leftJson, @SqlType(StandardTypes.JSON) Slice rightJson)
['presto-main/src/main/java/com/facebook/presto/operator/scalar/JsonOperators.java']
{'.java': 1}
1
1
0
0
1
7,213,635
1,435,720
207,589
1,538
260
58
8
1
8,414
211
1,887
93
0
2
1970-01-01T00:23:39
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
174
prestodb/presto/2098/2095
prestodb
presto
https://github.com/prestodb/presto/issues/2095
https://github.com/prestodb/presto/pull/2098
https://github.com/prestodb/presto/pull/2098#issuecomment-66523147
1
fixes
row_number() with limit filter incorrect when filter contains NOT
The following query: ``` sql SELECT * FROM ( SELECT row_number() OVER () rn FROM (VALUES (0),(0),(0),(0)) ) WHERE NOT rn < 3; ``` produces the following (incorrect) output: ``` rn ---- (0 rows) ``` The correct output should be: ``` rn ---- 3 4 (2 rows) ```
145b5881c237b6c6cba8e20985dc69b461e79c1f
7f331bed914dc2afb8f3358fca214da22cc1b590
https://github.com/prestodb/presto/compare/145b5881c237b6c6cba8e20985dc69b461e79c1f...7f331bed914dc2afb8f3358fca214da22cc1b590
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/WindowFilterPushDown.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/WindowFilterPushDown.java index 85601e9b50..86a9c5e7a3 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/WindowFilterPushDown.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/WindowFilterPushDown.java @@ -111,7 +111,8 @@ public class WindowFilterPushDown if (filter.getLimit().isPresent()) { return filter.getLimit(); } - if (filterContainsWindowFunctions(node, filter.getFilterExpression().get())) { + if (filterContainsWindowFunctions(node, filter.getFilterExpression().get()) && + filter.getFilterExpression().get() instanceof ComparisonExpression) { Symbol rowNumberSymbol = Iterables.getOnlyElement(node.getWindowFunctions().entrySet()).getKey(); return WindowLimitExtractor.extract(filter.getFilterExpression().get(), rowNumberSymbol); } @@ -213,52 +214,56 @@ public class WindowFilterPushDown @Override protected Long visitComparisonExpression(ComparisonExpression node, Symbol rowNumberSymbol) { - QualifiedNameReference reference = extractReference(node); - Literal literal = extractLiteral(node); - if (!Symbol.fromQualifiedName(reference.getName()).equals(rowNumberSymbol)) { + Optional<QualifiedNameReference> reference = extractReference(node); + Optional<Literal> literal = extractLiteral(node); + if (!reference.isPresent() || !literal.isPresent()) { + return null; + } + if (!Symbol.fromQualifiedName(reference.get().getName()).equals(rowNumberSymbol)) { return null; } + long literalValue = extractValue(literal.get()); if (node.getLeft() instanceof QualifiedNameReference && node.getRight() instanceof Literal) { if (node.getType() == ComparisonExpression.Type.LESS_THAN_OR_EQUAL) { - return extractValue(literal); + return literalValue; } if (node.getType() == ComparisonExpression.Type.LESS_THAN) { - return extractValue(literal) - 1; + return literalValue - 1; } } else if (node.getLeft() instanceof Literal && node.getRight() instanceof QualifiedNameReference) { if (node.getType() == ComparisonExpression.Type.GREATER_THAN_OR_EQUAL) { - return extractValue(literal); + return literalValue; } if (node.getType() == ComparisonExpression.Type.GREATER_THAN) { - return extractValue(literal) - 1; + return literalValue - 1; } } return null; } } - private static QualifiedNameReference extractReference(ComparisonExpression expression) + private static Optional<QualifiedNameReference> extractReference(ComparisonExpression expression) { if (expression.getLeft() instanceof QualifiedNameReference) { - return (QualifiedNameReference) expression.getLeft(); + return Optional.of((QualifiedNameReference) expression.getLeft()); } if (expression.getRight() instanceof QualifiedNameReference) { - return (QualifiedNameReference) expression.getRight(); + return Optional.of((QualifiedNameReference) expression.getRight()); } - throw new IllegalArgumentException("Comparison does not have a child of type QualifiedNameReference"); + return Optional.absent(); } - private static Literal extractLiteral(ComparisonExpression expression) + private static Optional<Literal> extractLiteral(ComparisonExpression expression) { if (expression.getLeft() instanceof Literal) { - return (Literal) expression.getLeft(); + return Optional.of((Literal) expression.getLeft()); } if (expression.getRight() instanceof Literal) { - return (Literal) expression.getRight(); + return Optional.of((Literal) expression.getRight()); } - throw new IllegalArgumentException("Comparison does not have a child of type Literal"); + return Optional.absent(); } private static long extractValue(Literal literal) diff --git a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java index 1e130e2abd..16c35dc736 100644 --- a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java +++ b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java @@ -1873,6 +1873,29 @@ public abstract class AbstractTestQueries assertEquals(actual, expected); } + @Test + public void testRowNumberNoOptimization() + throws Exception + { + MaterializedResult actual = computeActual("" + + "SELECT orderkey, orderstatus FROM (\\n" + + " SELECT row_number() OVER () rn, orderkey, orderstatus\\n" + + " FROM orders\\n" + + ") WHERE NOT rn <= 10\\n"); + MaterializedResult all = computeExpected("SELECT orderkey, orderstatus FROM ORDERS", actual.getTypes()); + assertEquals(actual.getMaterializedRows().size(), all.getMaterializedRows().size() - 10); + assertTrue(all.getMaterializedRows().containsAll(actual.getMaterializedRows())); + + actual = computeActual("" + + "SELECT orderkey, orderstatus FROM (\\n" + + " SELECT row_number() OVER () rn, orderkey, orderstatus\\n" + + " FROM orders\\n" + + ") WHERE rn - 5 <= 10\\n"); + all = computeExpected("SELECT orderkey, orderstatus FROM ORDERS", actual.getTypes()); + assertEquals(actual.getMaterializedRows().size(), 15); + assertTrue(all.getMaterializedRows().containsAll(actual.getMaterializedRows())); + } + @Test public void testRowNumberUnpartitionedLimit() throws Exception
['presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/WindowFilterPushDown.java']
{'.java': 2}
2
2
0
0
2
7,168,804
1,426,482
206,205
1,521
2,599
385
37
1
282
48
89
28
0
3
1970-01-01T00:23:38
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
196
prestodb/presto/5921/5797
prestodb
presto
https://github.com/prestodb/presto/issues/5797
https://github.com/prestodb/presto/pull/5921
https://github.com/prestodb/presto/pull/5921
1
fixes
Fix SHOW CREATE TABLE for Raptor
`RaptorMetadata.getTableMetadata()` does not include table properties, so`SHOW CREATE TABLE` does not include them. We want to make as few database calls as possible. These are the properties we need: - `ordering`: could be added to `TableColumn` - `temporal_column`: could be added to `TableColumn` - `bucket_count`: already in `RaptorTableHandle` - `bucketed_on`: could be added to `TableColumn` - `distribution_name`: could be added to `RaptorTableHandle` along with `distributionId` (seems ugly to put it in the handle, but the handle already has the schema/table name just for this metadata call)
7b47e32a25523c4a83e51ccf8edcfd29567c109e
b0ff6a9771963aabaf58062c74511ab38364cbd1
https://github.com/prestodb/presto/compare/7b47e32a25523c4a83e51ccf8edcfd29567c109e...b0ff6a9771963aabaf58062c74511ab38364cbd1
diff --git a/presto-raptor/src/main/java/com/facebook/presto/raptor/RaptorMetadata.java b/presto-raptor/src/main/java/com/facebook/presto/raptor/RaptorMetadata.java index dd0d772d46..073c7b61c3 100644 --- a/presto-raptor/src/main/java/com/facebook/presto/raptor/RaptorMetadata.java +++ b/presto-raptor/src/main/java/com/facebook/presto/raptor/RaptorMetadata.java @@ -39,6 +39,7 @@ import com.facebook.presto.spi.Constraint; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.SchemaTableName; import com.facebook.presto.spi.SchemaTablePrefix; +import com.facebook.presto.spi.TableNotFoundException; import com.facebook.presto.spi.ViewNotFoundException; import com.facebook.presto.spi.connector.ConnectorMetadata; import com.facebook.presto.spi.connector.ConnectorPartitioningHandle; @@ -65,6 +66,8 @@ import java.util.Optional; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.Set; +import java.util.SortedMap; +import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Predicate; @@ -83,6 +86,8 @@ import static com.facebook.presto.raptor.RaptorSessionProperties.getOneSplitPerB import static com.facebook.presto.raptor.RaptorTableProperties.BUCKETED_ON_PROPERTY; import static com.facebook.presto.raptor.RaptorTableProperties.BUCKET_COUNT_PROPERTY; import static com.facebook.presto.raptor.RaptorTableProperties.DISTRIBUTION_NAME_PROPERTY; +import static com.facebook.presto.raptor.RaptorTableProperties.ORDERING_PROPERTY; +import static com.facebook.presto.raptor.RaptorTableProperties.TEMPORAL_COLUMN_PROPERTY; import static com.facebook.presto.raptor.RaptorTableProperties.getBucketColumns; import static com.facebook.presto.raptor.RaptorTableProperties.getBucketCount; import static com.facebook.presto.raptor.RaptorTableProperties.getDistributionName; @@ -175,6 +180,7 @@ public class RaptorMetadata tableName.getTableName(), table.getTableId(), table.getDistributionId(), + table.getDistributionName(), table.getBucketCount(), OptionalLong.empty(), Optional.ofNullable(sampleWeightColumnHandle), @@ -186,17 +192,41 @@ public class RaptorMetadata { RaptorTableHandle handle = checkType(tableHandle, RaptorTableHandle.class, "tableHandle"); SchemaTableName tableName = new SchemaTableName(handle.getSchemaName(), handle.getTableName()); - List<ColumnMetadata> columns = dao.listTableColumns(handle.getTableId()).stream() + List<TableColumn> tableColumns = dao.listTableColumns(handle.getTableId()); + if (tableColumns.isEmpty()) { + throw new TableNotFoundException(tableName); + } + + ImmutableMap.Builder<String, Object> properties = ImmutableMap.builder(); + SortedMap<Integer, String> bucketing = new TreeMap<>(); + SortedMap<Integer, String> ordering = new TreeMap<>(); + + for (TableColumn column : tableColumns) { + if (column.isTemporal()) { + properties.put(TEMPORAL_COLUMN_PROPERTY, column.getColumnName()); + } + column.getBucketOrdinal().ifPresent(bucketOrdinal -> bucketing.put(bucketOrdinal, column.getColumnName())); + column.getSortOrdinal().ifPresent(sortOrdinal -> ordering.put(sortOrdinal, column.getColumnName())); + } + + if (!bucketing.isEmpty()) { + properties.put(BUCKETED_ON_PROPERTY, ImmutableList.copyOf(bucketing.values())); + } + if (!ordering.isEmpty()) { + properties.put(ORDERING_PROPERTY, ImmutableList.copyOf(ordering.values())); + } + + handle.getBucketCount().ifPresent(bucketCount -> properties.put(BUCKET_COUNT_PROPERTY, bucketCount)); + handle.getDistributionName().ifPresent(distributionName -> properties.put(DISTRIBUTION_NAME_PROPERTY, distributionName)); + + List<ColumnMetadata> columns = tableColumns.stream() .map(TableColumn::toColumnMetadata) .filter(isSampleWeightColumn().negate()) .collect(toCollection(ArrayList::new)); - if (columns.isEmpty()) { - throw new PrestoException(RAPTOR_ERROR, "Table does not have any columns: " + tableName); - } columns.add(hiddenColumn(SHARD_UUID_COLUMN_NAME, SHARD_UUID_COLUMN_TYPE)); columns.add(hiddenColumn(BUCKET_NUMBER_COLUMN_NAME, INTEGER)); - return new ConnectorTableMetadata(tableName, columns); + return new ConnectorTableMetadata(tableName, columns, properties.build()); } @Override @@ -694,6 +724,7 @@ public class RaptorMetadata handle.getTableName(), handle.getTableId(), handle.getDistributionId(), + handle.getDistributionName(), handle.getBucketCount(), OptionalLong.of(transactionId), handle.getSampleWeightColumnHandle(), diff --git a/presto-raptor/src/main/java/com/facebook/presto/raptor/RaptorTableHandle.java b/presto-raptor/src/main/java/com/facebook/presto/raptor/RaptorTableHandle.java index eb07641671..14893812cc 100644 --- a/presto-raptor/src/main/java/com/facebook/presto/raptor/RaptorTableHandle.java +++ b/presto-raptor/src/main/java/com/facebook/presto/raptor/RaptorTableHandle.java @@ -35,6 +35,7 @@ public final class RaptorTableHandle private final String tableName; private final long tableId; private final OptionalLong distributionId; + private final Optional<String> distributionName; private final OptionalInt bucketCount; private final OptionalLong transactionId; private final Optional<RaptorColumnHandle> sampleWeightColumnHandle; @@ -47,6 +48,7 @@ public final class RaptorTableHandle @JsonProperty("tableName") String tableName, @JsonProperty("tableId") long tableId, @JsonProperty("distributionId") OptionalLong distributionId, + @JsonProperty("distributionName") Optional<String> distributionName, @JsonProperty("bucketCount") OptionalInt bucketCount, @JsonProperty("transactionId") OptionalLong transactionId, @JsonProperty("sampleWeightColumnHandle") Optional<RaptorColumnHandle> sampleWeightColumnHandle, @@ -60,6 +62,7 @@ public final class RaptorTableHandle this.tableId = tableId; this.sampleWeightColumnHandle = requireNonNull(sampleWeightColumnHandle, "sampleWeightColumnHandle is null"); + this.distributionName = requireNonNull(distributionName, "distributionName is null"); this.distributionId = requireNonNull(distributionId, "distributionId is null"); this.bucketCount = requireNonNull(bucketCount, "bucketCount is null"); this.transactionId = requireNonNull(transactionId, "transactionId is null"); @@ -97,6 +100,12 @@ public final class RaptorTableHandle return distributionId; } + @JsonProperty + public Optional<String> getDistributionName() + { + return distributionName; + } + @JsonProperty public OptionalInt getBucketCount() { diff --git a/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/MetadataDao.java b/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/MetadataDao.java index 03129a950e..46896a6584 100644 --- a/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/MetadataDao.java +++ b/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/MetadataDao.java @@ -27,7 +27,10 @@ import java.util.Set; public interface MetadataDao { String TABLE_COLUMN_SELECT = "" + - "SELECT t.schema_name, t.table_name, c.column_id, c.column_name, c.data_type\\n" + + "SELECT t.schema_name, t.table_name,\\n" + + " c.column_id, c.column_name, c.data_type,\\n" + + " c.bucket_ordinal_position, c.sort_ordinal_position,\\n" + + " t.temporal_column_id = c.column_id AS temporal\\n" + "FROM tables t\\n" + "JOIN columns c ON (t.table_id = c.table_id)\\n"; @@ -38,7 +41,7 @@ public interface MetadataDao @Mapper(TableMapper.class) Table getTableInformation(@Bind("tableId") long tableId); - @SqlQuery("SELECT t.table_id, t.distribution_id, d.bucket_count, t.temporal_column_id\\n" + + @SqlQuery("SELECT t.table_id, t.distribution_id, d.distribution_name, d.bucket_count, t.temporal_column_id\\n" + "FROM tables t\\n" + "LEFT JOIN distributions d ON (t.distribution_id = d.distribution_id)\\n" + "WHERE t.schema_name = :schemaName\\n" + diff --git a/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/Table.java b/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/Table.java index 0bb855737f..26077c42af 100644 --- a/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/Table.java +++ b/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/Table.java @@ -18,6 +18,7 @@ import org.skife.jdbi.v2.tweak.ResultSetMapper; import java.sql.ResultSet; import java.sql.SQLException; +import java.util.Optional; import java.util.OptionalInt; import java.util.OptionalLong; @@ -30,13 +31,15 @@ public final class Table { private final long tableId; private final OptionalLong distributionId; + private final Optional<String> distributionName; private final OptionalInt bucketCount; private final OptionalLong temporalColumnId; - public Table(long tableId, OptionalLong distributionId, OptionalInt bucketCount, OptionalLong temporalColumnId) + public Table(long tableId, OptionalLong distributionId, Optional<String> distributionName, OptionalInt bucketCount, OptionalLong temporalColumnId) { this.tableId = tableId; this.distributionId = requireNonNull(distributionId, "distributionId is null"); + this.distributionName = requireNonNull(distributionName, "distributionName is null"); this.bucketCount = requireNonNull(bucketCount, "bucketCount is null"); this.temporalColumnId = requireNonNull(temporalColumnId, "temporalColumnId is null"); } @@ -51,6 +54,11 @@ public final class Table return distributionId; } + public Optional<String> getDistributionName() + { + return distributionName; + } + public OptionalInt getBucketCount() { return bucketCount; @@ -83,6 +91,7 @@ public final class Table return new Table( r.getLong("table_id"), getOptionalLong(r, "distribution_id"), + Optional.ofNullable(r.getString("distribution_name")), getOptionalInt(r, "bucket_count"), getOptionalLong(r, "temporal_column_id")); } diff --git a/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/TableColumn.java b/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/TableColumn.java index 8da00a4e08..a53f575f37 100644 --- a/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/TableColumn.java +++ b/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/TableColumn.java @@ -24,7 +24,9 @@ import javax.inject.Inject; import java.sql.ResultSet; import java.sql.SQLException; +import java.util.OptionalInt; +import static com.facebook.presto.raptor.util.DatabaseUtil.getOptionalInt; import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Preconditions.checkArgument; @@ -36,13 +38,19 @@ public class TableColumn private final String columnName; private final Type dataType; private final long columnId; + private final OptionalInt bucketOrdinal; + private final OptionalInt sortOrdinal; + private final boolean temporal; - public TableColumn(SchemaTableName table, String columnName, Type dataType, long columnId) + public TableColumn(SchemaTableName table, String columnName, Type dataType, long columnId, OptionalInt bucketOrdinal, OptionalInt sortOrdinal, boolean temporal) { this.table = requireNonNull(table, "table is null"); this.columnName = requireNonNull(columnName, "columnName is null"); this.dataType = requireNonNull(dataType, "dataType is null"); this.columnId = columnId; + this.bucketOrdinal = requireNonNull(bucketOrdinal, "bucketOrdinal is null"); + this.sortOrdinal = requireNonNull(sortOrdinal, "sortOrdinal is null"); + this.temporal = temporal; } public SchemaTableName getTable() @@ -65,6 +73,21 @@ public class TableColumn return columnId; } + public OptionalInt getBucketOrdinal() + { + return bucketOrdinal; + } + + public OptionalInt getSortOrdinal() + { + return sortOrdinal; + } + + public boolean isTemporal() + { + return temporal; + } + @Override public String toString() { @@ -113,7 +136,10 @@ public class TableColumn table, r.getString("column_name"), type, - r.getLong("column_id")); + r.getLong("column_id"), + getOptionalInt(r, "bucket_ordinal_position"), + getOptionalInt(r, "sort_ordinal_position"), + r.getBoolean("temporal")); } } } diff --git a/presto-raptor/src/test/java/com/facebook/presto/raptor/TestRaptorIntegrationSmokeTest.java b/presto-raptor/src/test/java/com/facebook/presto/raptor/TestRaptorIntegrationSmokeTest.java index 301b23ebe1..93c8362c45 100644 --- a/presto-raptor/src/test/java/com/facebook/presto/raptor/TestRaptorIntegrationSmokeTest.java +++ b/presto-raptor/src/test/java/com/facebook/presto/raptor/TestRaptorIntegrationSmokeTest.java @@ -346,7 +346,15 @@ public class TestRaptorIntegrationSmokeTest " c2 double,\\n" + " \\"c 3\\" varchar,\\n" + " \\"c'4\\" array(bigint),\\n" + - " c5 map(bigint, varchar)\\n" + + " c5 map(bigint, varchar),\\n" + + " c6 bigint,\\n" + + " c7 timestamp\\n" + + ")\\n" + + "WITH (\\n" + + " bucket_count = 32,\\n" + + " bucketed_on = ARRAY['c1','c6'],\\n" + + " ordering = ARRAY['c6','c1'],\\n" + + " temporal_column = 'c7'\\n" + ")", getSession().getCatalog().get(), getSession().getSchema().get(), "test_show_create_table"); assertUpdate(createTableSql); diff --git a/presto-raptor/src/test/java/com/facebook/presto/raptor/metadata/TestRaptorMetadata.java b/presto-raptor/src/test/java/com/facebook/presto/raptor/metadata/TestRaptorMetadata.java index 7ece09444c..4ab99af548 100644 --- a/presto-raptor/src/test/java/com/facebook/presto/raptor/metadata/TestRaptorMetadata.java +++ b/presto-raptor/src/test/java/com/facebook/presto/raptor/metadata/TestRaptorMetadata.java @@ -204,8 +204,8 @@ public class TestRaptorMetadata // verify sort columns List<TableColumn> sortColumns = metadataDao.listSortColumns(tableId); assertTableColumnsEqual(sortColumns, ImmutableList.of( - new TableColumn(DEFAULT_TEST_ORDERS, "orderdate", DATE, 4), - new TableColumn(DEFAULT_TEST_ORDERS, "custkey", BIGINT, 2))); + new TableColumn(DEFAULT_TEST_ORDERS, "orderdate", DATE, 4, OptionalInt.empty(), OptionalInt.of(0), true), + new TableColumn(DEFAULT_TEST_ORDERS, "custkey", BIGINT, 2, OptionalInt.empty(), OptionalInt.of(1), false))); // verify temporal column assertEquals(metadataDao.getTemporalColumnId(tableId), Long.valueOf(4)); @@ -231,8 +231,8 @@ public class TestRaptorMetadata MetadataDao metadataDao = dbi.onDemand(MetadataDao.class); assertTableColumnsEqual(metadataDao.listBucketColumns(tableId), ImmutableList.of( - new TableColumn(DEFAULT_TEST_ORDERS, "custkey", BIGINT, 2), - new TableColumn(DEFAULT_TEST_ORDERS, "orderkey", BIGINT, 1))); + new TableColumn(DEFAULT_TEST_ORDERS, "custkey", BIGINT, 2, OptionalInt.of(0), OptionalInt.empty(), false), + new TableColumn(DEFAULT_TEST_ORDERS, "orderkey", BIGINT, 1, OptionalInt.of(1), OptionalInt.empty(), false))); assertEquals(raptorTableHandle.getBucketCount(), OptionalInt.of(16)); @@ -274,8 +274,8 @@ public class TestRaptorMetadata MetadataDao metadataDao = dbi.onDemand(MetadataDao.class); assertTableColumnsEqual(metadataDao.listBucketColumns(tableId), ImmutableList.of( - new TableColumn(DEFAULT_TEST_ORDERS, "orderkey", BIGINT, 1), - new TableColumn(DEFAULT_TEST_ORDERS, "custkey", BIGINT, 2))); + new TableColumn(DEFAULT_TEST_ORDERS, "orderkey", BIGINT, 1, OptionalInt.of(0), OptionalInt.empty(), false), + new TableColumn(DEFAULT_TEST_ORDERS, "custkey", BIGINT, 2, OptionalInt.of(1), OptionalInt.empty(), false))); assertEquals(raptorTableHandle.getBucketCount(), OptionalInt.of(32)); @@ -306,7 +306,7 @@ public class TestRaptorMetadata assertEquals(raptorTableHandle.getTableId(), 1); assertTableColumnsEqual(metadataDao.listBucketColumns(tableId), ImmutableList.of( - new TableColumn(DEFAULT_TEST_ORDERS, "orderkey", BIGINT, 1))); + new TableColumn(DEFAULT_TEST_ORDERS, "orderkey", BIGINT, 1, OptionalInt.of(0), OptionalInt.empty(), false))); assertEquals(raptorTableHandle.getBucketCount(), OptionalInt.of(16)); @@ -329,7 +329,7 @@ public class TestRaptorMetadata assertEquals(tableId, 2); assertTableColumnsEqual(metadataDao.listBucketColumns(tableId), ImmutableList.of( - new TableColumn(DEFAULT_TEST_LINEITEMS, "orderkey", BIGINT, 1))); + new TableColumn(DEFAULT_TEST_LINEITEMS, "orderkey", BIGINT, 1, OptionalInt.of(0), OptionalInt.empty(), false))); assertEquals(raptorTableHandle.getBucketCount(), OptionalInt.of(16)); @@ -386,8 +386,8 @@ public class TestRaptorMetadata // verify sort columns List<TableColumn> sortColumns = metadataDao.listSortColumns(tableId); assertTableColumnsEqual(sortColumns, ImmutableList.of( - new TableColumn(DEFAULT_TEST_ORDERS, "orderdate", DATE, 4), - new TableColumn(DEFAULT_TEST_ORDERS, "custkey", BIGINT, 2))); + new TableColumn(DEFAULT_TEST_ORDERS, "orderdate", DATE, 4, OptionalInt.empty(), OptionalInt.of(0), false), + new TableColumn(DEFAULT_TEST_ORDERS, "custkey", BIGINT, 2, OptionalInt.empty(), OptionalInt.of(1), false))); // verify temporal column is not set assertEquals(metadataDao.getTemporalColumnId(tableId), null); @@ -723,6 +723,9 @@ public class TestRaptorMetadata assertEquals(actual.getColumnId(), expected.getColumnId()); assertEquals(actual.getColumnName(), expected.getColumnName()); assertEquals(actual.getDataType(), expected.getDataType()); + assertEquals(actual.getBucketOrdinal(), expected.getBucketOrdinal()); + assertEquals(actual.getSortOrdinal(), expected.getSortOrdinal()); + assertEquals(actual.isTemporal(), expected.isTemporal()); } private static void assertTableColumnsEqual(List<TableColumn> actual, List<TableColumn> expected) diff --git a/presto-raptor/src/test/java/com/facebook/presto/raptor/storage/organization/TestCompactionSetCreator.java b/presto-raptor/src/test/java/com/facebook/presto/raptor/storage/organization/TestCompactionSetCreator.java index 1c180a4f3f..b4e55569db 100644 --- a/presto-raptor/src/test/java/com/facebook/presto/raptor/storage/organization/TestCompactionSetCreator.java +++ b/presto-raptor/src/test/java/com/facebook/presto/raptor/storage/organization/TestCompactionSetCreator.java @@ -39,10 +39,10 @@ public class TestCompactionSetCreator { private static final long MAX_SHARD_ROWS = 100; private static final DataSize MAX_SHARD_SIZE = new DataSize(100, DataSize.Unit.BYTE); - private static final Table tableInfo = new Table(1L, OptionalLong.empty(), OptionalInt.empty(), OptionalLong.empty()); - private static final Table temporalTableInfo = new Table(1L, OptionalLong.empty(), OptionalInt.empty(), OptionalLong.of(1)); - private static final Table bucketedTableInfo = new Table(1L, OptionalLong.empty(), OptionalInt.of(3), OptionalLong.empty()); - private static final Table bucketedTemporalTableInfo = new Table(1L, OptionalLong.empty(), OptionalInt.of(3), OptionalLong.of(1)); + private static final Table tableInfo = new Table(1L, OptionalLong.empty(), Optional.empty(), OptionalInt.empty(), OptionalLong.empty()); + private static final Table temporalTableInfo = new Table(1L, OptionalLong.empty(), Optional.empty(), OptionalInt.empty(), OptionalLong.of(1)); + private static final Table bucketedTableInfo = new Table(1L, OptionalLong.empty(), Optional.empty(), OptionalInt.of(3), OptionalLong.empty()); + private static final Table bucketedTemporalTableInfo = new Table(1L, OptionalLong.empty(), Optional.empty(), OptionalInt.of(3), OptionalLong.of(1)); private final CompactionSetCreator compactionSetCreator = new CompactionSetCreator(MAX_SHARD_SIZE, MAX_SHARD_ROWS); diff --git a/presto-raptor/src/test/java/com/facebook/presto/raptor/storage/organization/TestShardOrganizationManager.java b/presto-raptor/src/test/java/com/facebook/presto/raptor/storage/organization/TestShardOrganizationManager.java index 36dfdb031b..c3be167003 100644 --- a/presto-raptor/src/test/java/com/facebook/presto/raptor/storage/organization/TestShardOrganizationManager.java +++ b/presto-raptor/src/test/java/com/facebook/presto/raptor/storage/organization/TestShardOrganizationManager.java @@ -56,8 +56,8 @@ public class TestShardOrganizationManager private MetadataDao metadataDao; private ShardOrganizerDao organizerDao; - private static final Table tableInfo = new Table(1L, OptionalLong.empty(), OptionalInt.empty(), OptionalLong.empty()); - private static final Table temporalTableInfo = new Table(1L, OptionalLong.empty(), OptionalInt.empty(), OptionalLong.of(1)); + private static final Table tableInfo = new Table(1L, OptionalLong.empty(), Optional.empty(), OptionalInt.empty(), OptionalLong.empty()); + private static final Table temporalTableInfo = new Table(1L, OptionalLong.empty(), Optional.empty(), OptionalInt.empty(), OptionalLong.of(1)); private static final List<Type> types = ImmutableList.of(BIGINT, VARCHAR, DATE, TIMESTAMP);
['presto-raptor/src/test/java/com/facebook/presto/raptor/TestRaptorIntegrationSmokeTest.java', 'presto-raptor/src/main/java/com/facebook/presto/raptor/RaptorTableHandle.java', 'presto-raptor/src/test/java/com/facebook/presto/raptor/storage/organization/TestCompactionSetCreator.java', 'presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/MetadataDao.java', 'presto-raptor/src/test/java/com/facebook/presto/raptor/storage/organization/TestShardOrganizationManager.java', 'presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/TableColumn.java', 'presto-raptor/src/test/java/com/facebook/presto/raptor/metadata/TestRaptorMetadata.java', 'presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/Table.java', 'presto-raptor/src/main/java/com/facebook/presto/raptor/RaptorMetadata.java']
{'.java': 9}
9
9
0
0
9
12,368,463
2,456,139
344,263
2,518
4,950
952
98
5
603
86
142
9
0
0
1970-01-01T00:24:31
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
192
prestodb/presto/6195/6191
prestodb
presto
https://github.com/prestodb/presto/issues/6191
https://github.com/prestodb/presto/pull/6195
https://github.com/prestodb/presto/pull/6195
1
fixes
Distinct sum aggregation may produce incorrect results for empty grouping sets
`AbstractTestQueries::testGroupingSetsWithMultipleDistinctAndUnion` fails for some configurations with `task_concurrency` higher then 1: ``` SELECT linenumber, COUNT(DISTINCT linenumber), SUM(DISTINCT suppkey) FROM (SELECT * FROM lineitem WHERE linenumber%2 = 0 UNION ALL SELECT * FROM lineitem WHERE linenumber%2 = 1) GROUP BY GROUPING SETS ((linenumber), ()) not equal Actual 8 rows: [3, 1, 5050] [null, 7, 30300] [7, 1, 5050] [1, 1, 5050] [4, 1, 5050] [6, 1, 5050] [5, 1, 5050] [2, 1, 5050] Expected 8 rows: [1, 1, 5050] [2, 1, 5050] [3, 1, 5050] [4, 1, 5050] [5, 1, 5050] [6, 1, 5050] [7, 1, 5050] [null, 7, 5050] ``` Simplified query: ``` > set session task_concurrency=8; > SELECT a, SUM(DISTINCT b) FROM (SELECT * FROM (VALUES (0,1), (0,2)) t(a,b) UNION ALL SELECT * FROM (VALUES (1,1), (1,2)) t(a,b)) GROUP BY GROUPING SETS ((a), ()); a | _col1 ------+------- 0 | 3 NULL | 6 1 | 3 ``` To reproduce this, number of workers must be greater then 1, task_concurrency must be greater then 1, query must contain an empty grouping set AND there must be union AND aggregation function must be sum distinct. It seems like multiple partial aggregations of empty grouping set are incorrectly combined in final aggregation, effectively multiplying result. CC @kokosing
815f8796c7e8cef625fd16c44608116b9c66700b
d95e3496631a0467c27ccc93beed01415cf065b6
https://github.com/prestodb/presto/compare/815f8796c7e8cef625fd16c44608116b9c66700b...d95e3496631a0467c27ccc93beed01415cf065b6
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PropertyDerivations.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PropertyDerivations.java index 474dd52bbc..0d8aa9d9a5 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PropertyDerivations.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PropertyDerivations.java @@ -222,9 +222,7 @@ class PropertyDerivations @Override public ActualProperties visitGroupId(GroupIdNode node, List<ActualProperties> inputProperties) { - ActualProperties properties = Iterables.getOnlyElement(inputProperties); - - return properties.translate(translateGroupIdSymbols(node)); + return Iterables.getOnlyElement(inputProperties).translate(translateGroupIdSymbols(node)); } private Function<Symbol, Optional<Symbol>> translateGroupIdSymbols(GroupIdNode node) diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/StreamPropertyDerivations.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/StreamPropertyDerivations.java index 867ed6a2af..cdcc0f0231 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/StreamPropertyDerivations.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/StreamPropertyDerivations.java @@ -291,6 +291,28 @@ final class StreamPropertyDerivations return inputToOutput; } + @Override + public StreamProperties visitGroupId(GroupIdNode node, List<StreamProperties> inputProperties) + { + return Iterables.getOnlyElement(inputProperties).translate(translateGroupIdSymbols(node)); + } + + private Function<Symbol, Optional<Symbol>> translateGroupIdSymbols(GroupIdNode node) + { + List<Symbol> commonGroupingColumns = node.getCommonGroupingColumns(); + return symbol -> { + if (node.getIdentityMappings().containsKey(symbol)) { + return Optional.of(node.getIdentityMappings().get(symbol)); + } + + if (commonGroupingColumns.contains(symbol)) { + return Optional.of(symbol); + } + + return Optional.empty(); + }; + } + @Override public StreamProperties visitAggregation(AggregationNode node, List<StreamProperties> inputProperties) { @@ -392,12 +414,6 @@ final class StreamPropertyDerivations return Iterables.getOnlyElement(inputProperties); } - @Override - public StreamProperties visitGroupId(GroupIdNode node, List<StreamProperties> inputProperties) - { - return Iterables.getOnlyElement(inputProperties); - } - @Override public StreamProperties visitWindow(WindowNode node, List<StreamProperties> inputProperties) { diff --git a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java index 7fe4713525..afd7562503 100644 --- a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java +++ b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java @@ -1590,6 +1590,17 @@ public abstract class AbstractTestQueries @Test public void testGroupingSetsWithSingleDistinctAndUnion() throws Exception + { + assertQuery("SELECT suppkey, COUNT(DISTINCT linenumber) FROM " + + "(SELECT * FROM lineitem WHERE linenumber%2 = 0 UNION ALL SELECT * FROM lineitem WHERE linenumber%2 = 1) " + + "GROUP BY GROUPING SETS ((suppkey), ())", + "SELECT suppkey, COUNT(DISTINCT linenumber) FROM lineitem GROUP BY suppkey UNION ALL " + + "SELECT NULL, COUNT(DISTINCT linenumber) FROM lineitem"); + } + + @Test + public void testGroupingSetsWithSingleDistinctAndUnionGroupedArguments() + throws Exception { assertQuery("SELECT linenumber, COUNT(DISTINCT linenumber) FROM " + "(SELECT * FROM lineitem WHERE linenumber%2 = 0 UNION ALL SELECT * FROM lineitem WHERE linenumber%2 = 1) " +
['presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/StreamPropertyDerivations.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PropertyDerivations.java', 'presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java']
{'.java': 3}
3
3
0
0
3
12,639,513
2,508,751
351,271
2,556
1,321
218
32
2
1,365
205
467
41
0
2
1970-01-01T00:24:34
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
216
prestodb/presto/1992/1991
prestodb
presto
https://github.com/prestodb/presto/issues/1991
https://github.com/prestodb/presto/pull/1992
https://github.com/prestodb/presto/pull/1992
1
fixes
Query input rows/size stats not tracked properly for JOIN queries
The query-level stats only include the row/size from the leaf stage. The should include the inputs for all stages that perform table scans. For example: ``` 1:20 [ 130M rows, 14.1GB] [1.64M rows/s, 182MB/s] [ <=> ] STAGES ROWS ROWS/s BYTES BYTES/s QUEUED RUN DONE 0.........R 0 0 0B 0B 0 1 0 1.......R 0 0 0B 0B 0 20 0 2.....S 13B 163M 1.82T 23.4G 1478 8870 27560 3...F 43.1M 0 2.38G 0B 0 0 20 4.F 130M 0 14.1G 0B 0 0 2363 ``` The bug is possibly due to the following check in `QueryStateMachine.getQueryInfo()`, line 193: ``` java if (stageInfo.getSubStages().isEmpty()) { ```
70ff6bac3ae6b4f2c91555c0e52121021eb313d9
8dd30570a1d8e40f0a267fcb6b02230dd58eb185
https://github.com/prestodb/presto/compare/70ff6bac3ae6b4f2c91555c0e52121021eb313d9...8dd30570a1d8e40f0a267fcb6b02230dd58eb185
diff --git a/presto-main/src/main/java/com/facebook/presto/execution/QueryStateMachine.java b/presto-main/src/main/java/com/facebook/presto/execution/QueryStateMachine.java index b909d8c410..67578efa87 100644 --- a/presto-main/src/main/java/com/facebook/presto/execution/QueryStateMachine.java +++ b/presto-main/src/main/java/com/facebook/presto/execution/QueryStateMachine.java @@ -19,12 +19,14 @@ import com.facebook.presto.client.FailureInfo; import com.facebook.presto.execution.StateMachine.StateChangeListener; import com.facebook.presto.spi.ErrorCode; import com.facebook.presto.spi.PrestoException; +import com.facebook.presto.sql.planner.plan.TableScanNode; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; import io.airlift.log.Logger; import io.airlift.units.DataSize; import io.airlift.units.Duration; @@ -190,7 +192,7 @@ public class QueryStateMachine totalUserTime += stageStats.getTotalUserTime().roundTo(NANOSECONDS); totalBlockedTime += stageStats.getTotalBlockedTime().roundTo(NANOSECONDS); - if (stageInfo.getSubStages().isEmpty()) { + if (Iterables.any(stageInfo.getPlan().getSources(), Predicates.instanceOf(TableScanNode.class))) { rawInputDataSize += stageStats.getRawInputDataSize().toBytes(); rawInputPositions += stageStats.getRawInputPositions();
['presto-main/src/main/java/com/facebook/presto/execution/QueryStateMachine.java']
{'.java': 1}
1
1
0
0
1
7,093,901
1,409,001
205,067
1,495
279
59
4
1
803
105
293
21
0
2
1970-01-01T00:23:36
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
215
prestodb/presto/2271/1696
prestodb
presto
https://github.com/prestodb/presto/issues/1696
https://github.com/prestodb/presto/pull/2271
https://github.com/prestodb/presto/pull/2271
1
fixes
Compilation for try_cast is broken
The exception handling is completely broken because exceptions clear the stack. It needs to be in a separate method. This query reproduces it: ``` select concat('foo', try_cast(x as varchar)) from (values (1)) a (x); ``` Exception: ``` java.lang.VerifyError: Instruction type does not match stack map ```
6ce854ea9f07006ff509ec9db6eca11f3212c45c
90348e394c04387e3c68c0b94d401fbbf99d5952
https://github.com/prestodb/presto/compare/6ce854ea9f07006ff509ec9db6eca11f3212c45c...90348e394c04387e3c68c0b94d401fbbf99d5952
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/gen/ByteCodeUtils.java b/presto-main/src/main/java/com/facebook/presto/sql/gen/ByteCodeUtils.java index 468704ffe1..2cb18b820d 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/gen/ByteCodeUtils.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/gen/ByteCodeUtils.java @@ -152,7 +152,8 @@ public final class ByteCodeUtils MethodType methodType = binding.getType(); Signature signature = function.getSignature(); - Class<?> unboxedReturnType = Primitives.unwrap(methodType.returnType()); + Class<?> returnType = methodType.returnType(); + Class<?> unboxedReturnType = Primitives.unwrap(returnType); LabelNode end = new LabelNode("end"); Block block = new Block(context) @@ -181,23 +182,35 @@ public final class ByteCodeUtils block.append(invoke(context, binding, function.getSignature())); if (function.isNullable()) { - if (unboxedReturnType.isPrimitive() && unboxedReturnType != void.class) { - LabelNode notNull = new LabelNode("notNull"); - block.dup(methodType.returnType()) - .ifNotNullGoto(notNull) - .putVariable("wasNull", true) - .comment("swap boxed null with unboxed default") - .pop(methodType.returnType()) - .pushJavaDefault(unboxedReturnType) - .gotoLabel(end) - .visitLabel(notNull) - .append(unboxPrimitive(context, unboxedReturnType)); - } - else { - block.dup(methodType.returnType()) - .ifNotNullGoto(end) - .putVariable("wasNull", true); - } + block.append(unboxPrimitiveIfNecessary(context, returnType)); + } + block.visitLabel(end); + + return block; + } + + public static Block unboxPrimitiveIfNecessary(CompilerContext context, Class<?> boxedType) + { + Block block = new Block(context); + LabelNode end = new LabelNode("end"); + Class<?> unboxedType = Primitives.unwrap(boxedType); + + if (unboxedType.isPrimitive() && unboxedType != void.class) { + LabelNode notNull = new LabelNode("notNull"); + block.dup(boxedType) + .ifNotNullGoto(notNull) + .putVariable("wasNull", true) + .comment("swap boxed null with unboxed default") + .pop(boxedType) + .pushJavaDefault(unboxedType) + .gotoLabel(end) + .visitLabel(notNull) + .append(unboxPrimitive(context, unboxedType)); + } + else { + block.dup(boxedType) + .ifNotNullGoto(end) + .putVariable("wasNull", true); } block.visitLabel(end); diff --git a/presto-main/src/main/java/com/facebook/presto/sql/gen/CompilerOperations.java b/presto-main/src/main/java/com/facebook/presto/sql/gen/CompilerOperations.java index c0d534724b..0f91ebca5f 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/gen/CompilerOperations.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/gen/CompilerOperations.java @@ -59,14 +59,6 @@ public final class CompilerOperations return left > right; } - public static void propagateInterruptedException(Throwable throwable) - { - if (throwable instanceof InterruptedException) { - Thread.currentThread().interrupt(); - throw new RuntimeException(throwable); - } - } - public static boolean in(Object value, Set<?> set) { return set.contains(value); diff --git a/presto-main/src/main/java/com/facebook/presto/sql/gen/TryCastCodeGenerator.java b/presto-main/src/main/java/com/facebook/presto/sql/gen/TryCastCodeGenerator.java index 8c74c604c5..b09c3a3f8d 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/gen/TryCastCodeGenerator.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/gen/TryCastCodeGenerator.java @@ -16,14 +16,23 @@ package com.facebook.presto.sql.gen; import com.facebook.presto.byteCode.Block; import com.facebook.presto.byteCode.ByteCodeNode; import com.facebook.presto.byteCode.CompilerContext; -import com.facebook.presto.byteCode.control.TryCatch; +import com.facebook.presto.byteCode.instruction.LabelNode; import com.facebook.presto.metadata.Signature; import com.facebook.presto.spi.type.Type; import com.facebook.presto.sql.relational.RowExpression; +import com.google.common.primitives.Primitives; +import java.lang.invoke.MethodHandle; import java.util.List; -import static com.facebook.presto.byteCode.ParameterizedType.type; +import static com.facebook.presto.sql.gen.ByteCodeUtils.ifWasNullPopAndGoto; +import static com.facebook.presto.sql.gen.ByteCodeUtils.invoke; +import static com.facebook.presto.sql.gen.ByteCodeUtils.unboxPrimitiveIfNecessary; +import static com.facebook.presto.type.UnknownType.UNKNOWN; +import static java.lang.invoke.MethodHandles.catchException; +import static java.lang.invoke.MethodHandles.constant; +import static java.lang.invoke.MethodHandles.dropArguments; +import static java.lang.invoke.MethodType.methodType; public class TryCastCodeGenerator implements ByteCodeGenerator @@ -31,19 +40,43 @@ public class TryCastCodeGenerator @Override public ByteCodeNode generateExpression(Signature signature, ByteCodeGeneratorContext generatorContext, Type returnType, List<RowExpression> arguments) { - ByteCodeNode castByteCode = new CastCodeGenerator().generateExpression(signature, generatorContext, returnType, arguments); - CompilerContext context = generatorContext.getContext(); - Block catchBlock = new Block(context) - .comment("propagate InterruptedException") - .invokeStatic(CompilerOperations.class, "propagateInterruptedException", void.class, Throwable.class) - .comment("wasNull = true;") - .putVariable("wasNull", true) - .comment("restore stack after exception") - .getVariable("output") // TODO: this is quite a strong assumption to make. This code should not be sensitive to whether "output" was on the stack before the call - .comment("return dummy value for null") - .pushJavaDefault(returnType.getJavaType()); - - return new TryCatch(context, "TRY_CAST", castByteCode, catchBlock, type(Exception.class)); + RowExpression argument = arguments.get(0); + + Class<?> argumentType = argument.getType().getJavaType(); + Class<?> unboxedReturnType = returnType.getJavaType(); + Class<?> boxedReturnType = Primitives.wrap(unboxedReturnType); + + if (argument.getType().equals(UNKNOWN)) { + return new Block(context) + .putVariable("wasNull", true) + .pushJavaDefault(unboxedReturnType); + } + + MethodHandle function = generatorContext + .getRegistry() + .getCoercion(argument.getType(), returnType) + .getMethodHandle() + .asType(methodType(boxedReturnType, argumentType)); + + MethodHandle tryCast = exceptionToNull(function, boxedReturnType, RuntimeException.class); + + Binding tryCastBinding = generatorContext.getCallSiteBinder().bind(tryCast); + + LabelNode end = new LabelNode("end"); + + return new Block(context) + .comment("call tryCast method") + .append(generatorContext.generate(argument)) + .append(ifWasNullPopAndGoto(context, end, unboxedReturnType, argumentType)) + .append(invoke(generatorContext.getContext(), tryCastBinding, "tryCast")) + .append(unboxPrimitiveIfNecessary(context, boxedReturnType)) + .visitLabel(end); + } + + private static MethodHandle exceptionToNull(MethodHandle target, Class<?> type, Class<? extends Throwable> throwable) + { + MethodHandle toNull = dropArguments(constant(type, null), 0, throwable); + return catchException(target, throwable, toNull); } } diff --git a/presto-main/src/test/java/com/facebook/presto/sql/gen/TestExpressionCompiler.java b/presto-main/src/test/java/com/facebook/presto/sql/gen/TestExpressionCompiler.java index 094181a730..3aed863516 100644 --- a/presto-main/src/test/java/com/facebook/presto/sql/gen/TestExpressionCompiler.java +++ b/presto-main/src/test/java/com/facebook/presto/sql/gen/TestExpressionCompiler.java @@ -543,8 +543,13 @@ public class TestExpressionCompiler assertExecute("try_cast('foo' as varchar)", "foo"); assertExecute("try_cast('foo' as bigint)", null); assertExecute("try_cast(bound_string as bigint)", null); + assertExecute("try_cast(cast(null as varchar) as bigint)", null); + assertExecute("try_cast(bound_long / 13 as bigint)", 94); assertExecute("coalesce(try_cast('123' as bigint), 456)", 123L); assertExecute("coalesce(try_cast('foo' as bigint), 456)", 456L); + assertExecute("concat('foo', cast('bar' as varchar))", "foobar"); + assertExecute("try_cast(try_cast(123 as varchar) as bigint)", 123L); + assertExecute("try_cast('foo' as varchar) || try_cast('bar' as varchar)", "foobar"); Futures.allAsList(futures).get(); } diff --git a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java index a65a5e4b5c..015fedab8b 100644 --- a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java +++ b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java @@ -2248,6 +2248,9 @@ public abstract class AbstractTestQueries assertQuery("SELECT try_cast('foo' AS BIGINT) FROM orders", "SELECT CAST(null AS BIGINT) FROM orders"); assertQuery("SELECT try_cast(clerk AS BIGINT) FROM orders", "SELECT CAST(null AS BIGINT) FROM orders"); + assertQuery("SELECT try_cast(orderkey * orderkey AS VARCHAR) FROM orders", "SELECT CAST(orderkey * orderkey AS VARCHAR) FROM orders"); + assertQuery("SELECT try_cast(try_cast(orderkey AS VARCHAR) AS BIGINT) FROM orders", "SELECT orderkey FROM orders"); + assertQuery("SELECT try_cast(clerk AS VARCHAR) || try_cast(clerk AS VARCHAR) FROM orders", "SELECT clerk || clerk FROM orders"); assertQuery("SELECT coalesce(try_cast('foo' AS BIGINT), 456) FROM orders", "SELECT 456 FROM orders"); assertQuery("SELECT coalesce(try_cast(clerk AS BIGINT), 456) FROM orders", "SELECT 456 FROM orders");
['presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java', 'presto-main/src/main/java/com/facebook/presto/sql/gen/ByteCodeUtils.java', 'presto-main/src/main/java/com/facebook/presto/sql/gen/CompilerOperations.java', 'presto-main/src/test/java/com/facebook/presto/sql/gen/TestExpressionCompiler.java', 'presto-main/src/main/java/com/facebook/presto/sql/gen/TryCastCodeGenerator.java']
{'.java': 5}
5
5
0
0
5
7,411,808
1,475,764
213,041
1,568
5,845
1,088
120
3
308
46
71
12
0
2
1970-01-01T00:23:42
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
214
prestodb/presto/2364/2330
prestodb
presto
https://github.com/prestodb/presto/issues/2330
https://github.com/prestodb/presto/pull/2364
https://github.com/prestodb/presto/pull/2364
1
fixes
Detect quick worker restarts and fail queries immediately
When a worker restart, the engine may not notice the change and wait for work that will never complete. An easy fix for this is to add the node instance id to task info and then the `HttpRemoteTask` would see the change and fail the task. This issue is identified by having a task stuck in the RUNNING state with 0 splits assigned. If there are multiple queries, they will all be stuck on the same node or nodes that rebooted.
4260ab3d315025f6a450bc7188f21cdd38c22c76
39202d3ffeb50897c0d7d8a30c29c13a01773dd3
https://github.com/prestodb/presto/compare/4260ab3d315025f6a450bc7188f21cdd38c22c76...39202d3ffeb50897c0d7d8a30c29c13a01773dd3
diff --git a/presto-main/src/main/java/com/facebook/presto/execution/SqlTask.java b/presto-main/src/main/java/com/facebook/presto/execution/SqlTask.java index 1ee5413c8d..12d7dfb1ef 100644 --- a/presto-main/src/main/java/com/facebook/presto/execution/SqlTask.java +++ b/presto-main/src/main/java/com/facebook/presto/execution/SqlTask.java @@ -35,6 +35,7 @@ import javax.annotation.Nullable; import java.net.URI; import java.util.List; +import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicLong; @@ -49,6 +50,7 @@ public class SqlTask private static final Logger log = Logger.get(SqlTask.class); private final TaskId taskId; + private final String nodeInstanceId; private final URI location; private final TaskStateMachine taskStateMachine; private final SharedBuffer sharedBuffer; @@ -62,6 +64,7 @@ public class SqlTask public SqlTask( TaskId taskId, + String nodeInstanceId, URI location, SqlTaskExecutionFactory sqlTaskExecutionFactory, ExecutorService taskNotificationExecutor, @@ -69,6 +72,7 @@ public class SqlTask DataSize maxBufferSize) { this.taskId = checkNotNull(taskId, "taskId is null"); + this.nodeInstanceId = checkNotNull(nodeInstanceId, "nodeInstanceId is null"); this.location = checkNotNull(location, "location is null"); this.sqlTaskExecutionFactory = checkNotNull(sqlTaskExecutionFactory, "sqlTaskExecutionFactory is null"); checkNotNull(taskNotificationExecutor, "taskNotificationExecutor is null"); @@ -174,6 +178,7 @@ public class SqlTask return new TaskInfo( taskStateMachine.getTaskId(), + Optional.of(nodeInstanceId), versionNumber, state, location, diff --git a/presto-main/src/main/java/com/facebook/presto/execution/SqlTaskManager.java b/presto-main/src/main/java/com/facebook/presto/execution/SqlTaskManager.java index 480d0a9f8e..1727c91682 100644 --- a/presto-main/src/main/java/com/facebook/presto/execution/SqlTaskManager.java +++ b/presto-main/src/main/java/com/facebook/presto/execution/SqlTaskManager.java @@ -27,6 +27,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.ListenableFuture; import io.airlift.concurrent.ThreadPoolExecutorMBean; import io.airlift.log.Logger; +import io.airlift.node.NodeInfo; import io.airlift.units.DataSize; import io.airlift.units.Duration; import org.joda.time.DateTime; @@ -78,8 +79,10 @@ public class SqlTaskManager final LocationFactory locationFactory, TaskExecutor taskExecutor, QueryMonitor queryMonitor, + NodeInfo nodeInfo, TaskManagerConfig config) { + checkNotNull(nodeInfo, "nodeInfo is null"); checkNotNull(config, "config is null"); infoCacheTime = config.getInfoMaxAge(); clientTimeout = config.getClientTimeout(); @@ -102,6 +105,7 @@ public class SqlTaskManager { return new SqlTask( taskId, + nodeInfo.getInstanceId(), locationFactory.createLocalTaskLocation(taskId), sqlTaskExecutionFactory, taskNotificationExecutor, diff --git a/presto-main/src/main/java/com/facebook/presto/execution/TaskInfo.java b/presto-main/src/main/java/com/facebook/presto/execution/TaskInfo.java index d68b08c45e..f20dad9dd4 100644 --- a/presto-main/src/main/java/com/facebook/presto/execution/TaskInfo.java +++ b/presto-main/src/main/java/com/facebook/presto/execution/TaskInfo.java @@ -24,6 +24,7 @@ import javax.annotation.concurrent.Immutable; import java.net.URI; import java.util.List; +import java.util.Optional; import java.util.Set; import static com.google.common.base.MoreObjects.toStringHelper; @@ -50,6 +51,7 @@ public class TaskInfo public static final long MAX_VERSION = Long.MAX_VALUE; private final TaskId taskId; + private final Optional<String> nodeInstanceId; private final long version; private final TaskState state; private final URI self; @@ -61,6 +63,7 @@ public class TaskInfo @JsonCreator public TaskInfo(@JsonProperty("taskId") TaskId taskId, + @JsonProperty("nodeInstanceId") Optional<String> nodeInstanceId, @JsonProperty("version") long version, @JsonProperty("state") TaskState state, @JsonProperty("self") URI self, @@ -71,6 +74,7 @@ public class TaskInfo @JsonProperty("failures") List<ExecutionFailureInfo> failures) { this.taskId = checkNotNull(taskId, "taskId is null"); + this.nodeInstanceId = checkNotNull(nodeInstanceId, "nodeInstanceId is null"); this.version = checkNotNull(version, "version is null"); this.state = checkNotNull(state, "state is null"); this.self = checkNotNull(self, "self is null"); @@ -93,6 +97,12 @@ public class TaskInfo return taskId; } + @JsonProperty + public Optional<String> getNodeInstanceId() + { + return nodeInstanceId; + } + @JsonProperty public long getVersion() { @@ -143,7 +153,7 @@ public class TaskInfo public TaskInfo summarize() { - return new TaskInfo(taskId, version, state, self, lastHeartbeat, outputBuffers, noMoreSplits, stats.summarize(), failures); + return new TaskInfo(taskId, nodeInstanceId, version, state, self, lastHeartbeat, outputBuffers, noMoreSplits, stats.summarize(), failures); } @Override diff --git a/presto-main/src/main/java/com/facebook/presto/server/HttpRemoteTask.java b/presto-main/src/main/java/com/facebook/presto/server/HttpRemoteTask.java index 473996c505..40e59dab43 100644 --- a/presto-main/src/main/java/com/facebook/presto/server/HttpRemoteTask.java +++ b/presto-main/src/main/java/com/facebook/presto/server/HttpRemoteTask.java @@ -67,6 +67,7 @@ import java.net.URI; import java.util.HashSet; import java.util.List; import java.util.Map.Entry; +import java.util.Optional; import java.util.Queue; import java.util.Set; import java.util.concurrent.CancellationException; @@ -82,7 +83,9 @@ import java.util.concurrent.atomic.AtomicReference; import static com.facebook.presto.spi.StandardErrorCode.REMOTE_TASK_ERROR; import static com.facebook.presto.spi.StandardErrorCode.TOO_MANY_REQUESTS_FAILED; +import static com.facebook.presto.spi.StandardErrorCode.WORKER_RESTARTED; import static com.facebook.presto.util.Failures.WORKER_NODE_ERROR; +import static com.facebook.presto.util.Failures.WORKER_RESTARTED_ERROR; import static com.facebook.presto.util.Failures.toFailure; import static com.facebook.presto.util.ImmutableCollectors.toImmutableList; import static com.google.common.base.MoreObjects.toStringHelper; @@ -188,6 +191,7 @@ public class HttpRemoteTask taskInfo = new StateMachine<>("task " + taskId, executor, new TaskInfo( taskId, + Optional.empty(), TaskInfo.MIN_VERSION, TaskState.PLANNED, location, @@ -322,7 +326,14 @@ public class HttpRemoteTask } // change to new value if old value is not changed and new value has a newer version + AtomicBoolean workerRestarted = new AtomicBoolean(); taskInfo.setIf(newValue, oldValue -> { + // did the worker restart + if (oldValue.getNodeInstanceId().isPresent() && !oldValue.getNodeInstanceId().equals(newValue.getNodeInstanceId())) { + workerRestarted.set(true); + return false; + } + if (oldValue.getState().isDone()) { // never update if the task has reached a terminal state return false; @@ -334,6 +345,12 @@ public class HttpRemoteTask return true; }); + if (workerRestarted.get()) { + PrestoException exception = new PrestoException(WORKER_RESTARTED, format("%s (%s)", WORKER_RESTARTED_ERROR, newValue.getSelf())); + failTask(exception); + abort(); + } + // remove acknowledged splits, which frees memory for (TaskSource source : sources) { PlanNodeId planNodeId = source.getPlanNodeId(); @@ -465,6 +482,7 @@ public class HttpRemoteTask TaskInfo taskInfo = getTaskInfo(); URI uri = taskInfo.getSelf(); updateTaskInfo(new TaskInfo(taskInfo.getTaskId(), + taskInfo.getNodeInstanceId(), TaskInfo.MAX_VERSION, TaskState.ABORTED, uri, @@ -521,6 +539,7 @@ public class HttpRemoteTask log.debug(cause, "Remote task failed: %s", taskInfo.getSelf()); } updateTaskInfo(new TaskInfo(taskInfo.getTaskId(), + taskInfo.getNodeInstanceId(), TaskInfo.MAX_VERSION, TaskState.FAILED, taskInfo.getSelf(), diff --git a/presto-main/src/main/java/com/facebook/presto/util/Failures.java b/presto-main/src/main/java/com/facebook/presto/util/Failures.java index d84d0d8af8..e9b52ae132 100644 --- a/presto-main/src/main/java/com/facebook/presto/util/Failures.java +++ b/presto-main/src/main/java/com/facebook/presto/util/Failures.java @@ -34,11 +34,13 @@ import static java.util.Arrays.asList; public final class Failures { - public static final String WORKER_NODE_ERROR = "" + - "Encountered too many errors talking to a worker node. " + - "The node may have crashed or be under too much load. " + + private static final String NODE_CRASHED_ERROR = "The node may have crashed or be under too much load. " + "This is probably a transient issue, so please retry your query in a few minutes."; + public static final String WORKER_NODE_ERROR = "Encountered too many errors talking to a worker node. " + NODE_CRASHED_ERROR; + + public static final String WORKER_RESTARTED_ERROR = "A worker node running your query has restarted. " + NODE_CRASHED_ERROR; + private Failures() {} public static ExecutionFailureInfo toFailure(Throwable failure) diff --git a/presto-main/src/test/java/com/facebook/presto/execution/MockRemoteTaskFactory.java b/presto-main/src/test/java/com/facebook/presto/execution/MockRemoteTaskFactory.java index d31eccc264..fb79a6abc8 100644 --- a/presto-main/src/test/java/com/facebook/presto/execution/MockRemoteTaskFactory.java +++ b/presto-main/src/test/java/com/facebook/presto/execution/MockRemoteTaskFactory.java @@ -162,6 +162,7 @@ public class MockRemoteTaskFactory return new TaskInfo( taskStateMachine.getTaskId(), + Optional.empty(), nextTaskInfoVersion.getAndIncrement(), state, location, diff --git a/presto-main/src/test/java/com/facebook/presto/execution/TestSqlStageExecution.java b/presto-main/src/test/java/com/facebook/presto/execution/TestSqlStageExecution.java index dc34df9d98..b0d045974c 100644 --- a/presto-main/src/test/java/com/facebook/presto/execution/TestSqlStageExecution.java +++ b/presto-main/src/test/java/com/facebook/presto/execution/TestSqlStageExecution.java @@ -442,6 +442,7 @@ public class TestSqlStageExecution return new TaskInfo( taskStateMachine.getTaskId(), + Optional.empty(), nextTaskInfoVersion.getAndIncrement(), state, location, diff --git a/presto-main/src/test/java/com/facebook/presto/execution/TestSqlTask.java b/presto-main/src/test/java/com/facebook/presto/execution/TestSqlTask.java index 04d77f8b58..b363827a20 100644 --- a/presto-main/src/test/java/com/facebook/presto/execution/TestSqlTask.java +++ b/presto-main/src/test/java/com/facebook/presto/execution/TestSqlTask.java @@ -278,6 +278,7 @@ public class TestSqlTask return new SqlTask( taskId, + "test", location, sqlTaskExecutionFactory, taskNotificationExecutor, diff --git a/presto-main/src/test/java/com/facebook/presto/execution/TestSqlTaskManager.java b/presto-main/src/test/java/com/facebook/presto/execution/TestSqlTaskManager.java index 701501ca26..22b7f83597 100644 --- a/presto-main/src/test/java/com/facebook/presto/execution/TestSqlTaskManager.java +++ b/presto-main/src/test/java/com/facebook/presto/execution/TestSqlTaskManager.java @@ -245,6 +245,7 @@ public class TestSqlTaskManager new MockLocationFactory(), taskExecutor, new QueryMonitor(new ObjectMapperProvider().get(), new NullEventClient(), new NodeInfo("test"), new NodeVersion("testVersion")), + new NodeInfo("test"), config); } diff --git a/presto-main/src/test/java/com/facebook/presto/server/MockTaskManager.java b/presto-main/src/test/java/com/facebook/presto/server/MockTaskManager.java index b3870629ad..113221fb3b 100644 --- a/presto-main/src/test/java/com/facebook/presto/server/MockTaskManager.java +++ b/presto-main/src/test/java/com/facebook/presto/server/MockTaskManager.java @@ -44,6 +44,7 @@ import java.net.URI; import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; +import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ScheduledExecutorService; @@ -271,6 +272,7 @@ public class MockTaskManager return new TaskInfo( taskStateMachine.getTaskId(), + Optional.empty(), nextTaskInfoVersion.getAndIncrement(), state, location, diff --git a/presto-spi/src/main/java/com/facebook/presto/spi/StandardErrorCode.java b/presto-spi/src/main/java/com/facebook/presto/spi/StandardErrorCode.java index 9ed35f16c4..e54d5e3e8a 100644 --- a/presto-spi/src/main/java/com/facebook/presto/spi/StandardErrorCode.java +++ b/presto-spi/src/main/java/com/facebook/presto/spi/StandardErrorCode.java @@ -42,6 +42,7 @@ public enum StandardErrorCode NO_NODES_AVAILABLE(0x0001_0005), REMOTE_TASK_ERROR(0x0001_0006), COMPILER_ERROR(0x0001_0007), + WORKER_RESTARTED(0x0001_0008), INSUFFICIENT_RESOURCES(0x0002_0000), EXCEEDED_MEMORY_LIMIT(0x0002_0001),
['presto-main/src/main/java/com/facebook/presto/execution/SqlTask.java', 'presto-main/src/main/java/com/facebook/presto/util/Failures.java', 'presto-main/src/test/java/com/facebook/presto/execution/MockRemoteTaskFactory.java', 'presto-main/src/test/java/com/facebook/presto/server/MockTaskManager.java', 'presto-main/src/test/java/com/facebook/presto/execution/TestSqlTask.java', 'presto-main/src/test/java/com/facebook/presto/execution/TestSqlTaskManager.java', 'presto-main/src/main/java/com/facebook/presto/server/HttpRemoteTask.java', 'presto-main/src/main/java/com/facebook/presto/execution/TaskInfo.java', 'presto-main/src/test/java/com/facebook/presto/execution/TestSqlStageExecution.java', 'presto-spi/src/main/java/com/facebook/presto/spi/StandardErrorCode.java', 'presto-main/src/main/java/com/facebook/presto/execution/SqlTaskManager.java']
{'.java': 11}
11
11
0
0
11
7,420,867
1,477,677
213,380
1,572
2,546
514
49
6
430
81
95
4
0
0
1970-01-01T00:23:43
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
213
prestodb/presto/3775/3646
prestodb
presto
https://github.com/prestodb/presto/issues/3646
https://github.com/prestodb/presto/pull/3775
https://github.com/prestodb/presto/pull/3775
1
fixes
Duplicate DistinctLimitNode in query plan
When explain distinct limit query, the plan looks like below There are duplicate DistinctLimit in the plan. ``` presto:orc> explain select distinct l_orderkey from lineitem limit 10; Query Plan --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - Output[l_orderkey] => [l_orderkey:bigint] - DistinctLimit[10] => [l_orderkey:bigint, $hashvalue:bigint] - Exchange[GATHER] => l_orderkey:bigint, $hashvalue:bigint - DistinctLimit[10] => [l_orderkey:bigint, $hashvalue:bigint] - DistinctLimit[10] => [l_orderkey:bigint, $hashvalue:bigint] - Project => [l_orderkey:bigint, $hashvalue:bigint] $hashvalue := "combine_hash"(0, COALESCE("$operator$hash_code"("l_orderkey"), 0)) - TableScan[hive:hive:orc:lineitem, originalConstraint = true] => [l_orderkey:bigint] LAYOUT: hive l_orderkey := HiveColumnHandle{clientId=hive, name=l_orderkey, ordinalPosition=0, hiveType=bigint, hiveColumnIndex=0, partitionKey=false} ```
db5ea9183412656f9cbf2e8a9302666ac323143d
7bdf3ff5faf3e0dce34b82271050a718cd9e157d
https://github.com/prestodb/presto/compare/db5ea9183412656f9cbf2e8a9302666ac323143d...7bdf3ff5faf3e0dce34b82271050a718cd9e157d
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/AddExchanges.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/AddExchanges.java index 90beffb26c..ae565e188e 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/AddExchanges.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/AddExchanges.java @@ -545,10 +545,6 @@ public class AddExchanges PlanWithProperties child = planChild(node, context.withPreferredProperties(PreferredProperties.any())); if (child.getProperties().isDistributed()) { - child = withDerivedProperties( - new DistinctLimitNode(idAllocator.getNextId(), child.getNode(), node.getLimit(), node.getHashSymbol()), - child.getProperties()); - child = withDerivedProperties( gatheringExchange( idAllocator.getNextId(),
['presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/AddExchanges.java']
{'.java': 1}
1
1
0
0
1
9,246,331
1,839,831
262,147
1,925
227
35
4
1
2,251
82
288
19
0
1
1970-01-01T00:24:05
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
212
prestodb/presto/4012/4008
prestodb
presto
https://github.com/prestodb/presto/issues/4008
https://github.com/prestodb/presto/pull/4012
https://github.com/prestodb/presto/pull/4012
1
fixes
Array constructor with too many values causes ClassFormatError
Queries that contain very large array constructors cause bytecode to be generated that contains too many method arguments. ``` SELECT ARRAY['1','1','1','2','1','1','-1','1','1','1','1','1','-1','1','1','1','1','1','1','1','1','1','-1','1','-1','1','1','1','1','1','1','1','-1','-1','-1','1','-1','1','-1','3','-1','1','1','1','1','-1','-1','1','1','-1','-1','1','1','1','1','1','-1','1','1','1','1','1','-1','-1','1','-1','1','-1','1','1','1','-1','1','1','-1','1','1','-1','1','-1','-1','-1','1','1','-1','1','1','1','1','1','-1','1','-1','1','-1','1','1','1','1','-1','-1','-1','1','-1','-1','-1','1','1','1','-1','1','-1','-1','-1','-1','1','-1','-1','-1','1','-1','1','1','3','1','-1','-1','1','-1','-1','1','-1','-1','1','1','1','-1','-1','-1','1','1','1','-1','1','1','1','1','-1','-1','-1','1','-1','1','-1','3','-1','-1','1','-1','1','1','-1','-1','3','-1','1','-1','-1','-1','1','-1','-1','1','1','1','1','1','-1','1','1','-1','-1','-1','1','1','1','-1','1','-1','1','1','1','-1','-1','1','1','-1','-1','-1','-1','1','-1','-1','1','-1','1','1','-1','1','-1','-1','1','1','-1','-1','-1','-1','1','1','1','-1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','-1','-1','-1','-1','1','-1','1','-1','-1','1','3','-1','-1','1','1','3','1','1','1','1','1','1','1','1','-1','1','1','3','3','1','1','1','-1','-1','1','1','1','3','1','1','1','1','1','1','1','1','1','1','1','1','1','1','-1','1','1','1','1','1','1','1','3','1','1','1','1','1','1','1','1','1','1','1','1','-1','1','1','1','1','1','-1','1','3','1','1','1','1','1','3','1','3','1','1','1','1','3','-1','-1','-1','1','1','1','-1','-1','-1','-1','-1','1','-1','1','1','3','1','1','1','1','-1','-1','3','1','1','3','-1','1','1','1','-1','-1','1','1','1','-1','1','1','1','-1','1','3','1','1','1','1','3','3','-1','1','1','-1','3','3','1','1','3','-1','-1','1','1','-1','-1','1','1','3','1','-1','3','3','1','1','3','1','1','1','3','3','1','1','3','3','3','1','1','1','1','-1','-1','1','1','3','1','1','3','3','1','1','3','3','1','-1','1','1','1','1','-1','1','1','1','1','1','3','3','-1','-1','-1','1','-1','1','1','3','1','3','1','1','1','1','1','3','1','1','-1','1','3','3','3','1','1','3','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','3','1','3','3','1','1','1','1','1','1','1','1','1','1','1','1','1','3','3','1','1']; ``` fails with ``` com.google.common.util.concurrent.ExecutionError: java.lang.ClassFormatError: Too many arguments in method signature i n class file com_facebook_presto_$gen_SliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSlice SliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSli ceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceS liceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSlic eSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSl iceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSlice SliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSli ceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceSliceS liceSliceSliceSliceSliceSliceSliceSlice at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2201) at com.google.common.cache.LocalCache.get(LocalCache.java:3937) at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3941) at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4824) at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4830) at com.facebook.presto.metadata.FunctionRegistry.getScalarFunctionImplementation(FunctionRegistry.java:586) at com.facebook.presto.sql.planner.ExpressionInterpreter$Visitor.visitFunctionCall(ExpressionInterpreter.java: 798) at com.facebook.presto.sql.planner.ExpressionInterpreter$Visitor.visitArrayConstructor(ExpressionInterpreter.j ava:940) at com.facebook.presto.sql.tree.ArrayConstructor.accept(ArrayConstructor.java:54) at com.facebook.presto.sql.tree.AstVisitor.process(AstVisitor.java:22) at com.facebook.presto.sql.planner.ExpressionInterpreter.optimize(ExpressionInterpreter.java:251) at com.facebook.presto.sql.planner.optimizations.SimplifyExpressions$Rewriter.simplifyExpression(SimplifyExpre ssions.java:133) at com.google.common.collect.Maps$7.transformEntry(Maps.java:1812) at com.google.common.collect.Maps$10.getValue(Maps.java:1857) at com.google.common.collect.ImmutableMap.copyOf(ImmutableMap.java:292) at com.facebook.presto.sql.planner.optimizations.SimplifyExpressions$Rewriter.visitProject(SimplifyExpressions .java:92) at com.facebook.presto.sql.planner.optimizations.SimplifyExpressions$Rewriter.visitProject(SimplifyExpressions .java:70) at com.facebook.presto.sql.planner.plan.ProjectNode.accept(ProjectNode.java:81) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.rewrite(SimplePlanRewriter.java:86) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.rewrite(SimplePlanRewriter.java:97) at com.facebook.presto.sql.planner.optimizations.SimplifyExpressions$Rewriter.visitProject(SimplifyExpressions .java:91) at com.facebook.presto.sql.planner.optimizations.SimplifyExpressions$Rewriter.visitProject(SimplifyExpressions .java:70) at com.facebook.presto.sql.planner.plan.ProjectNode.accept(ProjectNode.java:81) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.rewrite(SimplePlanRewriter.java:86) at com.facebook.presto.sql.planner.plan.SimplePlanRewriter$RewriteContext.rewrite(SimplePlanRewriter.java:97) at com.facebook.presto.sql.planner.optimizations.SimplifyExpressions$Rewriter.visitProject(SimplifyExpressions .java:91) ... ```
72917dec52feac0df81fbdc3fa86fdfa3ccb5396
cca5a7c1c89bc9b7a47dd16956bb408c753ab5bc
https://github.com/prestodb/presto/compare/72917dec52feac0df81fbdc3fa86fdfa3ccb5396...cca5a7c1c89bc9b7a47dd16956bb408c753ab5bc
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/ExpressionInterpreter.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/ExpressionInterpreter.java index 3b49320335..4bdf002a0b 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/ExpressionInterpreter.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/ExpressionInterpreter.java @@ -25,6 +25,8 @@ import com.facebook.presto.spi.ConnectorSession; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.RecordCursor; import com.facebook.presto.spi.block.Block; +import com.facebook.presto.spi.block.BlockBuilder; +import com.facebook.presto.spi.block.BlockBuilderStatus; import com.facebook.presto.spi.type.StandardTypes; import com.facebook.presto.spi.type.Type; import com.facebook.presto.sql.analyzer.AnalysisContext; @@ -68,6 +70,7 @@ import com.facebook.presto.sql.tree.SimpleCaseExpression; import com.facebook.presto.sql.tree.StringLiteral; import com.facebook.presto.sql.tree.SubscriptExpression; import com.facebook.presto.sql.tree.WhenClause; +import com.facebook.presto.type.ArrayType; import com.facebook.presto.type.LikeFunctions; import com.facebook.presto.util.Failures; import com.facebook.presto.util.FastutilSetHelper; @@ -93,6 +96,7 @@ import java.util.stream.Stream; import static com.facebook.presto.spi.StandardErrorCode.NOT_SUPPORTED; import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature; +import static com.facebook.presto.spi.type.TypeUtils.writeNativeValue; import static com.facebook.presto.sql.analyzer.ExpressionAnalyzer.createConstantAnalyzer; import static com.facebook.presto.sql.analyzer.SemanticErrorCode.EXPRESSION_NOT_CONSTANT; import static com.facebook.presto.sql.planner.LiteralInterpreter.toExpression; @@ -936,7 +940,18 @@ public class ExpressionInterpreter @Override protected Object visitArrayConstructor(ArrayConstructor node, Object context) { - return visitFunctionCall(new FunctionCall(QualifiedName.of(ArrayConstructor.ARRAY_CONSTRUCTOR), node.getValues()), context); + Type elementType = ((ArrayType) expressionTypes.get(node)).getElementType(); + BlockBuilder arrayBlockBuilder = elementType.createBlockBuilder(new BlockBuilderStatus(), node.getValues().size()); + + for (Expression expression : node.getValues()) { + Object value = process(expression, context); + if (value instanceof Expression) { + return visitFunctionCall(new FunctionCall(QualifiedName.of(ArrayConstructor.ARRAY_CONSTRUCTOR), node.getValues()), context); + } + writeNativeValue(elementType, arrayBlockBuilder, value); + } + + return arrayBlockBuilder.build(); } @Override diff --git a/presto-main/src/test/java/com/facebook/presto/sql/TestExpressionInterpreter.java b/presto-main/src/test/java/com/facebook/presto/sql/TestExpressionInterpreter.java index 70d3b8c032..41f09f57d5 100644 --- a/presto-main/src/test/java/com/facebook/presto/sql/TestExpressionInterpreter.java +++ b/presto-main/src/test/java/com/facebook/presto/sql/TestExpressionInterpreter.java @@ -33,6 +33,7 @@ import com.facebook.presto.sql.tree.LikePredicate; import com.facebook.presto.sql.tree.QualifiedName; import com.facebook.presto.sql.tree.QualifiedNameReference; import com.facebook.presto.sql.tree.StringLiteral; +import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import io.airlift.slice.Slice; @@ -48,6 +49,7 @@ import org.testng.annotations.Test; import java.util.IdentityHashMap; import java.util.Map; import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; import static com.facebook.presto.SessionTestUtils.TEST_SESSION; import static com.facebook.presto.spi.type.BigintType.BIGINT; @@ -64,6 +66,7 @@ import static com.facebook.presto.sql.analyzer.ExpressionAnalyzer.getExpressionT import static com.facebook.presto.sql.planner.ExpressionInterpreter.expressionInterpreter; import static com.facebook.presto.sql.planner.ExpressionInterpreter.expressionOptimizer; import static io.airlift.slice.Slices.utf8Slice; +import static java.lang.String.format; import static java.util.Locale.ENGLISH; import static org.testng.Assert.assertEquals; @@ -929,6 +932,26 @@ public class TestExpressionInterpreter optimize("0 / 0"); } + @Test + public void testMassiveArrayConstructor() + { + optimize(format("ARRAY [%s]", Joiner.on(", ").join(IntStream.range(0, 10_000).mapToObj(i -> "(bound_long + " + i + ")").iterator()))); + optimize(format("ARRAY [%s]", Joiner.on(", ").join(IntStream.range(0, 10_000).mapToObj(i -> "'" + i + "'").iterator()))); + optimize(format("ARRAY [%s]", Joiner.on(", ").join(IntStream.range(0, 10_000).mapToObj(i -> "ARRAY['" + i + "']").iterator()))); + } + + @Test + public void testArrayConstructor() + { + optimize("ARRAY []"); + assertOptimizedEquals("ARRAY [(unbound_long + 0), (unbound_long + 1), (unbound_long + 2)]", + "array_constructor((unbound_long + 0), (unbound_long + 1), (unbound_long + 2))"); + assertOptimizedEquals("ARRAY [(bound_long + 0), (unbound_long + 1), (bound_long + 2)]", + "array_constructor((bound_long + 0), (unbound_long + 1), (bound_long + 2))"); + assertOptimizedEquals("ARRAY [(bound_long + 0), (unbound_long + 1), NULL]", + "array_constructor((bound_long + 0), (unbound_long + 1), NULL)"); + } + @Test(expectedExceptions = PrestoException.class) public void testArraySubscriptConstantNegativeIndex() {
['presto-main/src/test/java/com/facebook/presto/sql/TestExpressionInterpreter.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/ExpressionInterpreter.java']
{'.java': 2}
2
2
0
0
2
9,923,818
1,970,571
280,472
2,048
1,063
190
17
1
6,187
108
1,901
56
0
2
1970-01-01T00:24:08
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
210
prestodb/presto/4046/4042
prestodb
presto
https://github.com/prestodb/presto/issues/4042
https://github.com/prestodb/presto/pull/4046
https://github.com/prestodb/presto/pull/4046
1
fixes
Raptor local shard cleanup should only mark shards for current node
The calls in `ShardCleaner` to `updateCleanedShardNodes()` and `updatePurgedShardNodes()` should take the current node ID. It is updating the shard for all nodes rather than just the local node.
62411b7b148754932980e4ae48caf1413777c61a
acfc0609c0b5bccb92f3d17e4b9cfa87f7a79f5c
https://github.com/prestodb/presto/compare/62411b7b148754932980e4ae48caf1413777c61a...acfc0609c0b5bccb92f3d17e4b9cfa87f7a79f5c
diff --git a/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/ShardCleaner.java b/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/ShardCleaner.java index b7ef3d1d4c..7138fa225e 100644 --- a/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/ShardCleaner.java +++ b/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/ShardCleaner.java @@ -16,6 +16,7 @@ package com.facebook.presto.raptor.metadata; import com.facebook.presto.raptor.backup.BackupStore; import com.facebook.presto.raptor.storage.StorageService; import com.facebook.presto.spi.NodeManager; +import com.facebook.presto.spi.PrestoException; import com.google.common.annotations.VisibleForTesting; import io.airlift.log.Logger; import io.airlift.units.Duration; @@ -41,6 +42,7 @@ import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; +import static com.facebook.presto.raptor.RaptorErrorCode.RAPTOR_ERROR; import static com.facebook.presto.raptor.util.DatabaseUtil.onDemandDao; import static io.airlift.concurrent.Threads.daemonThreadsNamed; import static java.util.Objects.requireNonNull; @@ -239,7 +241,7 @@ public class ShardCleaner for (UUID uuid : uuids) { deleteFile(storageService.getStorageFile(uuid)); } - dao.updateCleanedShardNodes(uuids); + dao.updateCleanedShardNodes(uuids, getCurrentNodeId()); } } @@ -255,7 +257,7 @@ public class ShardCleaner for (UUID uuid : uuids) { deleteFile(storageService.getStorageFile(uuid)); } - dao.updatePurgedShardNodes(uuids); + dao.updatePurgedShardNodes(uuids, getCurrentNodeId()); } } @@ -327,6 +329,15 @@ public class ShardCleaner } } + private int getCurrentNodeId() + { + Integer nodeId = dao.getNodeId(currentNode); + if (nodeId == null) { + throw new PrestoException(RAPTOR_ERROR, "Node does not exist: " + currentNode); + } + return nodeId; + } + private static Timestamp maxTimestamp(Duration duration) { return new Timestamp(System.currentTimeMillis() - duration.toMillis()); diff --git a/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/ShardManagerDao.java b/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/ShardManagerDao.java index 98e3ee0b0c..e6ebdbf69c 100644 --- a/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/ShardManagerDao.java +++ b/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/ShardManagerDao.java @@ -279,11 +279,17 @@ public interface ShardManagerDao @SqlBatch("UPDATE deleted_shard_nodes SET clean_time = CURRENT_TIMESTAMP\\n" + "WHERE shard_uuid = :shardUuid\\n" + + " AND node_id = :nodeId\\n" + " AND clean_time IS NULL\\n") - void updateCleanedShardNodes(@Bind("shardUuid") Iterable<UUID> shardUuids); + void updateCleanedShardNodes( + @Bind("shardUuid") Iterable<UUID> shardUuids, + @Bind("nodeId") int nodeId); @SqlBatch("UPDATE deleted_shard_nodes SET purge_time = CURRENT_TIMESTAMP\\n" + "WHERE shard_uuid = :shardUuid\\n" + + " AND node_id = :nodeId\\n" + " AND purge_time IS NULL\\n") - void updatePurgedShardNodes(@Bind("shardUuid") Iterable<UUID> shardUuids); + void updatePurgedShardNodes( + @Bind("shardUuid") Iterable<UUID> shardUuids, + @Bind("nodeId") int nodeId); } diff --git a/presto-raptor/src/test/java/com/facebook/presto/raptor/metadata/TestShardManagerDao.java b/presto-raptor/src/test/java/com/facebook/presto/raptor/metadata/TestShardManagerDao.java index eb56cdc0ef..2335e5ad09 100644 --- a/presto-raptor/src/test/java/com/facebook/presto/raptor/metadata/TestShardManagerDao.java +++ b/presto-raptor/src/test/java/com/facebook/presto/raptor/metadata/TestShardManagerDao.java @@ -24,12 +24,14 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.sql.SQLException; +import java.sql.Timestamp; import java.util.List; import java.util.Map; import java.util.UUID; import static com.facebook.presto.raptor.metadata.SchemaDaoUtil.createTablesWithRetry; import static io.airlift.testing.Assertions.assertInstanceOf; +import static java.util.concurrent.TimeUnit.DAYS; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; @@ -276,6 +278,50 @@ public class TestShardManagerDao assertContainsShardNode(shardNodes, nodeName2, shardUuid4); } + @Test + public void testDeletedShardNodes() + { + String nodeName1 = UUID.randomUUID().toString(); + int nodeId1 = dao.insertNode(nodeName1); + + String nodeName2 = UUID.randomUUID().toString(); + int nodeId2 = dao.insertNode(nodeName2); + + ImmutableList<UUID> shards = ImmutableList.of(UUID.randomUUID()); + + // insert shard on both nodes + dao.insertDeletedShardNodes(shards, ImmutableList.of(nodeId1)); + dao.insertDeletedShardNodes(shards, ImmutableList.of(nodeId2)); + + // verify we should clean from both + assertEquals(dao.getCleanableShardNodesBatch(nodeName1, future()), shards); + assertEquals(dao.getCleanableShardNodesBatch(nodeName2, future()), shards); + + // clean on first node + dao.updateCleanedShardNodes(shards, nodeId1); + assertEquals(dao.getCleanableShardNodesBatch(nodeName1, future()), ImmutableList.of()); + assertEquals(dao.getCleanableShardNodesBatch(nodeName2, future()), shards); + + // clean on second node + dao.updateCleanedShardNodes(shards, nodeId2); + assertEquals(dao.getCleanableShardNodesBatch(nodeName1, future()), ImmutableList.of()); + assertEquals(dao.getCleanableShardNodesBatch(nodeName2, future()), ImmutableList.of()); + + // verify we should purge from both + assertEquals(dao.getPurgableShardNodesBatch(nodeName1, future()), shards); + assertEquals(dao.getPurgableShardNodesBatch(nodeName2, future()), shards); + + // purge on first node + dao.updatePurgedShardNodes(shards, nodeId1); + assertEquals(dao.getPurgableShardNodesBatch(nodeName1, future()), ImmutableList.of()); + assertEquals(dao.getPurgableShardNodesBatch(nodeName2, future()), shards); + + // purge on second node + dao.updatePurgedShardNodes(shards, nodeId2); + assertEquals(dao.getPurgableShardNodesBatch(nodeName1, future()), ImmutableList.of()); + assertEquals(dao.getPurgableShardNodesBatch(nodeName2, future()), ImmutableList.of()); + } + private long createTable(String name) { return dbi.onDemand(MetadataDao.class).insertTable("test", name, false); @@ -285,4 +331,9 @@ public class TestShardManagerDao { assertTrue(nodes.contains(new ShardNode(shardUuid, nodeName))); } + + private static Timestamp future() + { + return new Timestamp(System.currentTimeMillis() + DAYS.toMillis(1)); + } }
['presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/ShardManagerDao.java', 'presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/ShardCleaner.java', 'presto-raptor/src/test/java/com/facebook/presto/raptor/metadata/TestShardManagerDao.java']
{'.java': 3}
3
3
0
0
3
9,507,352
1,891,493
269,569
1,969
1,136
281
25
2
195
28
50
2
0
0
1970-01-01T00:24:08
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
209
prestodb/presto/4469/4421
prestodb
presto
https://github.com/prestodb/presto/issues/4421
https://github.com/prestodb/presto/pull/4469
https://github.com/prestodb/presto/pull/4469
1
closes
Validate column order when creating Hive tables
Partition columns for Hive tables are always at the end because Hive works that way. When creating a table, the creation should fail if the columns are not in the final order (having `CREATE TABLE` silently rearrange columns is quite unexpected). We should use a new error code for this: `HIVE_COLUMN_ORDER_MISMATCH` This should fail because the partition column is listed first, but will be at the end in the final table: ``` CREATE TABLE test ( ds varchar, x bigint) WITH (partitioned_by = ARRAY['ds']); ``` This should fail because the partition columns are listed in a different order than in the partition specification: ``` CREATE TABLE test ( x bigint, type varchar, ds varchar) WITH (partitioned_by = ARRAY['ds', 'type']); ```
b3f052c34ac4832b6f65d6a95b2f49add2fa29dd
ff642bd931cf1d5a5e6e3a0bea465f8fcb9fbd37
https://github.com/prestodb/presto/compare/b3f052c34ac4832b6f65d6a95b2f49add2fa29dd...ff642bd931cf1d5a5e6e3a0bea465f8fcb9fbd37
diff --git a/presto-hive/src/main/java/com/facebook/presto/hive/HiveErrorCode.java b/presto-hive/src/main/java/com/facebook/presto/hive/HiveErrorCode.java index c902673fab..5da341a3cd 100644 --- a/presto-hive/src/main/java/com/facebook/presto/hive/HiveErrorCode.java +++ b/presto-hive/src/main/java/com/facebook/presto/hive/HiveErrorCode.java @@ -42,7 +42,8 @@ public enum HiveErrorCode HIVE_UNSUPPORTED_FORMAT(0x0100_0013), HIVE_PARTITION_READ_ONLY(0x0100_00014), HIVE_TOO_MANY_OPEN_PARTITIONS(0x0000_0015), - HIVE_CONCURRENT_MODIFICATION_DETECTED(0x0000_0016); + HIVE_CONCURRENT_MODIFICATION_DETECTED(0x0000_0016), + HIVE_COLUMN_ORDER_MISMATCH(0x0000_0017); private final ErrorCode errorCode; diff --git a/presto-hive/src/main/java/com/facebook/presto/hive/HiveMetadata.java b/presto-hive/src/main/java/com/facebook/presto/hive/HiveMetadata.java index 05bd0aee5a..f4ab85d629 100644 --- a/presto-hive/src/main/java/com/facebook/presto/hive/HiveMetadata.java +++ b/presto-hive/src/main/java/com/facebook/presto/hive/HiveMetadata.java @@ -82,6 +82,7 @@ import java.util.function.Predicate; import static com.facebook.presto.hive.HiveColumnHandle.SAMPLE_WEIGHT_COLUMN_NAME; import static com.facebook.presto.hive.HiveColumnHandle.updateRowIdHandle; +import static com.facebook.presto.hive.HiveErrorCode.HIVE_COLUMN_ORDER_MISMATCH; import static com.facebook.presto.hive.HiveErrorCode.HIVE_CONCURRENT_MODIFICATION_DETECTED; import static com.facebook.presto.hive.HiveErrorCode.HIVE_FILESYSTEM_ERROR; import static com.facebook.presto.hive.HiveErrorCode.HIVE_INVALID_METADATA; @@ -1304,8 +1305,23 @@ public class HiveMetadata throw new PrestoException(HIVE_UNSUPPORTED_FORMAT, format("Output format %s with SerDe %s is not supported", outputFormat, serializationLib)); } + private static void validateColumnOrdering(ConnectorTableMetadata tableMetadata) + { + List<String> partitionedBy = getPartitionedBy(tableMetadata.getProperties()); + + List<String> allColumns = tableMetadata.getColumns().stream() + .map(ColumnMetadata::getName) + .collect(toList()); + + if (!allColumns.subList(allColumns.size() - partitionedBy.size(), allColumns.size()).equals(partitionedBy)) { + throw new PrestoException(HIVE_COLUMN_ORDER_MISMATCH, "Partition keys must be the last columns in the table and in the same order as the table properties: " + partitionedBy); + } + } + private static List<HiveColumnHandle> getColumnHandles(String connectorId, ConnectorTableMetadata tableMetadata, Set<String> partitionColumnNames) { + validateColumnOrdering(tableMetadata); + ImmutableList.Builder<HiveColumnHandle> columnHandles = ImmutableList.builder(); Set<String> foundPartitionColumns = new HashSet<>(); int ordinal = 0; diff --git a/presto-hive/src/test/java/com/facebook/presto/hive/TestHiveIntegrationSmokeTest.java b/presto-hive/src/test/java/com/facebook/presto/hive/TestHiveIntegrationSmokeTest.java index 7dcb48d386..ff6017a4c4 100644 --- a/presto-hive/src/test/java/com/facebook/presto/hive/TestHiveIntegrationSmokeTest.java +++ b/presto-hive/src/test/java/com/facebook/presto/hive/TestHiveIntegrationSmokeTest.java @@ -144,13 +144,13 @@ public class TestHiveIntegrationSmokeTest { @Language("SQL") String createTable = "" + "CREATE TABLE test_partitioned_table (" + - " _partition_varchar VARCHAR" + - ", _partition_bigint BIGINT" + - ", _varchar VARCHAR" + + " _varchar VARCHAR" + ", _varbinary VARBINARY" + ", _bigint BIGINT" + ", _double DOUBLE" + ", _boolean BOOLEAN" + + ", _partition_varchar VARCHAR" + + ", _partition_bigint BIGINT" + ") " + "WITH (" + "format = '" + storageFormat + "', " + @@ -244,7 +244,6 @@ public class TestHiveIntegrationSmokeTest List<HivePartition> partitions = getPartitions("test_create_partitioned_table_as"); assertEquals(partitions.size(), 3); - // Hive will reorder the partition keys to the end assertQuery("SELECT * from test_create_partitioned_table_as", "SELECT orderkey, shippriority, orderstatus FROM orders"); assertUpdate("DROP TABLE test_create_partitioned_table_as"); @@ -252,6 +251,27 @@ public class TestHiveIntegrationSmokeTest assertFalse(queryRunner.tableExists(getSession(), "test_create_partitioned_table_as")); } + @Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "Partition keys must be the last columns in the table and in the same order as the table properties.*") + public void testCreatePartitionedTableInvalidColumnOrdering() + { + assertUpdate("" + + "CREATE TABLE test_show_columns_partition_key\\n" + + "(grape bigint, apple varchar, orange bigint, pear varchar)\\n" + + "WITH (partitioned_by = ARRAY['apple'])"); + } + + @Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "Partition keys must be the last columns in the table and in the same order as the table properties.*") + public void testCreatePartitionedTableAsInvalidColumnOrdering() + throws Exception + { + assertUpdate("" + + "CREATE TABLE test_create_partitioned_table_as " + + "WITH (partitioned_by = ARRAY['SHIP_PRIORITY', 'ORDER_STATUS']) " + + "AS " + + "SELECT shippriority AS ship_priority, orderkey AS order_key, orderstatus AS order_status " + + "FROM tpch.tiny.orders"); + } + @Test public void insertTable() throws Exception @@ -317,9 +337,9 @@ public class TestHiveIntegrationSmokeTest @Language("SQL") String createTable = "" + "CREATE TABLE test_insert_partitioned_table " + "(" + - " ORDER_STATUS VARCHAR," + + " ORDER_KEY BIGINT," + " SHIP_PRIORITY BIGINT," + - " ORDER_KEY BIGINT" + + " ORDER_STATUS VARCHAR" + ") " + "WITH (" + "format = '" + storageFormat + "', " + @@ -380,9 +400,9 @@ public class TestHiveIntegrationSmokeTest @Language("SQL") String createTable = "" + "CREATE TABLE test_metadata_delete " + "(" + - " LINE_STATUS VARCHAR," + + " ORDER_KEY BIGINT," + " LINE_NUMBER BIGINT," + - " ORDER_KEY BIGINT" + + " LINE_STATUS VARCHAR" + ") " + "WITH (" + STORAGE_FORMAT_PROPERTY + " = '" + storageFormat + "', " + @@ -391,7 +411,6 @@ public class TestHiveIntegrationSmokeTest assertUpdate(createTable); - // Hive will reorder the partition keys, so we must insert into the table assuming the partition keys have been moved to the end assertUpdate("" + "INSERT INTO test_metadata_delete " + "SELECT orderkey, linenumber, linestatus " + @@ -459,10 +478,9 @@ public class TestHiveIntegrationSmokeTest { assertUpdate("" + "CREATE TABLE test_show_columns_partition_key\\n" + - "(grape bigint, apple varchar, orange bigint, pear varchar)\\n" + + "(grape bigint, orange bigint, pear varchar, apple varchar)\\n" + "WITH (partitioned_by = ARRAY['apple'])"); - // partition keys go last and have a special comment MaterializedResult actual = computeActual("SHOW COLUMNS FROM test_show_columns_partition_key"); MaterializedResult expected = resultBuilder(getSession(), VARCHAR, VARCHAR, VARCHAR) .row("grape", "bigint", "")
['presto-hive/src/test/java/com/facebook/presto/hive/TestHiveIntegrationSmokeTest.java', 'presto-hive/src/main/java/com/facebook/presto/hive/HiveMetadata.java', 'presto-hive/src/main/java/com/facebook/presto/hive/HiveErrorCode.java']
{'.java': 3}
3
3
0
0
3
10,245,799
2,033,189
288,703
2,105
956
209
19
2
750
120
166
23
0
2
1970-01-01T00:24:14
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
208
prestodb/presto/4537/4532
prestodb
presto
https://github.com/prestodb/presto/issues/4532
https://github.com/prestodb/presto/pull/4537
https://github.com/prestodb/presto/pull/4537
1
fixes
Unbounded varchar should not be serialized with length
The fact that `varchar` is internally represented as `varchar(MAX_INT)` is an implementation detail that should not leak out and be permanently stored in external systems. It also breaks backwards compatibility with older clients, causes issues in clients that try to allocate a buffer of that size, etc.
09d7a2e16a4e901bfee19836a079dd6c19405d37
918ecbefe2e1c3381457a21ad3dd26ecb49be061
https://github.com/prestodb/presto/compare/09d7a2e16a4e901bfee19836a079dd6c19405d37...918ecbefe2e1c3381457a21ad3dd26ecb49be061
diff --git a/presto-spi/src/main/java/com/facebook/presto/spi/type/TypeSignature.java b/presto-spi/src/main/java/com/facebook/presto/spi/type/TypeSignature.java index 6378252088..24959ed22c 100644 --- a/presto-spi/src/main/java/com/facebook/presto/spi/type/TypeSignature.java +++ b/presto-spi/src/main/java/com/facebook/presto/spi/type/TypeSignature.java @@ -272,9 +272,16 @@ public class TypeSignature @JsonValue public String toString() { + // TODO: remove these hacks if (base.equalsIgnoreCase(StandardTypes.ROW)) { return rowToString(); } + else if (base.equalsIgnoreCase(StandardTypes.VARCHAR) && + (parameters.size() == 1) && + parameters.get(0).isLongLiteral() && + parameters.get(0).getLongLiteral() == VarcharType.MAX_LENGTH) { + return base; + } else { StringBuilder typeName = new StringBuilder(base); if (!parameters.isEmpty()) { diff --git a/presto-spi/src/test/java/com/facebook/presto/spi/type/TestTypeSignature.java b/presto-spi/src/test/java/com/facebook/presto/spi/type/TestTypeSignature.java index aa16aebabf..720d5dc840 100644 --- a/presto-spi/src/test/java/com/facebook/presto/spi/type/TestTypeSignature.java +++ b/presto-spi/src/test/java/com/facebook/presto/spi/type/TestTypeSignature.java @@ -22,6 +22,8 @@ import java.util.List; import java.util.Map; import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature; +import static com.facebook.presto.spi.type.VarcharType.VARCHAR; +import static com.facebook.presto.spi.type.VarcharType.createVarcharType; import static org.testng.Assert.assertEquals; import static org.testng.Assert.fail; @@ -144,6 +146,14 @@ public class TestTypeSignature assertSignature("varchar(10)", "varchar", ImmutableList.<String>of("10")); } + @Test + public void testVarchar() + throws Exception + { + assertEquals(VARCHAR.getTypeSignature().toString(), "varchar"); + assertEquals(createVarcharType(42).getTypeSignature().toString(), "varchar(42)"); + } + private static void assertRowSignature( String typeName, String base,
['presto-spi/src/test/java/com/facebook/presto/spi/type/TestTypeSignature.java', 'presto-spi/src/main/java/com/facebook/presto/spi/type/TypeSignature.java']
{'.java': 2}
2
2
0
0
2
10,291,562
2,041,435
289,735
2,108
319
70
7
1
305
47
57
2
0
0
1970-01-01T00:24:15
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
207
prestodb/presto/4627/4585
prestodb
presto
https://github.com/prestodb/presto/issues/4585
https://github.com/prestodb/presto/pull/4627
https://github.com/prestodb/presto/pull/4627
1
fixes
Uncategorized error for Raptor system table
The catch block needs to be `catch (SQLException | DBIException e)` ``` org.skife.jdbi.v2.exceptions.UnableToObtainConnectionException: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: ... at org.skife.jdbi.v2.DBI.open(DBI.java:230) at com.facebook.presto.raptor.systemtables.ShardMetadataRecordCursor.getTableIds(ShardMetadataRecordCursor.java:321) at com.facebook.presto.raptor.systemtables.ShardMetadataRecordCursor.<init>(ShardMetadataRecordCursor.java:103) at com.facebook.presto.raptor.systemtables.ShardMetadataSystemTable.cursor(ShardMetadataSystemTable.java:57) at com.facebook.presto.connector.system.SystemRecordSetProvider$1.cursor(SystemRecordSetProvider.java:118) at com.facebook.presto.split.MappedRecordSet.cursor(MappedRecordSet.java:53) at com.facebook.presto.spi.RecordPageSource.<init>(RecordPageSource.java:37) at com.facebook.presto.split.RecordPageSourceProvider.createPageSource(RecordPageSourceProvider.java:42) at com.facebook.presto.split.PageSourceManager.createPageSource(PageSourceManager.java:48) at com.facebook.presto.operator.ScanFilterAndProjectOperator.createSourceIfNecessary(ScanFilterAndProjectOperator.java:287) at com.facebook.presto.operator.ScanFilterAndProjectOperator.isFinished(ScanFilterAndProjectOperator.java:180) at com.facebook.presto.operator.Driver.processInternal(Driver.java:377) at com.facebook.presto.operator.Driver.processFor(Driver.java:303) at com.facebook.presto.execution.SqlTaskExecution$DriverSplitRunner.processFor(SqlTaskExecution.java:575) at com.facebook.presto.execution.TaskExecutor$PrioritizedSplitRunner.process(TaskExecutor.java:505) at com.facebook.presto.execution.TaskExecutor$Runner.run(TaskExecutor.java:640) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) ```
5fb01fdf4a0d963ffc2227f4b2f32d2a82451450
e741f6bbb42e4779b7fa12c77941301a963deec3
https://github.com/prestodb/presto/compare/5fb01fdf4a0d963ffc2227f4b2f32d2a82451450...e741f6bbb42e4779b7fa12c77941301a963deec3
diff --git a/presto-raptor/src/main/java/com/facebook/presto/raptor/systemtables/ShardMetadataRecordCursor.java b/presto-raptor/src/main/java/com/facebook/presto/raptor/systemtables/ShardMetadataRecordCursor.java index 7011abd113..68fa9ca885 100644 --- a/presto-raptor/src/main/java/com/facebook/presto/raptor/systemtables/ShardMetadataRecordCursor.java +++ b/presto-raptor/src/main/java/com/facebook/presto/raptor/systemtables/ShardMetadataRecordCursor.java @@ -27,6 +27,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import io.airlift.slice.Slice; import org.skife.jdbi.v2.IDBI; +import org.skife.jdbi.v2.exceptions.DBIException; import java.sql.Connection; import java.sql.PreparedStatement; @@ -181,7 +182,7 @@ public class ShardMetadataRecordCursor completedBytes += resultSetValues.extractValues(resultSet, ImmutableSet.of(getColumnIndex(SHARD_METADATA, SHARD_UUID))); return true; } - catch (SQLException e) { + catch (SQLException | DBIException e) { throw metadataError(e); } } @@ -275,7 +276,7 @@ public class ShardMetadataRecordCursor tupleDomain); return statement.executeQuery(); } - catch (SQLException e) { + catch (SQLException | DBIException e) { close(); throw metadataError(e); } @@ -328,7 +329,7 @@ public class ShardMetadataRecordCursor tableIds.add(resultSet.getLong("table_id")); } } - catch (SQLException e) { + catch (SQLException | DBIException e) { throw metadataError(e); } return tableIds.build().iterator();
['presto-raptor/src/main/java/com/facebook/presto/raptor/systemtables/ShardMetadataRecordCursor.java']
{'.java': 1}
1
1
0
0
1
10,385,747
2,058,356
291,972
2,126
299
68
7
1
1,986
54
462
25
0
1
1970-01-01T00:24:16
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
206
prestodb/presto/4871/4869
prestodb
presto
https://github.com/prestodb/presto/issues/4869
https://github.com/prestodb/presto/pull/4871
https://github.com/prestodb/presto/pull/4871
1
fixes
Potential deadlock when using phased scheduler with broadcast joins
``` sql SELECT * FROM orders CROSS JOIN (VALUES 1); ``` ``` Fragment 0 [SINGLE] Output layout: [orderkey, custkey, orderstatus, totalprice, orderdate, orderpriority, clerk, shippriority, comment, field] Output partitioning: SINGLE [] - Output[orderkey, custkey, orderstatus, totalprice, orderdate, orderpriority, clerk, shippriority, comment, _col9] => [orderkey:bigint, custkey:bigint, orderstatus:varchar, totalprice:double, orderdate:date, orderpriority: _col9 := field - RemoteSource[1] => [orderkey:bigint, custkey:bigint, orderstatus:varchar, totalprice:double, orderdate:date, orderpriority:varchar, clerk:varchar, shippriority:bigint, comment:varchar, field:bigint] Fragment 1 [SOURCE] Output layout: [orderkey, custkey, orderstatus, totalprice, orderdate, orderpriority, clerk, shippriority, comment, field] Output partitioning: SINGLE [] - InnerJoin[] => [orderkey:bigint, custkey:bigint, orderstatus:varchar, totalprice:double, orderdate:date, orderpriority:varchar, clerk:varchar, shippriority:bigint, comment:varchar, field:bigint] - TableScan[tpch:tpch:orders:sf1.0, originalConstraint = true] => [orderkey:bigint, custkey:bigint, orderstatus:varchar, totalprice:double, orderdate:date, orderpriority:varchar, clerk:varchar, shippriority:bigint, comm orderkey := tpch:orderkey custkey := tpch:custkey orderstatus := tpch:orderstatus totalprice := tpch:totalprice orderdate := tpch:orderdate orderpriority := tpch:orderpriority clerk := tpch:clerk shippriority := tpch:shippriority comment := tpch:comment - RemoteSource[2] => [field:bigint] Fragment 2 [SINGLE] Output layout: [field] Output partitioning: BROADCAST [] - Values => [field:bigint] (1) ``` The scheduling dependency graph is missing an edge (2->1), which can cause the join stage to be scheduled independently (and before) the build stage.
b4d90f151c1a649c276f332e2116339e7e844f9e
be0cc2ac232c6467b730f8256e58673f766fade1
https://github.com/prestodb/presto/compare/b4d90f151c1a649c276f332e2116339e7e844f9e...be0cc2ac232c6467b730f8256e58673f766fade1
diff --git a/presto-main/src/main/java/com/facebook/presto/execution/scheduler/PhasedExecutionSchedule.java b/presto-main/src/main/java/com/facebook/presto/execution/scheduler/PhasedExecutionSchedule.java index 29c622be83..1c3f4c1df4 100644 --- a/presto-main/src/main/java/com/facebook/presto/execution/scheduler/PhasedExecutionSchedule.java +++ b/presto-main/src/main/java/com/facebook/presto/execution/scheduler/PhasedExecutionSchedule.java @@ -153,7 +153,12 @@ public class PhasedExecutionSchedule for (DefaultEdge edge : graph.edgeSet()) { PlanFragmentId source = graph.getEdgeSource(edge); PlanFragmentId target = graph.getEdgeTarget(edge); - componentGraph.addEdge(componentMembership.get(source), componentMembership.get(target)); + + Set<PlanFragmentId> from = componentMembership.get(source); + Set<PlanFragmentId> to = componentMembership.get(target); + if (!from.equals(to)) { // the topological order iterator below doesn't include vertices that have self-edges, so don't add them + componentGraph.addEdge(from, to); + } } List<Set<PlanFragmentId>> schedulePhases = ImmutableList.copyOf(new TopologicalOrderIterator<>(componentGraph)); @@ -274,7 +279,7 @@ public class PhasedExecutionSchedule { List<PlanNode> sources = node.getSources(); if (sources.isEmpty()) { - return ImmutableSet.of(); + return ImmutableSet.of(currentFragmentId); } if (sources.size() == 1) { return sources.get(0).accept(this, currentFragmentId); diff --git a/presto-main/src/test/java/com/facebook/presto/execution/scheduler/TestPhasedExecutionSchedule.java b/presto-main/src/test/java/com/facebook/presto/execution/scheduler/TestPhasedExecutionSchedule.java index 45ec18c8ba..97ab602569 100644 --- a/presto-main/src/test/java/com/facebook/presto/execution/scheduler/TestPhasedExecutionSchedule.java +++ b/presto-main/src/test/java/com/facebook/presto/execution/scheduler/TestPhasedExecutionSchedule.java @@ -94,6 +94,17 @@ public class TestPhasedExecutionSchedule assertEquals(phases, ImmutableList.of(ImmutableSet.of(joinFragment.getId()), ImmutableSet.of(buildFragment.getId()), ImmutableSet.of(probeFragment.getId()))); } + @Test + public void testBroadcastJoin() + throws Exception + { + PlanFragment buildFragment = createTableScanPlanFragment("build"); + PlanFragment joinFragment = createBroadcastJoinPlanFragment("join", buildFragment); + + List<Set<PlanFragmentId>> phases = PhasedExecutionSchedule.extractPhases(ImmutableList.of(joinFragment, buildFragment)); + assertEquals(phases, ImmutableList.of(ImmutableSet.of(joinFragment.getId(), buildFragment.getId()))); + } + @Test public void testJoinWithDeepSources() throws Exception @@ -150,6 +161,30 @@ public class TestPhasedExecutionSchedule return createFragment(planNode); } + private static PlanFragment createBroadcastJoinPlanFragment(String name, PlanFragment buildFragment) + { + Symbol symbol = new Symbol("column"); + PlanNode tableScan = new TableScanNode( + new PlanNodeId(name), + new TableHandle("test", new TestingTableHandle()), + ImmutableList.of(symbol), + ImmutableMap.of(symbol, new TestingColumnHandle("column")), + Optional.empty(), + TupleDomain.all(), + null); + + PlanNode join = new JoinNode( + new PlanNodeId(name + "_id"), + INNER, + tableScan, + new RemoteSourceNode(new PlanNodeId("build_id"), buildFragment.getId(), ImmutableList.of()), + ImmutableList.of(), + Optional.<Symbol>empty(), + Optional.<Symbol>empty()); + + return createFragment(join); + } + private static PlanFragment createJoinPlanFragment(String name, PlanFragment buildFragment, PlanFragment probeFragment) { PlanNode planNode = new JoinNode(
['presto-main/src/main/java/com/facebook/presto/execution/scheduler/PhasedExecutionSchedule.java', 'presto-main/src/test/java/com/facebook/presto/execution/scheduler/TestPhasedExecutionSchedule.java']
{'.java': 2}
2
2
0
0
2
10,524,650
2,084,709
295,533
2,146
559
99
9
1
5,963
183
583
37
0
2
1970-01-01T00:24:18
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
205
prestodb/presto/5055/4901
prestodb
presto
https://github.com/prestodb/presto/issues/4901
https://github.com/prestodb/presto/pull/5055
https://github.com/prestodb/presto/pull/5055
1
fixes
try(cast(...)) fails with multiple predicates in a where clause
When I run the following query: ``` sql with example as ( select id, other_id from ( values (1, '23452'), (3, '2354') ) as t (id, other_id) ) select try(cast(other_id as bigint)) as other_id from example where id = 1 and try(cast(other_id as bigint)) is not null ``` It produces the error message: `Compiler failed and interpreter is disabled` When I remove the `id = 1` in the final query, the query works as expected.
747603c9539bf8d20b625e597d392bc1538a983c
c9d6b954fbd7d240c6c096ba1e36fdf92bb786b6
https://github.com/prestodb/presto/compare/747603c9539bf8d20b625e597d392bc1538a983c...c9d6b954fbd7d240c6c096ba1e36fdf92bb786b6
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/gen/BytecodeExpressionVisitor.java b/presto-main/src/main/java/com/facebook/presto/sql/gen/BytecodeExpressionVisitor.java index 4bc29acfa3..fae3a4ea5d 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/gen/BytecodeExpressionVisitor.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/gen/BytecodeExpressionVisitor.java @@ -17,14 +17,12 @@ import com.facebook.presto.bytecode.BytecodeBlock; import com.facebook.presto.bytecode.BytecodeNode; import com.facebook.presto.bytecode.MethodDefinition; import com.facebook.presto.bytecode.Scope; -import com.facebook.presto.bytecode.Variable; import com.facebook.presto.metadata.FunctionRegistry; import com.facebook.presto.sql.relational.CallExpression; import com.facebook.presto.sql.relational.ConstantExpression; import com.facebook.presto.sql.relational.InputReferenceExpression; import com.facebook.presto.sql.relational.RowExpressionVisitor; -import java.util.List; import java.util.Map; import static com.facebook.presto.bytecode.expression.BytecodeExpressions.constantTrue; @@ -51,7 +49,6 @@ public class BytecodeExpressionVisitor private final CachedInstanceBinder cachedInstanceBinder; private final RowExpressionVisitor<Scope, BytecodeNode> fieldReferenceCompiler; private final FunctionRegistry registry; - private final List<? extends Variable> expressionInputs; private final Map<CallExpression, MethodDefinition> tryExpressionsMap; public BytecodeExpressionVisitor( @@ -59,14 +56,12 @@ public class BytecodeExpressionVisitor CachedInstanceBinder cachedInstanceBinder, RowExpressionVisitor<Scope, BytecodeNode> fieldReferenceCompiler, FunctionRegistry registry, - List<? extends Variable> expressionInputs, Map<CallExpression, MethodDefinition> tryExpressionsMap) { this.callSiteBinder = callSiteBinder; this.cachedInstanceBinder = cachedInstanceBinder; this.fieldReferenceCompiler = fieldReferenceCompiler; this.registry = registry; - this.expressionInputs = expressionInputs; this.tryExpressionsMap = tryExpressionsMap; } @@ -92,7 +87,7 @@ public class BytecodeExpressionVisitor generator = new SwitchCodeGenerator(); break; case TRY: - generator = new TryCodeGenerator(tryExpressionsMap, expressionInputs); + generator = new TryCodeGenerator(tryExpressionsMap); break; // functions that take null as input case IS_NULL: diff --git a/presto-main/src/main/java/com/facebook/presto/sql/gen/CursorProcessorCompiler.java b/presto-main/src/main/java/com/facebook/presto/sql/gen/CursorProcessorCompiler.java index 93996bc763..656a41901a 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/gen/CursorProcessorCompiler.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/gen/CursorProcessorCompiler.java @@ -204,7 +204,6 @@ public class CursorProcessorCompiler cachedInstanceBinder, fieldReferenceCompiler(cursor, wasNull), metadata.getFunctionRegistry(), - inputParameters, tryMethodMap.build()); MethodDefinition tryMethod = defineTryMethod( @@ -241,7 +240,6 @@ public class CursorProcessorCompiler cachedInstanceBinder, fieldReferenceCompiler(cursor, wasNullVariable), metadata.getFunctionRegistry(), - ImmutableList.of(session, cursor, wasNullVariable), tryMethodMap); LabelNode end = new LabelNode("end"); @@ -282,7 +280,6 @@ public class CursorProcessorCompiler cachedInstanceBinder, fieldReferenceCompiler(cursor, wasNullVariable), metadata.getFunctionRegistry(), - ImmutableList.of(session, cursor, wasNullVariable), tryMethodMap); body.getVariable(output) diff --git a/presto-main/src/main/java/com/facebook/presto/sql/gen/PageProcessorCompiler.java b/presto-main/src/main/java/com/facebook/presto/sql/gen/PageProcessorCompiler.java index 53f3e408d4..4269cef01d 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/gen/PageProcessorCompiler.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/gen/PageProcessorCompiler.java @@ -750,21 +750,20 @@ public class PageProcessorCompiler Parameter position = arg("position", int.class); Parameter wasNullVariable = arg("wasNull", boolean.class); - List<Parameter> inputParameters = ImmutableList.<Parameter>builder() - .add(session) - .addAll(blocks) - .add(position) - .add(wasNullVariable) - .build(); - BytecodeExpressionVisitor innerExpressionVisitor = new BytecodeExpressionVisitor( callSiteBinder, cachedInstanceBinder, fieldReferenceCompiler(callSiteBinder, position, wasNullVariable), metadata.getFunctionRegistry(), - inputParameters, tryMethodMap.build()); + List<Parameter> inputParameters = ImmutableList.<Parameter>builder() + .add(session) + .addAll(blocks) + .add(position) + .add(wasNullVariable) + .build(); + MethodDefinition tryMethod = defineTryMethod( innerExpressionVisitor, containerClassDefinition, @@ -789,17 +788,15 @@ public class PageProcessorCompiler List<Parameter> blocks = toBlockParameters(getInputChannels(filter)); Parameter position = arg("position", int.class); - List<Parameter> expressionInputs = ImmutableList.<Parameter>builder() - .add(session) - .addAll(blocks) - .add(position) - .build(); - MethodDefinition method = classDefinition.declareMethod( a(PUBLIC), "filter", type(boolean.class), - expressionInputs); + ImmutableList.<Parameter>builder() + .add(session) + .addAll(blocks) + .add(position) + .build()); method.comment("Filter: %s", filter.toString()); BytecodeBlock body = method.getBody(); @@ -812,10 +809,6 @@ public class PageProcessorCompiler cachedInstanceBinder, fieldReferenceCompiler(callSiteBinder, position, wasNullVariable), metadata.getFunctionRegistry(), - ImmutableList.<Variable>builder() - .addAll(expressionInputs) - .add(wasNullVariable) - .build(), tryMethodMap); BytecodeNode visitorBody = filter.accept(visitor, scope); @@ -838,18 +831,14 @@ public class PageProcessorCompiler Parameter position = arg("position", int.class); Parameter output = arg("output", BlockBuilder.class); - List<Parameter> expressionInputs = ImmutableList.<Parameter>builder() - .add(session) - .addAll(blocks) - .add(position) - .build(); - MethodDefinition method = classDefinition.declareMethod( a(PUBLIC), methodName, type(void.class), ImmutableList.<Parameter>builder() - .addAll(expressionInputs) + .add(session) + .addAll(blocks) + .add(position) .add(output) .build()); @@ -864,10 +853,6 @@ public class PageProcessorCompiler cachedInstanceBinder, fieldReferenceCompiler(callSiteBinder, position, wasNullVariable), metadata.getFunctionRegistry(), - ImmutableList.<Variable>builder() - .addAll(expressionInputs) - .add(wasNullVariable) - .build(), tryMethodMap ); diff --git a/presto-main/src/main/java/com/facebook/presto/sql/gen/TryCodeGenerator.java b/presto-main/src/main/java/com/facebook/presto/sql/gen/TryCodeGenerator.java index 25e23d17d7..f3cfb733c1 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/gen/TryCodeGenerator.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/gen/TryCodeGenerator.java @@ -20,7 +20,6 @@ import com.facebook.presto.bytecode.MethodDefinition; import com.facebook.presto.bytecode.Parameter; import com.facebook.presto.bytecode.ParameterizedType; import com.facebook.presto.bytecode.Scope; -import com.facebook.presto.bytecode.Variable; import com.facebook.presto.bytecode.control.TryCatch; import com.facebook.presto.metadata.Signature; import com.facebook.presto.spi.PrestoException; @@ -56,12 +55,10 @@ public class TryCodeGenerator private static final String EXCEPTION_HANDLER_NAME = "tryExpressionExceptionHandler"; private final Map<CallExpression, MethodDefinition> tryMethodsMap; - private final List<? extends Variable> inputParameters; - public TryCodeGenerator(Map<CallExpression, MethodDefinition> tryMethodsMap, List<? extends Variable> inputParameters) + public TryCodeGenerator(Map<CallExpression, MethodDefinition> tryMethodsMap) { this.tryMethodsMap = tryMethodsMap; - this.inputParameters = inputParameters; } @Override @@ -77,11 +74,14 @@ public class TryCodeGenerator .comment("load required variables") .getVariable(context.getScope().getVariable("this")); - inputParameters.stream() + MethodDefinition definition = tryMethodsMap.get(innerCallExpression); + + definition.getParameters().stream() + .map(parameter -> context.getScope().getVariable(parameter.getName())) .forEach(bytecodeBlock::getVariable); - bytecodeBlock.comment("call dynamic try method: " + tryMethodsMap.get(innerCallExpression).getName()) - .invokeVirtual(tryMethodsMap.get(innerCallExpression)) + bytecodeBlock.comment("call dynamic try method: " + definition.getName()) + .invokeVirtual(definition) .append(unboxPrimitiveIfNecessary(context.getScope(), Primitives.wrap(innerCallExpression.getType().getJavaType()))); return bytecodeBlock; diff --git a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java index eae6e30275..70819db65c 100644 --- a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java +++ b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java @@ -4306,6 +4306,11 @@ public abstract class AbstractTestQueries assertQuery( "SELECT COUNT(TRY(to_base(100, CAST(round(totalprice/100) AS BIGINT)))) FROM orders", "SELECT SUM(CASE WHEN CAST(round(totalprice/100) AS BIGINT) BETWEEN 2 AND 36 THEN 1 ELSE 0 END) FROM orders"); + + // as part of a complex expression + assertQuery( + "SELECT COUNT(CAST(orderkey AS VARCHAR) || TRY(to_base(100, CAST(round(totalprice/100) AS BIGINT)))) FROM orders", + "SELECT SUM(CASE WHEN CAST(round(totalprice/100) AS BIGINT) BETWEEN 2 AND 36 THEN 1 ELSE 0 END) FROM orders"); } @Test
['presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java', 'presto-main/src/main/java/com/facebook/presto/sql/gen/TryCodeGenerator.java', 'presto-main/src/main/java/com/facebook/presto/sql/gen/CursorProcessorCompiler.java', 'presto-main/src/main/java/com/facebook/presto/sql/gen/BytecodeExpressionVisitor.java', 'presto-main/src/main/java/com/facebook/presto/sql/gen/PageProcessorCompiler.java']
{'.java': 5}
5
5
0
0
5
10,859,413
2,151,335
303,974
2,194
3,248
516
69
4
480
75
132
25
0
1
1970-01-01T00:24:21
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
204
prestodb/presto/5073/5057
prestodb
presto
https://github.com/prestodb/presto/issues/5057
https://github.com/prestodb/presto/pull/5073
https://github.com/prestodb/presto/pull/5073
2
fix
Date constructor should handle year 0 correctly
Year zero is converted to January 2nd of 1 AD: ``` presto> select date '0000-12-31'; _col0 ------------ 0001-01-02 (1 row) ``` It should be rejected, similar to other invalid dates: ``` presto> select date '2015-02-29'; Query ... failed: Value cannot be cast to date: 2015-02-29 presto> select date '2016-12-32'; Query ... failed: Value cannot be cast to date: 2016-12-32 ```
7b0d0e02536bcb485b6e0c9a3c6959fa8cb67491
d06fe75c1551639f5bc96e86b22038b15f596843
https://github.com/prestodb/presto/compare/7b0d0e02536bcb485b6e0c9a3c6959fa8cb67491...d06fe75c1551639f5bc96e86b22038b15f596843
diff --git a/presto-main/src/test/java/com/facebook/presto/operator/scalar/FunctionAssertions.java b/presto-main/src/test/java/com/facebook/presto/operator/scalar/FunctionAssertions.java index b478b32aa8..0cc40f4a94 100644 --- a/presto-main/src/test/java/com/facebook/presto/operator/scalar/FunctionAssertions.java +++ b/presto-main/src/test/java/com/facebook/presto/operator/scalar/FunctionAssertions.java @@ -232,6 +232,17 @@ public final class FunctionAssertions } } + public void assertFunctionString(String projection, Type expectedType, String expected) + { + Object actual = selectSingleValue(projection, expectedType, compiler); + try { + assertEquals(actual.toString(), expected); + } + catch (Throwable e) { + throw e; + } + } + public void tryEvaluate(String expression, Type expectedType) { tryEvaluate(expression, expectedType, session); diff --git a/presto-main/src/test/java/com/facebook/presto/operator/scalar/TestDateTimeFunctions.java b/presto-main/src/test/java/com/facebook/presto/operator/scalar/TestDateTimeFunctions.java index 35d2801a5e..8c57fef0ce 100644 --- a/presto-main/src/test/java/com/facebook/presto/operator/scalar/TestDateTimeFunctions.java +++ b/presto-main/src/test/java/com/facebook/presto/operator/scalar/TestDateTimeFunctions.java @@ -820,11 +820,51 @@ public class TestDateTimeFunctions toTimestampWithTimeZone(new DateTime(2013, 5, 17, 0, 35, 10, 0, DATE_TIME_ZONE))); } + @Test + public void testDateTimeOutputString() + { + // SqlDate + assertFunctionString("date '2012-12-31'", DateType.DATE, "2012-12-31"); + assertFunctionString("date '0000-12-31'", DateType.DATE, "0000-12-31"); + assertFunctionString("date '0000-09-23'", DateType.DATE, "0000-09-23"); + assertFunctionString("date '0001-10-25'", DateType.DATE, "0001-10-25"); + assertFunctionString("date '1560-04-29'", DateType.DATE, "1560-04-29"); + + // SqlTime + assertFunctionString("time '00:00:00'", TimeType.TIME, "00:00:00.000"); + assertFunctionString("time '01:02:03'", TimeType.TIME, "01:02:03.000"); + assertFunctionString("time '23:23:23.233'", TimeType.TIME, "23:23:23.233"); + assertFunctionString("time '23:59:59.999'", TimeType.TIME, "23:59:59.999"); + + // SqlTimeWithTimeZone + assertFunctionString("time '00:00:00 UTC'", TIME_WITH_TIME_ZONE, "00:00:00.000 UTC"); + assertFunctionString("time '01:02:03 Asia/Shanghai'", TIME_WITH_TIME_ZONE, "01:02:03.000 Asia/Shanghai"); + assertFunctionString("time '23:23:23.233 America/Los_Angeles'", TIME_WITH_TIME_ZONE, "23:23:23.233 America/Los_Angeles"); + assertFunctionString(WEIRD_TIME_LITERAL, TIME_WITH_TIME_ZONE, "03:04:05.321 +07:09"); + + // SqlTimestamp + assertFunctionString("timestamp '0000-01-02 01:02:03'", TimestampType.TIMESTAMP, "0000-01-02 01:02:03.000"); + assertFunctionString("timestamp '2012-12-31 00:00:00'", TimestampType.TIMESTAMP, "2012-12-31 00:00:00.000"); + assertFunctionString("timestamp '1234-05-06 23:23:23.233'", TimestampType.TIMESTAMP, "1234-05-06 23:23:23.233"); + assertFunctionString("timestamp '2333-02-23 23:59:59.999'", TimestampType.TIMESTAMP, "2333-02-23 23:59:59.999"); + + // SqlTimestampWithTimeZone + assertFunctionString("timestamp '2012-12-31 00:00:00 UTC'", TIMESTAMP_WITH_TIME_ZONE, "2012-12-31 00:00:00.000 UTC"); + assertFunctionString("timestamp '0000-01-02 01:02:03 Asia/Shanghai'", TIMESTAMP_WITH_TIME_ZONE, "0000-01-02 01:02:03.000 Asia/Shanghai"); + assertFunctionString("timestamp '1234-05-06 23:23:23.233 America/Los_Angeles'", TIMESTAMP_WITH_TIME_ZONE, "1234-05-06 23:23:23.233 America/Los_Angeles"); + assertFunctionString("timestamp '2333-02-23 23:59:59.999 Asia/Tokyo'", TIMESTAMP_WITH_TIME_ZONE, "2333-02-23 23:59:59.999 Asia/Tokyo"); + } + private void assertFunction(String projection, Type expectedType, Object expected) { functionAssertions.assertFunction(projection, expectedType, expected); } + private void assertFunctionString(String projection, Type expectedType, String expected) + { + functionAssertions.assertFunctionString(projection, expectedType, expected); + } + private SqlDate toDate(DateTime dateDate) { long millis = dateDate.getMillis(); diff --git a/presto-spi/src/main/java/com/facebook/presto/spi/type/SqlDate.java b/presto-spi/src/main/java/com/facebook/presto/spi/type/SqlDate.java index 4171f4a56b..6a13509b44 100644 --- a/presto-spi/src/main/java/com/facebook/presto/spi/type/SqlDate.java +++ b/presto-spi/src/main/java/com/facebook/presto/spi/type/SqlDate.java @@ -15,13 +15,8 @@ package com.facebook.presto.spi.type; import com.fasterxml.jackson.annotation.JsonValue; -import java.text.SimpleDateFormat; -import java.util.Date; +import java.time.LocalDate; import java.util.Objects; -import java.util.concurrent.TimeUnit; - -import static com.facebook.presto.spi.type.TimeZoneIndex.getTimeZoneForKey; -import static com.facebook.presto.spi.type.TimeZoneKey.UTC_KEY; public final class SqlDate { @@ -60,8 +55,6 @@ public final class SqlDate @Override public String toString() { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); - format.setTimeZone(getTimeZoneForKey(UTC_KEY)); - return format.format(new Date(TimeUnit.DAYS.toMillis(days))); + return LocalDate.ofEpochDay(days).toString(); } } diff --git a/presto-spi/src/main/java/com/facebook/presto/spi/type/SqlTime.java b/presto-spi/src/main/java/com/facebook/presto/spi/type/SqlTime.java index 8858ef09d2..3a883c7aa0 100644 --- a/presto-spi/src/main/java/com/facebook/presto/spi/type/SqlTime.java +++ b/presto-spi/src/main/java/com/facebook/presto/spi/type/SqlTime.java @@ -15,14 +15,15 @@ package com.facebook.presto.spi.type; import com.fasterxml.jackson.annotation.JsonValue; -import java.text.SimpleDateFormat; -import java.util.Date; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; import java.util.Objects; -import static com.facebook.presto.spi.type.TimeZoneIndex.getTimeZoneForKey; - public final class SqlTime { + private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss.SSS"); + private final long millisUtc; private final TimeZoneKey sessionTimeZoneKey; @@ -66,8 +67,6 @@ public final class SqlTime @Override public String toString() { - SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss.SSS"); - format.setTimeZone(getTimeZoneForKey(sessionTimeZoneKey)); - return format.format(new Date(millisUtc)); + return Instant.ofEpochMilli(millisUtc).atZone(ZoneId.of(sessionTimeZoneKey.getId())).format(formatter); } } diff --git a/presto-spi/src/main/java/com/facebook/presto/spi/type/SqlTimeWithTimeZone.java b/presto-spi/src/main/java/com/facebook/presto/spi/type/SqlTimeWithTimeZone.java index e63867d8cd..ba09d16550 100644 --- a/presto-spi/src/main/java/com/facebook/presto/spi/type/SqlTimeWithTimeZone.java +++ b/presto-spi/src/main/java/com/facebook/presto/spi/type/SqlTimeWithTimeZone.java @@ -15,17 +15,19 @@ package com.facebook.presto.spi.type; import com.fasterxml.jackson.annotation.JsonValue; -import java.text.SimpleDateFormat; -import java.util.Date; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; import java.util.Objects; import java.util.TimeZone; import static com.facebook.presto.spi.type.DateTimeEncoding.unpackMillisUtc; import static com.facebook.presto.spi.type.DateTimeEncoding.unpackZoneKey; -import static com.facebook.presto.spi.type.TimeZoneIndex.getTimeZoneForKey; public final class SqlTimeWithTimeZone { + private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss.SSS VV"); + private final long millisUtc; private final TimeZoneKey timeZoneKey; @@ -81,8 +83,6 @@ public final class SqlTimeWithTimeZone @Override public String toString() { - SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss.SSS"); - format.setTimeZone(getTimeZoneForKey(timeZoneKey)); - return format.format(new Date(millisUtc)) + " " + timeZoneKey.getId(); + return Instant.ofEpochMilli(millisUtc).atZone(ZoneId.of(timeZoneKey.getId())).format(formatter); } } diff --git a/presto-spi/src/main/java/com/facebook/presto/spi/type/SqlTimestamp.java b/presto-spi/src/main/java/com/facebook/presto/spi/type/SqlTimestamp.java index eaa68b3c9f..6290daa6ea 100644 --- a/presto-spi/src/main/java/com/facebook/presto/spi/type/SqlTimestamp.java +++ b/presto-spi/src/main/java/com/facebook/presto/spi/type/SqlTimestamp.java @@ -15,14 +15,15 @@ package com.facebook.presto.spi.type; import com.fasterxml.jackson.annotation.JsonValue; -import java.text.SimpleDateFormat; -import java.util.Date; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; import java.util.Objects; -import static com.facebook.presto.spi.type.TimeZoneIndex.getTimeZoneForKey; - public final class SqlTimestamp { + private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS"); + private final long millisUtc; private final TimeZoneKey sessionTimeZoneKey; @@ -66,8 +67,6 @@ public final class SqlTimestamp @Override public String toString() { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); - format.setTimeZone(getTimeZoneForKey(sessionTimeZoneKey)); - return format.format(new Date(millisUtc)); + return Instant.ofEpochMilli(millisUtc).atZone(ZoneId.of(sessionTimeZoneKey.getId())).format(formatter); } } diff --git a/presto-spi/src/main/java/com/facebook/presto/spi/type/SqlTimestampWithTimeZone.java b/presto-spi/src/main/java/com/facebook/presto/spi/type/SqlTimestampWithTimeZone.java index e171f42743..b9ad4eb7de 100644 --- a/presto-spi/src/main/java/com/facebook/presto/spi/type/SqlTimestampWithTimeZone.java +++ b/presto-spi/src/main/java/com/facebook/presto/spi/type/SqlTimestampWithTimeZone.java @@ -15,17 +15,19 @@ package com.facebook.presto.spi.type; import com.fasterxml.jackson.annotation.JsonValue; -import java.text.SimpleDateFormat; -import java.util.Date; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; import java.util.Objects; import java.util.TimeZone; import static com.facebook.presto.spi.type.DateTimeEncoding.unpackMillisUtc; import static com.facebook.presto.spi.type.DateTimeEncoding.unpackZoneKey; -import static com.facebook.presto.spi.type.TimeZoneIndex.getTimeZoneForKey; public final class SqlTimestampWithTimeZone { + private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS VV"); + private final long millisUtc; private final TimeZoneKey timeZoneKey; @@ -81,8 +83,6 @@ public final class SqlTimestampWithTimeZone @Override public String toString() { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); - format.setTimeZone(getTimeZoneForKey(timeZoneKey)); - return format.format(new Date(millisUtc)) + " " + timeZoneKey.getId(); + return Instant.ofEpochMilli(millisUtc).atZone(ZoneId.of(timeZoneKey.getId())).format(formatter); } }
['presto-main/src/test/java/com/facebook/presto/operator/scalar/TestDateTimeFunctions.java', 'presto-spi/src/main/java/com/facebook/presto/spi/type/SqlTimestamp.java', 'presto-main/src/test/java/com/facebook/presto/operator/scalar/FunctionAssertions.java', 'presto-spi/src/main/java/com/facebook/presto/spi/type/SqlTimestampWithTimeZone.java', 'presto-spi/src/main/java/com/facebook/presto/spi/type/SqlTime.java', 'presto-spi/src/main/java/com/facebook/presto/spi/type/SqlTimeWithTimeZone.java', 'presto-spi/src/main/java/com/facebook/presto/spi/type/SqlDate.java']
{'.java': 7}
7
7
0
0
7
11,227,093
2,223,483
314,056
2,274
3,175
632
61
5
389
60
128
20
0
2
1970-01-01T00:24:21
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
203
prestodb/presto/5123/5110
prestodb
presto
https://github.com/prestodb/presto/issues/5110
https://github.com/prestodb/presto/pull/5123
https://github.com/prestodb/presto/pull/5123
1
fix
Race condition in array_concat
A query like: ``` sql select count(x) from ( select concat(a, b) x from t ) ``` where `a` and `b` are of type `array(map(string, double))`, fails non-deterministically with various exceptions (Presto version 0.144.2): ``` java.lang.IllegalStateException: closeEntry called before anything is written at com.facebook.presto.spi.block.InterleavedBlockBuilder.closeEntry(InterleavedBlockBuilder.java:212) at com.facebook.presto.spi.block.ArrayElementBlockWriter.closeEntry(ArrayElementBlockWriter.java:127) at com.facebook.presto.spi.block.AbstractArrayBlock.writePositionTo(AbstractArrayBlock.java:155) at com.facebook.presto.type.MapType.appendTo(MapType.java:192) at com.facebook.presto.operator.scalar.ArrayConcatFunction.concat(ArrayConcatFunction.java:53) at com_facebook_presto_$gen_CursorProcessor_37019.project_0(Unknown Source) at com_facebook_presto_$gen_CursorProcessor_37019.process(Unknown Source) at com.facebook.presto.operator.ScanFilterAndProjectOperator.getOutput(ScanFilterAndProjectOperator.java:215) at com.facebook.presto.operator.Driver.processInternal(Driver.java:380) at com.facebook.presto.operator.Driver.processFor(Driver.java:303) at com.facebook.presto.execution.SqlTaskExecution$DriverSplitRunner.processFor(SqlTaskExecution.java:577) at com.facebook.presto.execution.TaskExecutor$PrioritizedSplitRunner.process(TaskExecutor.java:529) at com.facebook.presto.execution.TaskExecutor$Runner.run(TaskExecutor.java:665) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) ``` ``` Query 20160425_183530_20138_n949w failed: Expected current entry size to be exactly 0 but was 0 java.lang.IllegalStateException: Expected current entry size to be exactly 0 but was 0 at com.facebook.presto.spi.block.ArrayBlockBuilder.beginBlockEntry(ArrayBlockBuilder.java:193) at com.facebook.presto.spi.block.ArrayBlockBuilder.beginBlockEntry(ArrayBlockBuilder.java:24) at com.facebook.presto.spi.block.AbstractArrayBlock.writePositionTo(AbstractArrayBlock.java:146) at com.facebook.presto.type.MapType.appendTo(MapType.java:192) at com.facebook.presto.operator.scalar.ArrayConcatFunction.concat(ArrayConcatFunction.java:53) at com_facebook_presto_$gen_CursorProcessor_36742.project_0(Unknown Source) at com_facebook_presto_$gen_CursorProcessor_36742.process(Unknown Source) at com.facebook.presto.operator.ScanFilterAndProjectOperator.getOutput(ScanFilterAndProjectOperator.java:215) at com.facebook.presto.operator.Driver.processInternal(Driver.java:380) at com.facebook.presto.operator.Driver.processFor(Driver.java:303) at com.facebook.presto.execution.SqlTaskExecution$DriverSplitRunner.processFor(SqlTaskExecution.java:577) at com.facebook.presto.execution.TaskExecutor$PrioritizedSplitRunner.process(TaskExecutor.java:529) at com.facebook.presto.execution.TaskExecutor$Runner.run(TaskExecutor.java:665) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) ``` ``` Query 20160425_183539_20170_n949w failed: Expected current entry size to be exactly 0 but was 1 java.lang.IllegalStateException: Expected current entry size to be exactly 0 but was 1 at com.facebook.presto.spi.block.ArrayBlockBuilder.beginBlockEntry(ArrayBlockBuilder.java:193) at com.facebook.presto.spi.block.ArrayBlockBuilder.beginBlockEntry(ArrayBlockBuilder.java:24) at com.facebook.presto.spi.block.AbstractArrayBlock.writePositionTo(AbstractArrayBlock.java:146) at com.facebook.presto.type.MapType.appendTo(MapType.java:192) at com.facebook.presto.operator.scalar.ArrayConcatFunction.concat(ArrayConcatFunction.java:53) at com_facebook_presto_$gen_CursorProcessor_37840.project_0(Unknown Source) at com_facebook_presto_$gen_CursorProcessor_37840.process(Unknown Source) at com.facebook.presto.operator.ScanFilterAndProjectOperator.getOutput(ScanFilterAndProjectOperator.java:215) at com.facebook.presto.operator.Driver.processInternal(Driver.java:380) at com.facebook.presto.operator.Driver.processFor(Driver.java:303) at com.facebook.presto.execution.SqlTaskExecution$DriverSplitRunner.processFor(SqlTaskExecution.java:577) at com.facebook.presto.execution.TaskExecutor$PrioritizedSplitRunner.process(TaskExecutor.java:529) at com.facebook.presto.execution.TaskExecutor$Runner.run(TaskExecutor.java:665) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) ```
7beadecb0d85efc5e33bd0f7505d8c8347dd81dd
73ccbf177d312daaff7c8c585f5d230ef468c722
https://github.com/prestodb/presto/compare/7beadecb0d85efc5e33bd0f7505d8c8347dd81dd...73ccbf177d312daaff7c8c585f5d230ef468c722
diff --git a/presto-hive/src/test/java/com/facebook/presto/hive/TestOrcPageSourceMemoryTracking.java b/presto-hive/src/test/java/com/facebook/presto/hive/TestOrcPageSourceMemoryTracking.java index 05aad9aeca..db5ca3f689 100644 --- a/presto-hive/src/test/java/com/facebook/presto/hive/TestOrcPageSourceMemoryTracking.java +++ b/presto-hive/src/test/java/com/facebook/presto/hive/TestOrcPageSourceMemoryTracking.java @@ -419,7 +419,7 @@ public class TestOrcPageSourceMemoryTracking new PlanNodeId("test"), new PlanNodeId("0"), (session, split, columnHandles) -> pageSource, - new GenericCursorProcessor(FilterFunctions.TRUE_FUNCTION, projections), + () -> new GenericCursorProcessor(FilterFunctions.TRUE_FUNCTION, projections), () -> new GenericPageProcessor(FilterFunctions.TRUE_FUNCTION, projections), columns.stream().map(columnHandle -> (ColumnHandle) columnHandle).collect(toList()), types diff --git a/presto-main/src/main/java/com/facebook/presto/operator/ScanFilterAndProjectOperator.java b/presto-main/src/main/java/com/facebook/presto/operator/ScanFilterAndProjectOperator.java index 0518c3e982..4492c1d74c 100644 --- a/presto-main/src/main/java/com/facebook/presto/operator/ScanFilterAndProjectOperator.java +++ b/presto-main/src/main/java/com/facebook/presto/operator/ScanFilterAndProjectOperator.java @@ -299,7 +299,7 @@ public class ScanFilterAndProjectOperator { private final int operatorId; private final PlanNodeId planNodeId; - private final CursorProcessor cursorProcessor; + private final Supplier<CursorProcessor> cursorProcessor; private final Supplier<PageProcessor> pageProcessor; private final PlanNodeId sourceId; private final PageSourceProvider pageSourceProvider; @@ -312,7 +312,7 @@ public class ScanFilterAndProjectOperator PlanNodeId planNodeId, PlanNodeId sourceId, PageSourceProvider pageSourceProvider, - CursorProcessor cursorProcessor, + Supplier<CursorProcessor> cursorProcessor, Supplier<PageProcessor> pageProcessor, Iterable<ColumnHandle> columns, List<Type> types) @@ -348,7 +348,7 @@ public class ScanFilterAndProjectOperator operatorContext, sourceId, pageSourceProvider, - cursorProcessor, + cursorProcessor.get(), pageProcessor.get(), columns, types); diff --git a/presto-main/src/main/java/com/facebook/presto/sql/gen/ExpressionCompiler.java b/presto-main/src/main/java/com/facebook/presto/sql/gen/ExpressionCompiler.java index aad8240bb1..ec012e2b2e 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/gen/ExpressionCompiler.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/gen/ExpressionCompiler.java @@ -81,15 +81,17 @@ public class ExpressionCompiler return pageProcessors.size(); } - public CursorProcessor compileCursorProcessor(RowExpression filter, List<RowExpression> projections, Object uniqueKey) + public Supplier<CursorProcessor> compileCursorProcessor(RowExpression filter, List<RowExpression> projections, Object uniqueKey) { - try { - return cursorProcessors.getUnchecked(new CacheKey(filter, projections, uniqueKey)) - .newInstance(); - } - catch (ReflectiveOperationException e) { - throw Throwables.propagate(e); - } + Class<? extends CursorProcessor> cursorProcessor = cursorProcessors.getUnchecked(new CacheKey(filter, projections, uniqueKey)); + return () -> { + try { + return cursorProcessor.newInstance(); + } + catch (ReflectiveOperationException e) { + throw Throwables.propagate(e); + } + }; } public Supplier<PageProcessor> compilePageProcessor(RowExpression filter, List<RowExpression> projections) diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/LocalExecutionPlanner.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/LocalExecutionPlanner.java index f98890a7e4..f4e8e6e6eb 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/LocalExecutionPlanner.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/LocalExecutionPlanner.java @@ -978,7 +978,7 @@ public class LocalExecutionPlanner try { if (columns != null) { - CursorProcessor cursorProcessor = compiler.compileCursorProcessor(translatedFilter, translatedProjections, sourceNode.getId()); + Supplier<CursorProcessor> cursorProcessor = compiler.compileCursorProcessor(translatedFilter, translatedProjections, sourceNode.getId()); Supplier<PageProcessor> pageProcessor = compiler.compilePageProcessor(translatedFilter, translatedProjections); SourceOperatorFactory operatorFactory = new ScanFilterAndProjectOperator.ScanFilterAndProjectOperatorFactory( @@ -1050,7 +1050,7 @@ public class LocalExecutionPlanner planNodeId, sourceNode.getId(), pageSourceProvider, - new GenericCursorProcessor(filterFunction, projectionFunctions), + () -> new GenericCursorProcessor(filterFunction, projectionFunctions), () -> new GenericPageProcessor(filterFunction, projectionFunctions), columns, toTypes(projectionFunctions)); diff --git a/presto-main/src/test/java/com/facebook/presto/operator/TestScanFilterAndProjectOperator.java b/presto-main/src/test/java/com/facebook/presto/operator/TestScanFilterAndProjectOperator.java index 1ed44ce165..d9ccc89e6f 100644 --- a/presto-main/src/test/java/com/facebook/presto/operator/TestScanFilterAndProjectOperator.java +++ b/presto-main/src/test/java/com/facebook/presto/operator/TestScanFilterAndProjectOperator.java @@ -71,7 +71,7 @@ public class TestScanFilterAndProjectOperator return new FixedPageSource(ImmutableList.of(input)); } }, - new GenericCursorProcessor(FilterFunctions.TRUE_FUNCTION, ImmutableList.of(singleColumn(VARCHAR, 0))), + () -> new GenericCursorProcessor(FilterFunctions.TRUE_FUNCTION, ImmutableList.of(singleColumn(VARCHAR, 0))), () -> new GenericPageProcessor(FilterFunctions.TRUE_FUNCTION, ImmutableList.of(singleColumn(VARCHAR, 0))), ImmutableList.<ColumnHandle>of(), ImmutableList.<Type>of(VARCHAR)); @@ -105,7 +105,7 @@ public class TestScanFilterAndProjectOperator return new RecordPageSource(new PageRecordSet(ImmutableList.<Type>of(VARCHAR), input)); } }, - new GenericCursorProcessor(FilterFunctions.TRUE_FUNCTION, ImmutableList.of(singleColumn(VARCHAR, 0))), + () -> new GenericCursorProcessor(FilterFunctions.TRUE_FUNCTION, ImmutableList.of(singleColumn(VARCHAR, 0))), () -> new GenericPageProcessor(FilterFunctions.TRUE_FUNCTION, ImmutableList.of(singleColumn(VARCHAR, 0))), ImmutableList.<ColumnHandle>of(), ImmutableList.<Type>of(VARCHAR)); diff --git a/presto-main/src/test/java/com/facebook/presto/operator/scalar/FunctionAssertions.java b/presto-main/src/test/java/com/facebook/presto/operator/scalar/FunctionAssertions.java index 0c394c94df..b478b32aa8 100644 --- a/presto-main/src/test/java/com/facebook/presto/operator/scalar/FunctionAssertions.java +++ b/presto-main/src/test/java/com/facebook/presto/operator/scalar/FunctionAssertions.java @@ -608,7 +608,7 @@ public final class FunctionAssertions SQL_PARSER, INPUT_TYPES, ImmutableList.of(filter, projection)); try { - CursorProcessor cursorProcessor = compiler.compileCursorProcessor( + Supplier<CursorProcessor> cursorProcessor = compiler.compileCursorProcessor( toRowExpression(filter, expressionTypes), ImmutableList.of(toRowExpression(projection, expressionTypes)), SOURCE_ID);
['presto-main/src/main/java/com/facebook/presto/sql/gen/ExpressionCompiler.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/LocalExecutionPlanner.java', 'presto-main/src/main/java/com/facebook/presto/operator/ScanFilterAndProjectOperator.java', 'presto-main/src/test/java/com/facebook/presto/operator/scalar/FunctionAssertions.java', 'presto-hive/src/test/java/com/facebook/presto/hive/TestOrcPageSourceMemoryTracking.java', 'presto-main/src/test/java/com/facebook/presto/operator/TestScanFilterAndProjectOperator.java']
{'.java': 6}
6
6
0
0
6
11,140,520
2,206,574
311,557
2,258
1,706
270
28
3
4,915
201
1,141
73
0
4
1970-01-01T00:24:21
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
202
prestodb/presto/5308/5267
prestodb
presto
https://github.com/prestodb/presto/issues/5267
https://github.com/prestodb/presto/pull/5308
https://github.com/prestodb/presto/pull/5308
1
fixes
Presto doesn't correctly deal with complex aggregations when arguments are also group by columns
Hi, I might found a bug related to ROLLUP function. Could you look into this issue? ### Problem ROLLUP function return 0 as total count if `COUNT(column)` is used. If `COUNT(*)` is used, Presto returns a correct result. #### PostgreSQL 9.5.2 ``` $ psql psql (9.5.2) Type "help" for help. postgres=# WITH test_data AS (SELECT * FROM ( postgres(# VALUES postgres(# ('a', 1), postgres(# ('b', 2), postgres(# ('a', 3) postgres(# ) as t(id, cnt) postgres(# ) postgres-# SELECT id, COUNT(*) as s_cnt postgres-# FROM test_data postgres-# GROUP BY ROLLUP(id) postgres-# ; id | s_cnt ----+------- a | 2 b | 1 | 3 (3 rows) ``` ``` postgres=# WITH test_data AS (SELECT * FROM ( postgres(# VALUES postgres(# ('a', 1), postgres(# ('b', 2), postgres(# ('a', 3) postgres(# ) as t(id, cnt) postgres(# ) postgres-# SELECT id, COUNT(id) as s_cnt postgres-# FROM test_data postgres-# GROUP BY ROLLUP(id); id | s_cnt ----+------- a | 2 b | 1 | 3 (3 rows) ``` ### Presto 0.146 ``` > WITH test_data AS (SELECT * FROM ( > VALUES > ('a', 1), > ('b', 2), > ('a', 3) > ) as t(id, cnt) > ) > SELECT id, COUNT(*) as s_cnt > FROM test_data > GROUP BY ROLLUP(id); > +------+-------+ | id | s_cnt | +------+-------+ | null | 3 | | a | 2 | | b | 1 | +------+-------+ 3 rows in set ``` _The following SQL show this problem_. `null` returns `0` ``` > WITH test_data AS (SELECT * FROM ( > VALUES > ('a', 1), > ('b', 2), > ('a', 3) > ) as t(id, cnt) > ) > SELECT id, COUNT(id) as s_cnt > FROM test_data > GROUP BY ROLLUP(id); +------+-------+ | id | s_cnt | +------+-------+ | null | 0 | | a | 2 | | b | 1 | +------+-------+ 3 rows in set ```
688a8ff0128169d8e0c4b28094ab29457bd1269b
30340ae10cda4efb91ff57ff58583f78759b4b3d
https://github.com/prestodb/presto/compare/688a8ff0128169d8e0c4b28094ab29457bd1269b...30340ae10cda4efb91ff57ff58583f78759b4b3d
diff --git a/presto-main/src/main/java/com/facebook/presto/operator/GroupIdOperator.java b/presto-main/src/main/java/com/facebook/presto/operator/GroupIdOperator.java index d4266a86b1..18653de108 100644 --- a/presto-main/src/main/java/com/facebook/presto/operator/GroupIdOperator.java +++ b/presto-main/src/main/java/com/facebook/presto/operator/GroupIdOperator.java @@ -41,25 +41,27 @@ public class GroupIdOperator { private final int operatorId; private final PlanNodeId planNodeId; - private final List<Type> inputTypes; private final List<Type> outputTypes; private final List<List<Integer>> groupingSetChannels; + private final List<Integer> groupingChannels; + private final List<Integer> copyChannels; private boolean closed; public GroupIdOperatorFactory( int operatorId, PlanNodeId planNodeId, - List<? extends Type> inputTypes, - List<List<Integer>> groupingSetChannels) + List<? extends Type> outputTypes, + List<List<Integer>> groupingSetChannels, + List<Integer> groupingChannels, + List<Integer> copyChannels) { this.operatorId = operatorId; this.planNodeId = requireNonNull(planNodeId, "planNodeId is null"); + this.outputTypes = ImmutableList.copyOf(requireNonNull(outputTypes)); this.groupingSetChannels = ImmutableList.copyOf(requireNonNull(groupingSetChannels)); - this.inputTypes = ImmutableList.copyOf(requireNonNull(inputTypes)); - - // add the groupId channel to the output types - this.outputTypes = ImmutableList.<Type>builder().addAll(inputTypes).add(BIGINT).build(); + this.groupingChannels = ImmutableList.copyOf(requireNonNull(groupingChannels)); + this.copyChannels = ImmutableList.copyOf(requireNonNull(copyChannels)); } @Override @@ -78,10 +80,11 @@ public class GroupIdOperator .flatMap(Collection::stream) .collect(toImmutableSet()); + // create an array of bitset for fast lookup of which columns are part of a given grouping set // will have a 'true' for every channel that should be set to null for each grouping set BitSet[] groupingSetNullChannels = new BitSet[groupingSetChannels.size()]; for (int i = 0; i < groupingSetChannels.size(); i++) { - groupingSetNullChannels[i] = new BitSet(inputTypes.size()); + groupingSetNullChannels[i] = new BitSet(groupingChannels.size() + copyChannels.size()); // first set all grouping columns to true for (int groupingColumn : allGroupingColumns) { groupingSetNullChannels[i].set(groupingColumn, true); @@ -92,13 +95,15 @@ public class GroupIdOperator } } - Block[] nullBlocks = new Block[inputTypes.size()]; - for (int i = 0; i < nullBlocks.length; i++) { - nullBlocks[i] = inputTypes.get(i).createBlockBuilder(new BlockBuilderStatus(), 1) + // create null blocks for every grouping channel + Block[] nullBlocks = new Block[groupingChannels.size()]; + for (int i = 0; i < groupingChannels.size(); i++) { + nullBlocks[i] = outputTypes.get(i).createBlockBuilder(new BlockBuilderStatus(), 1) .appendNull() .build(); } + // create groupid blocks for every group Block[] groupIdBlocks = new Block[groupingSetNullChannels.length]; for (int i = 0; i < groupingSetNullChannels.length; i++) { BlockBuilder builder = BIGINT.createBlockBuilder(new BlockBuilderStatus(), 1); @@ -106,7 +111,13 @@ public class GroupIdOperator groupIdBlocks[i] = builder.build(); } - return new GroupIdOperator(operatorContext, outputTypes, groupingSetNullChannels, nullBlocks, groupIdBlocks); + // create array of input channels for every grouping channel + int[] groupInputs = groupingChannels.stream().mapToInt(Integer::intValue).toArray(); + + // create array of input channels for every copy channel + int[] copyInputs = copyChannels.stream().mapToInt(Integer::intValue).toArray(); + + return new GroupIdOperator(operatorContext, outputTypes, groupingSetNullChannels, nullBlocks, groupIdBlocks, groupInputs, copyInputs); } @Override @@ -118,7 +129,7 @@ public class GroupIdOperator @Override public OperatorFactory duplicate() { - return new GroupIdOperatorFactory(operatorId, planNodeId, inputTypes, groupingSetChannels); + return new GroupIdOperatorFactory(operatorId, planNodeId, outputTypes, groupingSetChannels, groupingChannels, copyChannels); } } @@ -127,6 +138,8 @@ public class GroupIdOperator private final BitSet[] groupingSetNullChannels; private final Block[] nullBlocks; private final Block[] groupIdBlocks; + private final int[] groupInputs; + private final int[] copyInputs; private Page currentPage = null; private int currentGroupingSet = 0; @@ -137,15 +150,18 @@ public class GroupIdOperator List<Type> types, BitSet[] groupingSetNullChannels, Block[] nullBlocks, - Block[] groupIdBlocks) + Block[] groupIdBlocks, + int[] groupInputs, + int[] copyInputs) { this.operatorContext = requireNonNull(operatorContext, "operatorContext is null"); - this.types = requireNonNull(types, "inputTypes is null"); + this.types = requireNonNull(types, "types is null"); this.groupingSetNullChannels = requireNonNull(groupingSetNullChannels, "groupingSetNullChannels is null"); this.nullBlocks = requireNonNull(nullBlocks); - checkArgument(nullBlocks.length == (types.size() - 1), "length of nullBlocks must be one plus length of types"); this.groupIdBlocks = requireNonNull(groupIdBlocks); checkArgument(groupIdBlocks.length == groupingSetNullChannels.length, "groupIdBlocks and groupingSetNullChannels must have the same length"); + this.groupInputs = requireNonNull(groupInputs); + this.copyInputs = requireNonNull(copyInputs); } @Override @@ -200,17 +216,21 @@ public class GroupIdOperator private Page generateNextPage() { // generate 'n' pages for every input page, where n is the number of grouping sets - Block[] outputBlocks = new Block[currentPage.getChannelCount() + 1]; + Block[] outputBlocks = new Block[types.size()]; - for (int channel = 0; channel < currentPage.getChannelCount(); channel++) { - if (groupingSetNullChannels[currentGroupingSet].get(channel)) { - outputBlocks[channel] = new RunLengthEncodedBlock(nullBlocks[channel], currentPage.getPositionCount()); + for (int i = 0; i < groupInputs.length; i++) { + if (groupingSetNullChannels[currentGroupingSet].get(groupInputs[i])) { + outputBlocks[i] = new RunLengthEncodedBlock(nullBlocks[i], currentPage.getPositionCount()); } else { - outputBlocks[channel] = currentPage.getBlock(channel); + outputBlocks[i] = currentPage.getBlock(groupInputs[i]); } } + for (int i = 0; i < copyInputs.length; i++) { + outputBlocks[groupInputs.length + i] = currentPage.getBlock(copyInputs[i]); + } + outputBlocks[outputBlocks.length - 1] = new RunLengthEncodedBlock(groupIdBlocks[currentGroupingSet], currentPage.getPositionCount()); currentGroupingSet = (currentGroupingSet + 1) % groupingSetNullChannels.length; Page outputPage = new Page(currentPage.getPositionCount(), outputBlocks); diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/LocalExecutionPlanner.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/LocalExecutionPlanner.java index 7689c44064..4b29a1e346 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/LocalExecutionPlanner.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/LocalExecutionPlanner.java @@ -818,24 +818,42 @@ public class LocalExecutionPlanner public PhysicalOperation visitGroupId(GroupIdNode node, LocalExecutionPlanContext context) { PhysicalOperation source = node.getSource().accept(this, context); + ImmutableMap.Builder<Symbol, Integer> newLayout = ImmutableMap.builder(); + ImmutableList.Builder<Type> outputTypes = ImmutableList.builder(); - // add groupId to the layout - int groupIdChannel = source.getLayout().values().stream() - .mapToInt(Integer::intValue) - .max() - .orElse(-1) + 1; + int outputChannel = 0; - Map<Symbol, Integer> newLayout = ImmutableMap.<Symbol, Integer>builder() - .putAll(source.getLayout()) - .put(node.getGroupIdSymbol(), groupIdChannel) - .build(); + ImmutableList.Builder<Integer> groupingChannels = ImmutableList.builder(); + for (Symbol inputSymbol : node.getDistinctGroupingColumns()) { + int inputChannel = source.getLayout().get(inputSymbol); + newLayout.put(inputSymbol, outputChannel++); + outputTypes.add(source.getTypes().get(inputChannel)); + groupingChannels.add(inputChannel); + } + + ImmutableList.Builder<Integer> copyChannels = ImmutableList.builder(); + for (Symbol inputSymbol : node.getIdentityMappings().keySet()) { + int inputChannel = source.getLayout().get(inputSymbol); + newLayout.put(node.getIdentityMappings().get(inputSymbol), outputChannel++); + outputTypes.add(source.getTypes().get(inputChannel)); + copyChannels.add(inputChannel); + } + + newLayout.put(node.getGroupIdSymbol(), outputChannel); + outputTypes.add(BIGINT); List<List<Integer>> groupingSetChannels = node.getGroupingSets().stream() .map(groupingSet -> getChannelsForSymbols(groupingSet, source.getLayout())) .collect(toImmutableList()); - OperatorFactory groupIdOperatorFactory = new GroupIdOperator.GroupIdOperatorFactory(context.getNextOperatorId(), node.getId(), source.getTypes(), groupingSetChannels); - return new PhysicalOperation(groupIdOperatorFactory, newLayout, source); + OperatorFactory groupIdOperatorFactory = new GroupIdOperator.GroupIdOperatorFactory(context.getNextOperatorId(), + node.getId(), + outputTypes.build(), + groupingSetChannels, + groupingChannels.build(), + copyChannels.build()); + + return new PhysicalOperation(groupIdOperatorFactory, newLayout.build(), source); } @Override diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/QueryPlanner.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/QueryPlanner.java index c6e0f073e4..02264cd077 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/QueryPlanner.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/QueryPlanner.java @@ -60,6 +60,7 @@ import com.google.common.collect.Iterables; import java.util.Collection; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; @@ -369,29 +370,9 @@ class QueryPlanner } // 2. Aggregate - ImmutableMap.Builder<Symbol, FunctionCall> aggregationAssignments = ImmutableMap.builder(); - ImmutableMap.Builder<Symbol, Signature> functions = ImmutableMap.builder(); - // 2.a. Rewrite aggregates in terms of pre-projected inputs + // 2.a. Rewrite group by expressions in terms of pre-projected inputs TranslationMap translations = new TranslationMap(subPlan.getRelationPlan(), analysis); - boolean needPostProjectionCoercion = false; - for (FunctionCall aggregate : analysis.getAggregates(node)) { - Expression rewritten = subPlan.rewrite(aggregate); - Symbol newSymbol = symbolAllocator.newSymbol(rewritten, analysis.getType(aggregate)); - - // TODO: this is a hack, because we apply coercions to the output of expressions, rather than the arguments to expressions. - // Therefore we can end up with this implicit cast, and have to move it into a post-projection - if (rewritten instanceof Cast) { - rewritten = ((Cast) rewritten).getExpression(); - needPostProjectionCoercion = true; - } - aggregationAssignments.put(newSymbol, (FunctionCall) rewritten); - translations.put(aggregate, newSymbol); - - functions.put(newSymbol, analysis.getFunctionSignature(aggregate)); - } - - // 2.b. Rewrite group by expressions in terms of pre-projected inputs ImmutableList.Builder<List<Symbol>> groupingSetsSymbolsBuilder = ImmutableList.builder(); ImmutableSet.Builder<Symbol> distinctGroupingSymbolsBuilder = ImmutableSet.builder(); for (List<Expression> groupingSet : groupingSets) { @@ -405,15 +386,49 @@ class QueryPlanner groupingSetsSymbolsBuilder.add(groupingColumns.build()); } + // 2.b. Add a groupIdNode and groupIdSymbol if there are multiple grouping sets List<List<Symbol>> groupingSetsSymbols = groupingSetsSymbolsBuilder.build(); - // 2.c. Add a groupIdNode and groupIdSymbol if there are multiple grouping sets if (groupingSets.size() > 1) { + Set<Symbol> groupIdInputs = new HashSet<>(); + distinctGroupingColumns.stream() + .map(subPlan::translate) + .forEach(groupIdInputs::add); + + ImmutableMap.Builder<Symbol, Symbol> identityMapping = ImmutableMap.builder(); + for (Expression argument : arguments) { + Symbol output = symbolAllocator.newSymbol(argument, analysis.getTypeWithCoercions(argument), "id"); + identityMapping.put(subPlan.translate(argument), output); + groupIdInputs.add(subPlan.translate(argument)); + + // relies on the fact that group by expressions have already been re-written, and will not be affected by this mapping change + subPlan.getTranslations().put(argument, output); + } + Symbol groupIdSymbol = symbolAllocator.newSymbol("groupId", BIGINT); - GroupIdNode groupId = new GroupIdNode(idAllocator.getNextId(), subPlan.getRoot(), subPlan.getRoot().getOutputSymbols(), groupingSetsSymbols, groupIdSymbol); + GroupIdNode groupId = new GroupIdNode(idAllocator.getNextId(), subPlan.getRoot(), groupingSetsSymbols, identityMapping.build(), groupIdSymbol); subPlan = subPlan.withNewRoot(groupId); distinctGroupingSymbolsBuilder.add(groupIdSymbol); } - List<Symbol> distinctGroupingSymbols = distinctGroupingSymbolsBuilder.build().asList(); + + // 2.c. Rewrite aggregates in terms of pre-projected inputs + ImmutableMap.Builder<Symbol, FunctionCall> aggregationAssignments = ImmutableMap.builder(); + ImmutableMap.Builder<Symbol, Signature> functions = ImmutableMap.builder(); + boolean needPostProjectionCoercion = false; + for (FunctionCall aggregate : analysis.getAggregates(node)) { + Expression rewritten = subPlan.rewrite(aggregate); + Symbol newSymbol = symbolAllocator.newSymbol(rewritten, analysis.getType(aggregate)); + + // TODO: this is a hack, because we apply coercions to the output of expressions, rather than the arguments to expressions. + // Therefore we can end up with this implicit cast, and have to move it into a post-projection + if (rewritten instanceof Cast) { + rewritten = ((Cast) rewritten).getExpression(); + needPostProjectionCoercion = true; + } + aggregationAssignments.put(newSymbol, (FunctionCall) rewritten); + translations.put(aggregate, newSymbol); + + functions.put(newSymbol, analysis.getFunctionSignature(aggregate)); + } // 2.d. Mark distinct rows for each aggregate that has DISTINCT // Map from aggregate function arguments to marker symbols, so that we can reuse the markers, if two aggregates have the same argument @@ -437,6 +452,7 @@ class QueryPlanner masks.put(aggregateSymbol, marker); } + List<Symbol> distinctGroupingSymbols = distinctGroupingSymbolsBuilder.build().asList(); for (Map.Entry<Set<Expression>, Symbol> entry : argumentMarkers.entrySet()) { ImmutableList.Builder<Symbol> builder = ImmutableList.builder(); builder.addAll(distinctGroupingSymbols); diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/SymbolExtractor.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/SymbolExtractor.java index d93456e715..367d4deb5c 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/SymbolExtractor.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/SymbolExtractor.java @@ -113,6 +113,7 @@ public final class SymbolExtractor node.getSource().accept(this, context); builder.add(node.getGroupIdSymbol()); + builder.addAll(node.getIdentityMappings().values()); return null; } diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PruneUnreferencedOutputs.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PruneUnreferencedOutputs.java index f1fb28c362..dcf584f27e 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PruneUnreferencedOutputs.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PruneUnreferencedOutputs.java @@ -405,12 +405,21 @@ public class PruneUnreferencedOutputs { checkState(node.getDistinctGroupingColumns().stream().allMatch(column -> context.get().contains(column))); - PlanNode source = context.rewrite(node.getSource(), ImmutableSet.copyOf(context.get())); - List<Symbol> requiredSymbols = context.get().stream() - .filter(symbol -> !symbol.equals(node.getGroupIdSymbol())) - .collect(toImmutableList()); + ImmutableMap.Builder<Symbol, Symbol> identityMappingBuilder = ImmutableMap.builder(); + for (Map.Entry<Symbol, Symbol> entry : node.getIdentityMappings().entrySet()) { + if (context.get().contains(entry.getValue())) { + identityMappingBuilder.put(entry); + } + } + + Map<Symbol, Symbol> identityMapping = identityMappingBuilder.build(); + + PlanNode source = context.rewrite(node.getSource(), ImmutableSet.<Symbol>builder() + .addAll(identityMapping.keySet()) + .addAll(node.getDistinctGroupingColumns()) + .build()); - return new GroupIdNode(node.getId(), source, requiredSymbols, node.getGroupingSets(), node.getGroupIdSymbol()); + return new GroupIdNode(node.getId(), source, node.getGroupingSets(), identityMapping, node.getGroupIdSymbol()); } @Override diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/UnaliasSymbolReferences.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/UnaliasSymbolReferences.java index b61ef06f94..bde6ac893d 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/UnaliasSymbolReferences.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/UnaliasSymbolReferences.java @@ -162,7 +162,12 @@ public class UnaliasSymbolReferences .map(this::canonicalize) .collect(Collectors.toList()); - return new GroupIdNode(node.getId(), source, canonicalize(node.getInputSymbols()), groupingSetsSymbols, canonicalize(node.getGroupIdSymbol())); + ImmutableMap.Builder<Symbol, Symbol> newPassthroughMap = ImmutableMap.builder(); + for (Symbol inputSymbol : node.getIdentityMappings().keySet()) { + newPassthroughMap.put(canonicalize(inputSymbol), canonicalize(node.getIdentityMappings().get(inputSymbol))); + } + + return new GroupIdNode(node.getId(), source, groupingSetsSymbols, newPassthroughMap.build(), canonicalize(node.getGroupIdSymbol())); } @Override diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/plan/ChildReplacer.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/plan/ChildReplacer.java index 40c98bebf0..960396df1b 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/plan/ChildReplacer.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/plan/ChildReplacer.java @@ -174,7 +174,7 @@ public class ChildReplacer @Override public PlanNode visitGroupId(GroupIdNode node, List<PlanNode> newChildren) { - return new GroupIdNode(node.getId(), Iterables.getOnlyElement(newChildren), node.getInputSymbols(), node.getGroupingSets(), node.getGroupIdSymbol()); + return new GroupIdNode(node.getId(), Iterables.getOnlyElement(newChildren), node.getGroupingSets(), node.getIdentityMappings(), node.getGroupIdSymbol()); } @Override diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/plan/GroupIdNode.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/plan/GroupIdNode.java index 2b3c7b7616..daf3560ced 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/plan/GroupIdNode.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/plan/GroupIdNode.java @@ -17,12 +17,15 @@ import com.facebook.presto.sql.planner.Symbol; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; import javax.annotation.concurrent.Immutable; import java.util.Collection; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Set; import static java.util.Objects.requireNonNull; @@ -33,21 +36,21 @@ public class GroupIdNode extends PlanNode { private final PlanNode source; - private final List<Symbol> inputSymbols; private final List<List<Symbol>> groupingSets; + private final Map<Symbol, Symbol> identityMappings; private final Symbol groupIdSymbol; @JsonCreator public GroupIdNode(@JsonProperty("id") PlanNodeId id, @JsonProperty("source") PlanNode source, - @JsonProperty("inputSymbols") List<Symbol> inputSymbols, @JsonProperty("groupingSets") List<List<Symbol>> groupingSets, + @JsonProperty("identityMappings") Map<Symbol, Symbol> identityMappings, @JsonProperty("groupIdSymbol") Symbol groupIdSymbol) { super(id); this.source = requireNonNull(source); - this.inputSymbols = ImmutableList.copyOf(requireNonNull(inputSymbols)); this.groupingSets = ImmutableList.copyOf(requireNonNull(groupingSets)); + this.identityMappings = ImmutableMap.copyOf(requireNonNull(identityMappings)); this.groupIdSymbol = requireNonNull(groupIdSymbol); } @@ -55,7 +58,8 @@ public class GroupIdNode public List<Symbol> getOutputSymbols() { return ImmutableList.<Symbol>builder() - .addAll(source.getOutputSymbols()) + .addAll(getDistinctGroupingColumns()) + .addAll(identityMappings.values()) .add(groupIdSymbol) .build(); } @@ -72,10 +76,12 @@ public class GroupIdNode return source; } - @JsonProperty - public List<Symbol> getInputSymbols() + public Set<Symbol> getInputSymbols() { - return inputSymbols; + return ImmutableSet.<Symbol>builder() + .addAll(identityMappings.keySet()) + .addAll(getDistinctGroupingColumns()) + .build(); } @JsonProperty @@ -84,6 +90,12 @@ public class GroupIdNode return groupingSets; } + @JsonProperty + public Map<Symbol, Symbol> getIdentityMappings() + { + return identityMappings; + } + public List<Symbol> getDistinctGroupingColumns() { return groupingSets.stream() diff --git a/presto-main/src/test/java/com/facebook/presto/operator/TestGroupIdOperator.java b/presto-main/src/test/java/com/facebook/presto/operator/TestGroupIdOperator.java index 125bb02472..738a825da6 100644 --- a/presto-main/src/test/java/com/facebook/presto/operator/TestGroupIdOperator.java +++ b/presto-main/src/test/java/com/facebook/presto/operator/TestGroupIdOperator.java @@ -71,23 +71,28 @@ public class TestGroupIdOperator .build(); GroupIdOperatorFactory operatorFactory = - new GroupIdOperatorFactory(0, new PlanNodeId("test"), ImmutableList.of(BIGINT, VARCHAR, BOOLEAN, BIGINT), ImmutableList.of(ImmutableList.of(1, 2), ImmutableList.of(3))); + new GroupIdOperatorFactory(0, + new PlanNodeId("test"), + ImmutableList.of(VARCHAR, BOOLEAN, BIGINT, BIGINT, BIGINT), + ImmutableList.of(ImmutableList.of(1, 2), ImmutableList.of(3)), + ImmutableList.of(1, 2, 3), + ImmutableList.of(0)); Operator operator = operatorFactory.createOperator(driverContext); - MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, VARCHAR, BOOLEAN, BIGINT, BIGINT) - .row(100L, "400", true, null, 0L) - .row(101L, "401", false, null, 0L) - .row(102L, "402", true, null, 0L) - .row(200L, "500", true, null, 0L) - .row(201L, "501", false, null, 0L) - .row(202L, "502", true, null, 0L) - .row(100L, null, null, 1000L, 1L) - .row(101L, null, null, 1001L, 1L) - .row(102L, null, null, 1002L, 1L) - .row(200L, null, null, 1100L, 1L) - .row(201L, null, null, 1101L, 1L) - .row(202L, null, null, 1102L, 1L) + MaterializedResult expected = resultBuilder(driverContext.getSession(), VARCHAR, BOOLEAN, BIGINT, BIGINT, BIGINT) + .row("400", true, null, 100L, 0L) + .row("401", false, null, 101L, 0L) + .row("402", true, null, 102L, 0L) + .row("500", true, null, 200L, 0L) + .row("501", false, null, 201L, 0L) + .row("502", true, null, 202L, 0L) + .row(null, null, 1000L, 100L, 1L) + .row(null, null, 1001L, 101L, 1L) + .row(null, null, 1002L, 102L, 1L) + .row(null, null, 1100L, 200L, 1L) + .row(null, null, 1101L, 201L, 1L) + .row(null, null, 1102L, 202L, 1L) .build(); List<Page> pages = toPages(operator, input.iterator()); diff --git a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java index 1d43de6a41..bbad900d5d 100644 --- a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java +++ b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java @@ -1420,6 +1420,33 @@ public abstract class AbstractTestQueries "SELECT orderpriority, -1 FROM orders GROUP BY orderpriority"); } + @Test + public void testGroupingSetsAggregateOnGroupedColumn() + throws Exception + { + assertQuery("SELECT orderpriority, COUNT(orderpriority) FROM orders GROUP BY ROLLUP (orderpriority)", + "SELECT orderpriority, COUNT(orderpriority) FROM orders GROUP BY orderpriority UNION " + + "SELECT NULL, COUNT(orderpriority) FROM orders"); + } + + @Test + public void testGroupingSetsMultipleAggregatesOnGroupedColumn() + throws Exception + { + assertQuery("SELECT linenumber, suppkey, SUM(suppkey), COUNT(linenumber), SUM(CAST(quantity AS BIGINT)) FROM lineitem GROUP BY GROUPING SETS ((linenumber, suppkey), ())", + "SELECT linenumber, suppkey, SUM(suppkey), COUNT(linenumber), SUM(CAST(quantity AS BIGINT)) FROM lineitem GROUP BY linenumber, suppkey UNION " + + "SELECT NULL, NULL, SUM(suppkey), COUNT(linenumber), SUM(CAST(quantity AS BIGINT)) FROM lineitem"); + } + + @Test + public void testGroupingSetsMultipleAggregatesWithGroupedColumns() + throws Exception + { + assertQuery("SELECT linenumber, suppkey, COUNT(linenumber), SUM(CAST(quantity AS BIGINT)) FROM lineitem GROUP BY GROUPING SETS ((linenumber, suppkey), ())", + "SELECT linenumber, suppkey, COUNT(linenumber), SUM(CAST(quantity AS BIGINT)) FROM lineitem GROUP BY linenumber, suppkey UNION " + + "SELECT NULL, NULL, COUNT(linenumber), SUM(CAST(quantity AS BIGINT)) FROM lineitem"); + } + @Test public void testRollup() throws Exception
['presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/plan/ChildReplacer.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/LocalExecutionPlanner.java', 'presto-main/src/test/java/com/facebook/presto/operator/TestGroupIdOperator.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/QueryPlanner.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/SymbolExtractor.java', 'presto-main/src/main/java/com/facebook/presto/operator/GroupIdOperator.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PruneUnreferencedOutputs.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/plan/GroupIdNode.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/UnaliasSymbolReferences.java']
{'.java': 10}
10
10
0
0
10
11,649,862
2,309,070
325,360
2,376
14,079
2,591
221
8
1,699
310
585
101
0
4
1970-01-01T00:24:23
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
201
prestodb/presto/5334/5332
prestodb
presto
https://github.com/prestodb/presto/issues/5332
https://github.com/prestodb/presto/pull/5334
https://github.com/prestodb/presto/pull/5334
1
fix
Cannot chain `AT TIME ZONE`
Chaining `AT TIME ZONE` together results in the error `null`: ``` presto> SELECT TIMESTAMP '2012-10-31 01:00' AT TIME ZONE 'America/Los_Angeles' AT TIME ZONE 'UTC'; Query 20160520_185347_00028_kmihc failed: null presto> ``` Can work around this with e.g.: ``` presto> WITH tz_la AS (SELECT TIMESTAMP '2012-10-31 01:00' AT TIME ZONE 'America/Los_Angeles' AS ts) -> SELECT tz_la.ts, tz_la.ts AT TIME ZONE 'UTC' from tz_la; ts | _col1 ---------------------------------------------+----------------------------- 2012-10-31 01:00:00.000 America/Los_Angeles | 2012-10-31 08:00:00.000 UTC (1 row) Query 20160520_185900_00029_kmihc, FINISHED, 1 node Splits: 1 total, 0 done (0.00%) 0:00 [0 rows, 0B] [0 rows/s, 0B/s] presto> ``` This is on Presto 0.146. I believe this worked before but I could be mistaken and I haven't had time to bisect. I'll follow up if I find more info there.
b3f323cbce5419826e1bd7fb4b553e9812bedce1
3a235edb8202374bad34bfa0d914e019aa5d0643
https://github.com/prestodb/presto/compare/b3f323cbce5419826e1bd7fb4b553e9812bedce1...3a235edb8202374bad34bfa0d914e019aa5d0643
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/DesugaringRewriter.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/DesugaringRewriter.java index 593924b40a..ae1236a4a0 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/DesugaringRewriter.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/DesugaringRewriter.java @@ -45,7 +45,7 @@ public class DesugaringRewriter public Expression rewriteAtTimeZone(AtTimeZone node, Void context, ExpressionTreeRewriter<Void> treeRewriter) { Expression value = treeRewriter.rewrite(node.getValue(), context); - Type type = expressionTypes.get(value); + Type type = expressionTypes.get(node.getValue()); if (type.equals(TIME)) { value = new Cast(value, TIME_WITH_TIME_ZONE.getDisplayName()); } diff --git a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java index 046ae76db1..95174a774e 100644 --- a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java +++ b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java @@ -4401,6 +4401,13 @@ public abstract class AbstractTestQueries "values TIMESTAMP '1969-12-31 16:01:00-08:00', TIMESTAMP '1970-01-01 00:01:00-08:00', TIMESTAMP '1969-12-31 08:01:00-08:00'"); assertQuery("SELECT min(x) AT TIME ZONE 'America/Los_Angeles' FROM (values TIMESTAMP '1970-01-01 00:01:00+00:00', TIMESTAMP '1970-01-01 08:01:00+08:00', TIMESTAMP '1969-12-31 16:01:00-08:00') t(x)", "values TIMESTAMP '1969-12-31 16:01:00-08:00'"); + + // with chained AT TIME ZONE + assertQuery("SELECT TIMESTAMP '2012-10-31 01:00' AT TIME ZONE 'America/Los_Angeles' AT TIME ZONE 'UTC'", "SELECT TIMESTAMP '2012-10-30 18:00:00.000 America/Los_Angeles'"); + assertQuery("SELECT TIMESTAMP '2012-10-31 01:00' AT TIME ZONE 'Asia/Tokyo' AT TIME ZONE 'America/Los_Angeles'", "SELECT TIMESTAMP '2012-10-30 18:00:00.000 America/Los_Angeles'"); + assertQuery("SELECT TIMESTAMP '2012-10-31 01:00' AT TIME ZONE 'America/Los_Angeles' AT TIME ZONE 'Asia/Shanghai'", "SELECT TIMESTAMP '2012-10-30 18:00:00.000 America/Los_Angeles'"); + assertQuery("SELECT min(x) AT TIME ZONE 'America/Los_Angeles' AT TIME ZONE 'UTC' FROM (values TIMESTAMP '1970-01-01 00:01:00+00:00', TIMESTAMP '1970-01-01 08:01:00+08:00', TIMESTAMP '1969-12-31 16:01:00-08:00') t(x)", + "values TIMESTAMP '1969-12-31 16:01:00-08:00'"); } @Test
['presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/DesugaringRewriter.java']
{'.java': 2}
2
2
0
0
2
11,697,709
2,319,510
326,718
2,379
107
19
2
1
944
125
310
28
0
2
1970-01-01T00:24:23
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
200
prestodb/presto/5430/5429
prestodb
presto
https://github.com/prestodb/presto/issues/5429
https://github.com/prestodb/presto/pull/5430
https://github.com/prestodb/presto/pull/5430
1
fixes
round(nan(), 2) returns 0.0
`SELECT round(nan(), 2)` results in `0.0`, but should be `NaN`. This is a regression since 0.144.5.
2c3751dfbf7bc3af05bbd47970989580ad3742d5
ea771947c017fefa785e0e017fb533adaae83a2f
https://github.com/prestodb/presto/compare/2c3751dfbf7bc3af05bbd47970989580ad3742d5...ea771947c017fefa785e0e017fb533adaae83a2f
diff --git a/presto-main/src/main/java/com/facebook/presto/operator/scalar/MathFunctions.java b/presto-main/src/main/java/com/facebook/presto/operator/scalar/MathFunctions.java index c7a1031919..de0796209f 100644 --- a/presto-main/src/main/java/com/facebook/presto/operator/scalar/MathFunctions.java +++ b/presto-main/src/main/java/com/facebook/presto/operator/scalar/MathFunctions.java @@ -465,6 +465,10 @@ public final class MathFunctions @SqlType(StandardTypes.DOUBLE) public static double round(@SqlType(StandardTypes.DOUBLE) double num, @SqlType(StandardTypes.BIGINT) long decimals) { + if (Double.isNaN(num)) { + return num; + } + double factor = Math.pow(10, decimals); return Math.round(num * factor) / factor; } diff --git a/presto-main/src/test/java/com/facebook/presto/operator/scalar/TestMathFunctions.java b/presto-main/src/test/java/com/facebook/presto/operator/scalar/TestMathFunctions.java index 4a937b84e4..8b05ad68ac 100644 --- a/presto-main/src/test/java/com/facebook/presto/operator/scalar/TestMathFunctions.java +++ b/presto-main/src/test/java/com/facebook/presto/operator/scalar/TestMathFunctions.java @@ -485,6 +485,8 @@ public class TestMathFunctions assertFunction("round(CAST(NULL as DOUBLE), CAST(NULL as BIGINT))", DOUBLE, null); assertFunction("round(-3.0, CAST(NULL as BIGINT))", DOUBLE, null); assertFunction("round(CAST(NULL as DOUBLE), 1)", DOUBLE, null); + + assertFunction("round(nan(), 2)", DOUBLE, Double.NaN); } @Test
['presto-main/src/main/java/com/facebook/presto/operator/scalar/MathFunctions.java', 'presto-main/src/test/java/com/facebook/presto/operator/scalar/TestMathFunctions.java']
{'.java': 2}
2
2
0
0
2
11,778,463
2,336,385
328,764
2,386
71
15
4
1
100
16
34
2
0
0
1970-01-01T00:24:25
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
199
prestodb/presto/5457/5449
prestodb
presto
https://github.com/prestodb/presto/issues/5449
https://github.com/prestodb/presto/pull/5457
https://github.com/prestodb/presto/pull/5457
1
fix
array_agg should not ignore nulls
``` presto> select array_agg(x) from (values 1,2,3,null) t(x); _col0 ----------- [1, 2, 3] ``` The expected result is `[1, 2, 3, null]`. From the spec: > ii) Otherwise, the result of `<array aggregate function>` is an array of N elements such that for all i, 1 (one) ≤ i ≤ N, the value of the i-th element is the value of the first column of Ri. > > NOTE 331 — **Null values are not eliminated when computing `<array aggregate function>`**. This, plus the optional `<sort specification list>`, sets `<array aggregate function>` apart from `<general set function>`s.
b381dadddae2d54ea321b767bf2c1b9c4b23c7d1
29be269d77e121d03600ce99502f2c89055400a7
https://github.com/prestodb/presto/compare/b381dadddae2d54ea321b767bf2c1b9c4b23c7d1...29be269d77e121d03600ce99502f2c89055400a7
diff --git a/presto-main/src/main/java/com/facebook/presto/operator/aggregation/ArrayAggregationFunction.java b/presto-main/src/main/java/com/facebook/presto/operator/aggregation/ArrayAggregationFunction.java index 93540af632..b317a917e2 100644 --- a/presto-main/src/main/java/com/facebook/presto/operator/aggregation/ArrayAggregationFunction.java +++ b/presto-main/src/main/java/com/facebook/presto/operator/aggregation/ArrayAggregationFunction.java @@ -37,7 +37,7 @@ import java.util.List; import static com.facebook.presto.metadata.Signature.typeVariable; import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.BLOCK_INDEX; -import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.BLOCK_INPUT_CHANNEL; +import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.NULLABLE_BLOCK_INPUT_CHANNEL; import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.STATE; import static com.facebook.presto.operator.aggregation.AggregationUtils.generateAggregationName; import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature; @@ -111,7 +111,7 @@ public class ArrayAggregationFunction private static List<ParameterMetadata> createInputParameterMetadata(Type value) { - return ImmutableList.of(new ParameterMetadata(STATE), new ParameterMetadata(BLOCK_INPUT_CHANNEL, value), new ParameterMetadata(BLOCK_INDEX)); + return ImmutableList.of(new ParameterMetadata(STATE), new ParameterMetadata(NULLABLE_BLOCK_INPUT_CHANNEL, value), new ParameterMetadata(BLOCK_INDEX)); } public static void input(Type type, ArrayAggregationState state, Block value, int position) diff --git a/presto-main/src/main/java/com/facebook/presto/operator/aggregation/state/ArrayAggregationStateSerializer.java b/presto-main/src/main/java/com/facebook/presto/operator/aggregation/state/ArrayAggregationStateSerializer.java index 0f7aa2f876..f22ec14ec4 100644 --- a/presto-main/src/main/java/com/facebook/presto/operator/aggregation/state/ArrayAggregationStateSerializer.java +++ b/presto-main/src/main/java/com/facebook/presto/operator/aggregation/state/ArrayAggregationStateSerializer.java @@ -56,8 +56,7 @@ public class ArrayAggregationStateSerializer int positionCount = stateBlock.getPositionCount(); BlockBuilder blockBuilder = elementType.createBlockBuilder(new BlockBuilderStatus(), positionCount); for (int i = 0; i < positionCount; i++) { - stateBlock.writePositionTo(i, blockBuilder); - blockBuilder.closeEntry(); + elementType.appendTo(stateBlock, i, blockBuilder); } state.setBlockBuilder(blockBuilder); } diff --git a/presto-main/src/test/java/com/facebook/presto/operator/aggregation/TestArrayAggregation.java b/presto-main/src/test/java/com/facebook/presto/operator/aggregation/TestArrayAggregation.java index b62d350320..e6503be30f 100644 --- a/presto-main/src/test/java/com/facebook/presto/operator/aggregation/TestArrayAggregation.java +++ b/presto-main/src/test/java/com/facebook/presto/operator/aggregation/TestArrayAggregation.java @@ -58,7 +58,7 @@ public class TestArrayAggregation assertAggregation( bigIntAgg, 1.0, - null, + Arrays.asList(null, null, null), createLongsBlock(new Long[] {null, null, null})); } @@ -71,7 +71,7 @@ public class TestArrayAggregation assertAggregation( bigIntAgg, 1.0, - Arrays.asList(2L, 3L), + Arrays.asList(null, 2L, null, 3L, null), createLongsBlock(new Long[] {null, 2L, null, 3L, null})); }
['presto-main/src/main/java/com/facebook/presto/operator/aggregation/ArrayAggregationFunction.java', 'presto-main/src/main/java/com/facebook/presto/operator/aggregation/state/ArrayAggregationStateSerializer.java', 'presto-main/src/test/java/com/facebook/presto/operator/aggregation/TestArrayAggregation.java']
{'.java': 3}
3
3
0
0
3
11,886,696
2,359,126
332,095
2,406
738
128
7
2
583
97
164
16
0
1
1970-01-01T00:24:26
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
198
prestodb/presto/5504/5498
prestodb
presto
https://github.com/prestodb/presto/issues/5498
https://github.com/prestodb/presto/pull/5504
https://github.com/prestodb/presto/pull/5504
1
fixes
GROUPING SETS over UNION fails
The following query: ``` SELECT x, COUNT(DISTINCT x) AS c FROM ( SELECT * FROM (values (1)) t(x) UNION ALL SELECT * FROM (values (1)) t(x) ) t2 GROUP BY GROUPING SETS ((x), ()) ``` fails with: ``` Query 20160622_013115_00003_u5amn failed: index (0) must be less than size (0) java.lang.IndexOutOfBoundsException: index (0) must be less than size (0) at com.google.common.base.Preconditions.checkElementIndex(Preconditions.java:310) at com.google.common.base.Preconditions.checkElementIndex(Preconditions.java:292) at com.google.common.collect.RegularImmutableList.get(RegularImmutableList.java:65) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.visitUnion(AddExchanges.java:1104) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.visitUnion(AddExchanges.java:188) at com.facebook.presto.sql.planner.plan.UnionNode.accept(UnionNode.java:139) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.planChild(AddExchanges.java:1143) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.visitPlan(AddExchanges.java:215) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.visitPlan(AddExchanges.java:188) at com.facebook.presto.sql.planner.plan.PlanVisitor.visitGroupId(PlanVisitor.java:150) at com.facebook.presto.sql.planner.plan.GroupIdNode.accept(GroupIdNode.java:125) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.planChild(AddExchanges.java:1143) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.visitAggregation(AddExchanges.java:283) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.visitAggregation(AddExchanges.java:188) at com.facebook.presto.sql.planner.plan.AggregationNode.accept(AggregationNode.java:189) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.planChild(AddExchanges.java:1143) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.visitProject(AddExchanges.java:231) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.visitProject(AddExchanges.java:188) at com.facebook.presto.sql.planner.plan.ProjectNode.accept(ProjectNode.java:76) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.planChild(AddExchanges.java:1143) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.visitAggregation(AddExchanges.java:283) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.visitAggregation(AddExchanges.java:188) at com.facebook.presto.sql.planner.plan.AggregationNode.accept(AggregationNode.java:189) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.planChild(AddExchanges.java:1143) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.visitProject(AddExchanges.java:231) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.visitProject(AddExchanges.java:188) at com.facebook.presto.sql.planner.plan.ProjectNode.accept(ProjectNode.java:76) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.planChild(AddExchanges.java:1143) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.visitOutput(AddExchanges.java:237) at com.facebook.presto.sql.planner.optimizations.AddExchanges$Rewriter.visitOutput(AddExchanges.java:188) at com.facebook.presto.sql.planner.plan.OutputNode.accept(OutputNode.java:81) at com.facebook.presto.sql.planner.optimizations.AddExchanges.optimize(AddExchanges.java:150) at com.facebook.presto.sql.planner.LogicalPlanner.plan(LogicalPlanner.java:100) at com.facebook.presto.execution.SqlQueryExecution.doAnalyzeQuery(SqlQueryExecution.java:277) at com.facebook.presto.execution.SqlQueryExecution.analyzeQuery(SqlQueryExecution.java:256) at com.facebook.presto.execution.SqlQueryExecution.start(SqlQueryExecution.java:220) at com.facebook.presto.execution.QueuedExecution.lambda$start$1(QueuedExecution.java:68) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) ```
11ee7671117eee90f3c9100bb0c95cab7dfc277b
fe434cb1468f6f71a526786869d35334c7e28bc4
https://github.com/prestodb/presto/compare/11ee7671117eee90f3c9100bb0c95cab7dfc277b...fe434cb1468f6f71a526786869d35334c7e28bc4
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/AddExchanges.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/AddExchanges.java index f9c62657d0..6f4837b207 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/AddExchanges.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/AddExchanges.java @@ -45,6 +45,7 @@ import com.facebook.presto.sql.planner.plan.EnforceSingleRowNode; import com.facebook.presto.sql.planner.plan.ExchangeNode; import com.facebook.presto.sql.planner.plan.ExplainAnalyzeNode; import com.facebook.presto.sql.planner.plan.FilterNode; +import com.facebook.presto.sql.planner.plan.GroupIdNode; import com.facebook.presto.sql.planner.plan.IndexJoinNode; import com.facebook.presto.sql.planner.plan.IndexSourceNode; import com.facebook.presto.sql.planner.plan.JoinNode; @@ -383,6 +384,31 @@ public class AddExchanges deriveProperties(source, partial.getProperties())); } + @Override + public PlanWithProperties visitGroupId(GroupIdNode node, Context context) + { + PreferredProperties childPreference = context.getPreferredProperties().translate(translateGroupIdSymbols(node)); + PlanWithProperties child = planChild(node, context.withPreferredProperties(childPreference)); + return rebaseAndDeriveProperties(node, child); + } + + private Function<Symbol, Optional<Symbol>> translateGroupIdSymbols(GroupIdNode node) + { + Map<Symbol, Symbol> invertedMappings = ImmutableBiMap.copyOf(node.getIdentityMappings()).inverse(); + List<Symbol> commonGroupingColumns = node.getCommonGroupingColumns(); + return symbol -> { + if (invertedMappings.containsKey(symbol)) { + return Optional.of(invertedMappings.get(symbol)); + } + + if (commonGroupingColumns.contains(symbol)) { + return Optional.of(symbol); + } + + return Optional.empty(); + }; + } + @Override public PlanWithProperties visitMarkDistinct(MarkDistinctNode node, Context context) { diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PropertyDerivations.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PropertyDerivations.java index b586aea570..d9c01d0f7a 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PropertyDerivations.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PropertyDerivations.java @@ -75,6 +75,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.function.Function; import static com.facebook.presto.SystemSessionProperties.planWithTableNodePartitioning; import static com.facebook.presto.spi.predicate.TupleDomain.extractFixedValues; @@ -213,7 +214,25 @@ class PropertyDerivations @Override public ActualProperties visitGroupId(GroupIdNode node, List<ActualProperties> inputProperties) { - return Iterables.getOnlyElement(inputProperties); + ActualProperties properties = Iterables.getOnlyElement(inputProperties); + + return properties.translate(translateGroupIdSymbols(node)); + } + + private Function<Symbol, Optional<Symbol>> translateGroupIdSymbols(GroupIdNode node) + { + List<Symbol> commonGroupingColumns = node.getCommonGroupingColumns(); + return symbol -> { + if (node.getIdentityMappings().containsKey(symbol)) { + return Optional.of(node.getIdentityMappings().get(symbol)); + } + + if (commonGroupingColumns.contains(symbol)) { + return Optional.of(symbol); + } + + return Optional.empty(); + }; } @Override diff --git a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java index bda81a8b9f..f8225e2e2d 100644 --- a/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java +++ b/presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java @@ -1481,6 +1481,28 @@ public abstract class AbstractTestQueries "SELECT NULL, NULL, COUNT(linenumber), SUM(CAST(quantity AS BIGINT)) FROM lineitem"); } + @Test + public void testGroupingSetsWithSingleDistinctAndUnion() + throws Exception + { + assertQuery("SELECT linenumber, COUNT(DISTINCT linenumber) FROM " + + "(SELECT * FROM lineitem WHERE linenumber%2 = 0 UNION ALL SELECT * FROM lineitem WHERE linenumber%2 = 1) " + + "GROUP BY GROUPING SETS ((linenumber), ())", + "SELECT DISTINCT linenumber, 1 FROM lineitem UNION ALL " + + "SELECT NULL, COUNT(DISTINCT linenumber) FROM lineitem"); + } + + @Test + public void testGroupingSetsWithMultipleDistinctAndUnion() + throws Exception + { + assertQuery("SELECT linenumber, COUNT(DISTINCT linenumber), SUM(DISTINCT suppkey) FROM " + + "(SELECT * FROM lineitem WHERE linenumber%2 = 0 UNION ALL SELECT * FROM lineitem WHERE linenumber%2 = 1) " + + "GROUP BY GROUPING SETS ((linenumber), ())", + "SELECT linenumber, 1, SUM(DISTINCT suppkey) FROM lineitem GROUP BY linenumber UNION ALL " + + "SELECT NULL, COUNT(DISTINCT linenumber), SUM(DISTINCT suppkey) FROM lineitem"); + } + @Test public void testRollup() throws Exception
['presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/AddExchanges.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/PropertyDerivations.java', 'presto-tests/src/main/java/com/facebook/presto/tests/AbstractTestQueries.java']
{'.java': 3}
3
3
0
0
3
11,915,792
2,364,843
332,910
2,411
2,023
333
47
2
4,341
139
1,102
62
0
2
1970-01-01T00:24:26
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
197
prestodb/presto/5517/5516
prestodb
presto
https://github.com/prestodb/presto/issues/5516
https://github.com/prestodb/presto/pull/5517
https://github.com/prestodb/presto/pull/5517
1
fixes
Division by zero error with empty interleaved block
This change 373c745b30b2db1e96eef844096b3620a11a84c7 added this bit to `InterleavedBlockEncoding.readBlock`: ``` java byte isEmpty = sliceInput.readByte(); if (isEmpty == 1) { return new InterleavedBlock(new Block[0]); } ``` InterleavedBlock performs divisions using the length of that array (columns), which result in division by zero errors: ``` java int positionInBlock = position / columns; ``` ``` java.sql.SQLException: Query failed (#20160623_104612_01302_fsieu): / by zero at com.facebook.presto.jdbc.PrestoResultSet.resultsException(PrestoResultSet.java:1799) at com.facebook.presto.jdbc.PrestoResultSet$ResultsPageIterator.computeNext(PrestoResultSet.java:1787) at com.facebook.presto.jdbc.PrestoResultSet$ResultsPageIterator.computeNext(PrestoResultSet.java:1756) at com.facebook.presto.jdbc.internal.guava.collect.AbstractIterator.tryToComputeNext(AbstractIterator.java:143) at com.facebook.presto.jdbc.internal.guava.collect.AbstractIterator.hasNext(AbstractIterator.java:138) at com.facebook.presto.jdbc.internal.guava.collect.TransformedIterator.hasNext(TransformedIterator.java:43) at com.facebook.presto.jdbc.internal.guava.collect.Iterators$5.hasNext(Iterators.java:547) at com.facebook.presto.jdbc.PrestoResultSet.next(PrestoResultSet.java:149) at com.facebook.presto.verifier.Validator.convertJdbcResultSet(Validator.java:520) at com.facebook.presto.verifier.Validator.lambda$getResultSetConverter$4(Validator.java:494) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) at java.util.concurrent.FutureTask.report(FutureTask.java:122) at java.util.concurrent.FutureTask.get(FutureTask.java:206) at com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:130) at com.facebook.presto.verifier.Validator.executeQuery(Validator.java:426) at com.facebook.presto.verifier.Validator.executeQueryTest(Validator.java:304) at com.facebook.presto.verifier.Validator.validate(Validator.java:218) at com.facebook.presto.verifier.Validator.valid(Validator.java:190) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Caused by: java.lang.ArithmeticException: / by zero at com.facebook.presto.spi.block.AbstractInterleavedBlock.getRegion(AbstractInterleavedBlock.java:260) at com.facebook.presto.spi.block.AbstractInterleavedBlock.copyRegion(AbstractInterleavedBlock.java:249) at com.facebook.presto.spi.block.AbstractArrayBlock.getSingleValueBlock(AbstractArrayBlock.java:234) at com.facebook.presto.operator.TopNOperator$TopNBuilder.getValues(TopNOperator.java:338) at com.facebook.presto.operator.TopNOperator$TopNBuilder.addRow(TopNOperator.java:313) at com.facebook.presto.operator.TopNOperator$TopNBuilder.mergeWithGlobalCandidates(TopNOperator.java:284) at com.facebook.presto.operator.TopNOperator$TopNBuilder.processPage(TopNOperator.java:273) at com.facebook.presto.operator.TopNOperator.addInput(TopNOperator.java:202) at com.facebook.presto.operator.Driver.processInternal(Driver.java:384) at com.facebook.presto.operator.Driver.processFor(Driver.java:301) at com.facebook.presto.execution.SqlTaskExecution$DriverSplitRunner.processFor(SqlTaskExecution.java:618) at com.facebook.presto.execution.TaskExecutor$PrioritizedSplitRunner.process(TaskExecutor.java:529) at com.facebook.presto.execution.TaskExecutor$Runner.run(TaskExecutor.java:665) ... 3 more ``` This reproduces the issue: ``` java InterleavedBlock block = new InterleavedBlock(new Block[0]); block.copyRegion(0, 0); ``` (is that call to copyRegion even valid? If not, there might be another bug further up the stack, too) Also, the test in `AbstractInterleavedBlock`'s constructor is a bit suspect. The condition checks for "non-negative", but the message says "positive". Moreover, given that methods use that value in division operations, it would seem that we should ensure the value is never 0. ``` java if (columns < 0) { throw new IllegalArgumentException("Number of blocks in InterleavedBlock must be positive"); } ```
0f96a7e18f1e8eb654a55bdf15da4b8a1638d746
5928074ed7986b81b2fc9cf381314d980dd80175
https://github.com/prestodb/presto/compare/0f96a7e18f1e8eb654a55bdf15da4b8a1638d746...5928074ed7986b81b2fc9cf381314d980dd80175
diff --git a/presto-main/src/test/java/com/facebook/presto/block/TestInterleavedBlock.java b/presto-main/src/test/java/com/facebook/presto/block/TestInterleavedBlock.java index e3380eca5a..3bedad2d57 100644 --- a/presto-main/src/test/java/com/facebook/presto/block/TestInterleavedBlock.java +++ b/presto-main/src/test/java/com/facebook/presto/block/TestInterleavedBlock.java @@ -134,16 +134,17 @@ public class TestInterleavedBlock Type type = TYPES.get(position % TYPES.size()); assertInterleavedPosition(ImmutableList.of(type), block.getSingleValueBlock(position), 0, expectedValue); - assertInterleavedPosition(ImmutableList.of(type), block.getRegion(position, 1), 0, expectedValue); - assertInterleavedPosition(TYPES, block.getRegion(0, position + 1), position, expectedValue); - assertInterleavedPosition(ImmutableList.of(type), block.getRegion(position, block.getPositionCount() - position), 0, expectedValue); + int alignedPosition = position - position % COLUMN_COUNT; - assertInterleavedPosition(ImmutableList.of(type), block.copyRegion(position, 1), 0, expectedValue); - assertInterleavedPosition(TYPES, block.copyRegion(0, position + 1), position, expectedValue); - assertInterleavedPosition(ImmutableList.of(type), block.copyRegion(position, block.getPositionCount() - position), 0, expectedValue); + assertInterleavedPosition(ImmutableList.of(type), block.getRegion(alignedPosition, COLUMN_COUNT), position - alignedPosition, expectedValue); + assertInterleavedPosition(TYPES, block.getRegion(0, alignedPosition + COLUMN_COUNT), position, expectedValue); + assertInterleavedPosition(ImmutableList.of(type), block.getRegion(alignedPosition, block.getPositionCount() - alignedPosition), position - alignedPosition, expectedValue); - int positionFloored = position / COLUMN_COUNT * COLUMN_COUNT; - assertInterleavedPosition(TYPES, block.copyPositions(IntStream.range(positionFloored, positionFloored + COLUMN_COUNT).boxed().collect(Collectors.toList())), position % COLUMN_COUNT, expectedValue); + assertInterleavedPosition(ImmutableList.of(type), block.copyRegion(alignedPosition, COLUMN_COUNT), position - alignedPosition, expectedValue); + assertInterleavedPosition(TYPES, block.copyRegion(0, alignedPosition + COLUMN_COUNT), position, expectedValue); + assertInterleavedPosition(ImmutableList.of(type), block.copyRegion(alignedPosition, block.getPositionCount() - alignedPosition), position - alignedPosition, expectedValue); + + assertInterleavedPosition(TYPES, block.copyPositions(IntStream.range(alignedPosition, alignedPosition + COLUMN_COUNT).boxed().collect(Collectors.toList())), position % COLUMN_COUNT, expectedValue); } private <T> void assertInterleavedPosition(List<Type> types, Block block, int position, T expectedValue) diff --git a/presto-spi/src/main/java/com/facebook/presto/spi/block/AbstractInterleavedBlock.java b/presto-spi/src/main/java/com/facebook/presto/spi/block/AbstractInterleavedBlock.java index 80dc9daef9..0fdc5cb081 100644 --- a/presto-spi/src/main/java/com/facebook/presto/spi/block/AbstractInterleavedBlock.java +++ b/presto-spi/src/main/java/com/facebook/presto/spi/block/AbstractInterleavedBlock.java @@ -32,7 +32,7 @@ public abstract class AbstractInterleavedBlock protected AbstractInterleavedBlock(int columns) { - if (columns < 0) { + if (columns <= 0) { throw new IllegalArgumentException("Number of blocks in InterleavedBlock must be positive"); } this.columns = columns; @@ -43,12 +43,14 @@ public abstract class AbstractInterleavedBlock return columns; } - AbstractInterleavedBlock semiCompact() + Block[] computeSerializableSubBlocks() { - // the returned InterleavedBlock is guaranteed to have - // * start equal to 0 - // * positionCount equal to the sum of positionCount of column blocks - return getRegionAlwaysReturnInterleavedBlock(0, getPositionCount(), false); + InterleavedBlock interleavedBlock = (InterleavedBlock) sliceRange(0, getPositionCount(), false); + Block[] result = new Block[interleavedBlock.getBlockCount()]; + for (int i = 0; i < result.length; i++) { + result[i] = interleavedBlock.getBlock(i); + } + return result; } /** @@ -246,40 +248,30 @@ public abstract class AbstractInterleavedBlock @Override public Block copyRegion(int position, int length) { - return getRegion(position, length, true); + validateRange(position, length); + return sliceRange(position, length, true); } - protected Block getRegion(int position, int length, boolean compact) + protected void validateRange(int position, int length) { int positionCount = getPositionCount(); - if (position < 0 || length < 0 || position + length > positionCount) { - throw new IndexOutOfBoundsException("Invalid position (" + position + "), length (" + length + ") in block with " + positionCount + " positions"); - } - if (length <= 1) { - position = computePosition(position); - int positionInBlock = position / columns; - if (compact) { - return getBlock(position % columns).copyRegion(positionInBlock, length); - } - else { - return getBlock(position % columns).getRegion(positionInBlock, length); - } + if (position < 0 || length < 0 || position + length > positionCount || position % columns != 0 || length % columns != 0) { + throw new IndexOutOfBoundsException("Invalid position (" + position + "), length (" + length + ") in InterleavedBlock with " + positionCount + " positions and " + columns + " columns"); } - return getRegionAlwaysReturnInterleavedBlock(position, length, compact); } - private InterleavedBlock getRegionAlwaysReturnInterleavedBlock(int position, int length, boolean compact) + protected Block sliceRange(int position, int length, boolean compact) { position = computePosition(position); - Block[] resultBlocks = new Block[Math.min(columns, length)]; - for (int newBlockIndex = 0; newBlockIndex < resultBlocks.length; newBlockIndex++) { - int positionInBlock = (position + newBlockIndex) / columns; - int subBlockLength = (length + columns - 1 - newBlockIndex) / columns; + Block[] resultBlocks = new Block[columns]; + int positionInBlock = position / columns; + int subBlockLength = length / columns; + for (int blockIndex = 0; blockIndex < columns; blockIndex++) { if (compact) { - resultBlocks[newBlockIndex] = getBlock((newBlockIndex + position) % columns).copyRegion(positionInBlock, subBlockLength); + resultBlocks[blockIndex] = getBlock((blockIndex + position) % columns).copyRegion(positionInBlock, subBlockLength); } else { - resultBlocks[newBlockIndex] = getBlock((newBlockIndex + position) % columns).getRegion(positionInBlock, subBlockLength); + resultBlocks[blockIndex] = getBlock((blockIndex + position) % columns).getRegion(positionInBlock, subBlockLength); } } return new InterleavedBlock(resultBlocks); diff --git a/presto-spi/src/main/java/com/facebook/presto/spi/block/InterleavedBlock.java b/presto-spi/src/main/java/com/facebook/presto/spi/block/InterleavedBlock.java index d5a104133f..2d53a1c711 100644 --- a/presto-spi/src/main/java/com/facebook/presto/spi/block/InterleavedBlock.java +++ b/presto-spi/src/main/java/com/facebook/presto/spi/block/InterleavedBlock.java @@ -35,37 +35,17 @@ public class InterleavedBlock super(blocks.length); this.blocks = blocks; - // Aside from calculating sizeInBytes, retainedSizeInBytes, and positionCount, - // the loop below verifies that the position count of sub-blocks in the InterleavedBlock - // * differs by at most one - // * is non-ascending int sizeInBytes = 0; int retainedSizeInBytes = INSTANCE_SIZE; int positionCount = 0; - if (blocks.length != 0) { - int firstSubBlockPositionCount = blocks[0].getPositionCount(); - boolean subBlockHasDifferentSize = false; - for (int i = 0; i < getBlockCount(); i++) { - sizeInBytes += blocks[i].getSizeInBytes(); - retainedSizeInBytes += blocks[i].getRetainedSizeInBytes(); - positionCount += blocks[i].getPositionCount(); - - if (subBlockHasDifferentSize) { - if (firstSubBlockPositionCount - 1 != blocks[i].getPositionCount()) { - throw new IllegalArgumentException( - "length of sub blocks differ by at least 2 or is not non-ascending: block 0: " + firstSubBlockPositionCount + ", block " + i + ": " + blocks[i].getPositionCount()); - } - } - else { - if (firstSubBlockPositionCount != blocks[i].getPositionCount()) { - if (firstSubBlockPositionCount - 1 == blocks[i].getPositionCount()) { - subBlockHasDifferentSize = true; - } - else { - throw new IllegalArgumentException("length of sub blocks differ by at least 2: block 0: " + firstSubBlockPositionCount + ", block " + i + ": " + blocks[i].getPositionCount()); - } - } - } + int firstSubBlockPositionCount = blocks[0].getPositionCount(); + for (int i = 0; i < getBlockCount(); i++) { + sizeInBytes += blocks[i].getSizeInBytes(); + retainedSizeInBytes += blocks[i].getRetainedSizeInBytes(); + positionCount += blocks[i].getPositionCount(); + + if (firstSubBlockPositionCount != blocks[i].getPositionCount()) { + throw new IllegalArgumentException("length of sub blocks differ: block 0: " + firstSubBlockPositionCount + ", block " + i + ": " + blocks[i].getPositionCount()); } } @@ -90,9 +70,7 @@ public class InterleavedBlock @Override public Block getRegion(int position, int length) { - if (position < 0 || length < 0 || position + length > positionCount) { - throw new IndexOutOfBoundsException("Invalid position (" + position + "), length (" + length + ") in block with " + positionCount + " positions"); - } + validateRange(position, length); return new InterleavedBlock(blocks, computePosition(position), length, retainedSizeInBytes, blockEncoding); } diff --git a/presto-spi/src/main/java/com/facebook/presto/spi/block/InterleavedBlockBuilder.java b/presto-spi/src/main/java/com/facebook/presto/spi/block/InterleavedBlockBuilder.java index 2c30b96f5e..395ac8548a 100644 --- a/presto-spi/src/main/java/com/facebook/presto/spi/block/InterleavedBlockBuilder.java +++ b/presto-spi/src/main/java/com/facebook/presto/spi/block/InterleavedBlockBuilder.java @@ -238,7 +238,8 @@ public class InterleavedBlockBuilder @Override public Block getRegion(int position, int length) { - return getRegion(position, length, false); + validateRange(position, length); + return sliceRange(position, length, false); } @Override diff --git a/presto-spi/src/main/java/com/facebook/presto/spi/block/InterleavedBlockEncoding.java b/presto-spi/src/main/java/com/facebook/presto/spi/block/InterleavedBlockEncoding.java index a62b514079..a595b8e92a 100644 --- a/presto-spi/src/main/java/com/facebook/presto/spi/block/InterleavedBlockEncoding.java +++ b/presto-spi/src/main/java/com/facebook/presto/spi/block/InterleavedBlockEncoding.java @@ -39,25 +39,16 @@ public class InterleavedBlockEncoding @Override public void writeBlock(SliceOutput sliceOutput, Block block) { - if (block.getPositionCount() == 0) { - sliceOutput.appendByte(1); - return; - } - else { - sliceOutput.appendByte(0); - } - AbstractInterleavedBlock interleavedBlock = (AbstractInterleavedBlock) block; - interleavedBlock = interleavedBlock.semiCompact(); - if (interleavedBlock.getBlockCount() != individualBlockEncodings.length) { throw new IllegalArgumentException( "argument block differs in length (" + interleavedBlock.getBlockCount() + ") with this encoding (" + individualBlockEncodings.length + ")"); } - for (int i = 0; i < individualBlockEncodings.length; i++) { - individualBlockEncodings[i].writeBlock(sliceOutput, interleavedBlock.getBlock(i)); + Block[] subBlocks = interleavedBlock.computeSerializableSubBlocks(); + for (int i = 0; i < subBlocks.length; i++) { + individualBlockEncodings[i].writeBlock(sliceOutput, subBlocks[i]); } } @@ -71,11 +62,6 @@ public class InterleavedBlockEncoding @Override public Block readBlock(SliceInput sliceInput) { - byte isEmpty = sliceInput.readByte(); - if (isEmpty == 1) { - return new InterleavedBlock(new Block[0]); - } - Block[] individualBlocks = new Block[individualBlockEncodings.length]; for (int i = 0; i < individualBlockEncodings.length; i++) { individualBlocks[i] = individualBlockEncodings[i].readBlock(sliceInput);
['presto-spi/src/main/java/com/facebook/presto/spi/block/InterleavedBlockEncoding.java', 'presto-main/src/test/java/com/facebook/presto/block/TestInterleavedBlock.java', 'presto-spi/src/main/java/com/facebook/presto/spi/block/InterleavedBlockBuilder.java', 'presto-spi/src/main/java/com/facebook/presto/spi/block/AbstractInterleavedBlock.java', 'presto-spi/src/main/java/com/facebook/presto/spi/block/InterleavedBlock.java']
{'.java': 5}
5
5
0
0
5
11,919,889
2,365,646
333,048
2,412
6,828
1,423
111
4
4,767
246
1,144
79
0
5
1970-01-01T00:24:26
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
217
prestodb/presto/1869/1864
prestodb
presto
https://github.com/prestodb/presto/issues/1864
https://github.com/prestodb/presto/pull/1869
https://github.com/prestodb/presto/pull/1869
1
fixes
Null partition keys break Hive partition pruning
If the table has a partition key like `key=__HIVE_DEFAULT_PARTITION__`, the following query: ``` SELECT key , count(*) from TABLE GROUP BY 1 ``` returns results like: ``` key | _col1 ---------+-------- windows | 1 NULL | 2 ios | 3 android | 4 (4 rows) ``` But the following query return no rows: ``` SELECT key , count(*) from TABLE WHERE key is null GROUP BY 1 ```
477d90d9ba6a9fa75c9eecffd63564a31411b551
9c0145af61020fda5fd2042e1388eb29bdea4d90
https://github.com/prestodb/presto/compare/477d90d9ba6a9fa75c9eecffd63564a31411b551...9c0145af61020fda5fd2042e1388eb29bdea4d90
diff --git a/presto-hive/src/main/java/com/facebook/presto/hive/HiveUtil.java b/presto-hive/src/main/java/com/facebook/presto/hive/HiveUtil.java index 5291b65c4c..a53f35414e 100644 --- a/presto-hive/src/main/java/com/facebook/presto/hive/HiveUtil.java +++ b/presto-hive/src/main/java/com/facebook/presto/hive/HiveUtil.java @@ -62,6 +62,7 @@ import java.util.concurrent.Callable; import static com.facebook.presto.hive.HiveColumnHandle.hiveColumnIndexGetter; import static com.facebook.presto.hive.HiveColumnHandle.isPartitionKeyPredicate; import static com.facebook.presto.hive.HiveErrorCode.HIVE_CANNOT_OPEN_SPLIT; +import static com.facebook.presto.hive.HivePartitionKey.HIVE_DEFAULT_DYNAMIC_PARTITION; import static com.facebook.presto.hive.HiveType.HIVE_BOOLEAN; import static com.facebook.presto.hive.HiveType.HIVE_BYTE; import static com.facebook.presto.hive.HiveType.HIVE_DATE; @@ -321,7 +322,7 @@ public final class HiveUtil public static SerializableNativeValue parsePartitionValue(String partitionName, String value, HiveType hiveType, DateTimeZone timeZone) { - boolean isNull = isHiveNull(value.getBytes(UTF_8)); + boolean isNull = HIVE_DEFAULT_DYNAMIC_PARTITION.equals(value); if (HIVE_BOOLEAN.equals(hiveType)) { if (isNull) {
['presto-hive/src/main/java/com/facebook/presto/hive/HiveUtil.java']
{'.java': 1}
1
1
0
0
1
6,980,015
1,386,712
202,472
1,487
221
48
3
1
400
68
121
33
0
3
1970-01-01T00:23:34
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
195
prestodb/presto/6051/5980
prestodb
presto
https://github.com/prestodb/presto/issues/5980
https://github.com/prestodb/presto/pull/6051
https://github.com/prestodb/presto/pull/6051
1
fixes
Presto stats planning time is including queueing time
I noticed this when Presto was reporting super long planning times, but it looks like this was just because the queues are really full.
e00be17eb45de151374fd2fe19476074e6bb9712
c8945f4eb87d27f1b8ac5645973ed5ffd11d5266
https://github.com/prestodb/presto/compare/e00be17eb45de151374fd2fe19476074e6bb9712...c8945f4eb87d27f1b8ac5645973ed5ffd11d5266
diff --git a/presto-main/src/main/java/com/facebook/presto/execution/QueryStateMachine.java b/presto-main/src/main/java/com/facebook/presto/execution/QueryStateMachine.java index 8751bd1139..f97902577c 100644 --- a/presto-main/src/main/java/com/facebook/presto/execution/QueryStateMachine.java +++ b/presto-main/src/main/java/com/facebook/presto/execution/QueryStateMachine.java @@ -25,6 +25,7 @@ import com.facebook.presto.sql.planner.PlanFragment; import com.facebook.presto.sql.planner.plan.TableScanNode; import com.facebook.presto.transaction.TransactionId; import com.facebook.presto.transaction.TransactionManager; +import com.google.common.base.Ticker; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; @@ -61,7 +62,7 @@ import static com.facebook.presto.spi.StandardErrorCode.USER_CANCELED; import static com.facebook.presto.util.Failures.toFailure; import static com.google.common.base.Preconditions.checkArgument; import static io.airlift.units.DataSize.succinctBytes; -import static io.airlift.units.Duration.nanosSince; +import static io.airlift.units.Duration.succinctNanos; import static java.util.Objects.requireNonNull; import static java.util.concurrent.TimeUnit.NANOSECONDS; @@ -71,7 +72,7 @@ public class QueryStateMachine private static final Logger log = Logger.get(QueryStateMachine.class); private final DateTime createTime = DateTime.now(); - private final long createNanos = System.nanoTime(); + private final long createNanos; private final AtomicLong endNanos = new AtomicLong(); private final QueryId queryId; @@ -80,6 +81,7 @@ public class QueryStateMachine private final URI self; private final boolean autoCommit; private final TransactionManager transactionManager; + private final Ticker ticker; private final AtomicReference<VersionedMemoryPoolId> memoryPool = new AtomicReference<>(new VersionedMemoryPoolId(GENERAL_POOL, 0)); @@ -96,6 +98,7 @@ public class QueryStateMachine private final AtomicReference<Long> finishingStartNanos = new AtomicReference<>(); private final AtomicReference<Duration> finishingTime = new AtomicReference<>(); + private final AtomicReference<Long> totalPlanningStartNanos = new AtomicReference<>(); private final AtomicReference<Duration> totalPlanningTime = new AtomicReference<>(); private final StateMachine<QueryState> queryState; @@ -119,7 +122,7 @@ public class QueryStateMachine private final AtomicReference<Optional<Output>> output = new AtomicReference<>(Optional.empty()); private final StateMachine<Optional<QueryInfo>> finalQueryInfo; - private QueryStateMachine(QueryId queryId, String query, Session session, URI self, boolean autoCommit, TransactionManager transactionManager, Executor executor) + private QueryStateMachine(QueryId queryId, String query, Session session, URI self, boolean autoCommit, TransactionManager transactionManager, Executor executor, Ticker ticker) { this.queryId = requireNonNull(queryId, "queryId is null"); this.query = requireNonNull(query, "query is null"); @@ -127,6 +130,8 @@ public class QueryStateMachine this.self = requireNonNull(self, "self is null"); this.autoCommit = autoCommit; this.transactionManager = requireNonNull(transactionManager, "transactionManager is null"); + this.ticker = ticker; + this.createNanos = tickerNanos(); this.queryState = new StateMachine<>("query " + query, executor, QUEUED, TERMINAL_QUERY_STATES); this.finalQueryInfo = new StateMachine<>("finalQueryInfo-" + queryId, executor, Optional.empty()); @@ -136,6 +141,19 @@ public class QueryStateMachine * Created QueryStateMachines must be transitioned to terminal states to clean up resources. */ public static QueryStateMachine begin(QueryId queryId, String query, Session session, URI self, boolean transactionControl, TransactionManager transactionManager, Executor executor) + { + return beginWithTicker(queryId, query, session, self, transactionControl, transactionManager, executor, Ticker.systemTicker()); + } + + static QueryStateMachine beginWithTicker( + QueryId queryId, + String query, + Session session, + URI self, + boolean transactionControl, + TransactionManager transactionManager, + Executor executor, + Ticker ticker) { session.getTransactionId().ifPresent(transactionControl ? transactionManager::trySetActive : transactionManager::checkAndSetActive); @@ -150,7 +168,7 @@ public class QueryStateMachine querySession = session; } - QueryStateMachine queryStateMachine = new QueryStateMachine(queryId, query, querySession, self, autoCommit, transactionManager, executor); + QueryStateMachine queryStateMachine = new QueryStateMachine(queryId, query, querySession, self, autoCommit, transactionManager, executor, ticker); queryStateMachine.addStateChangeListener(newState -> log.debug("Query %s is %s", queryId, newState)); queryStateMachine.addStateChangeListener(newState -> { if (newState.isDone()) { @@ -166,7 +184,20 @@ public class QueryStateMachine */ public static QueryStateMachine failed(QueryId queryId, String query, Session session, URI self, TransactionManager transactionManager, Executor executor, Throwable throwable) { - QueryStateMachine queryStateMachine = new QueryStateMachine(queryId, query, session, self, false, transactionManager, executor); + return failedWithTicker(queryId, query, session, self, transactionManager, executor, Ticker.systemTicker(), throwable); + } + + static QueryStateMachine failedWithTicker( + QueryId queryId, + String query, + Session session, + URI self, + TransactionManager transactionManager, + Executor executor, + Ticker ticker, + Throwable throwable) + { + QueryStateMachine queryStateMachine = new QueryStateMachine(queryId, query, session, self, false, transactionManager, executor, ticker); queryStateMachine.transitionToFailed(throwable); return queryStateMachine; } @@ -472,14 +503,15 @@ public class QueryStateMachine public boolean transitionToPlanning() { queuedTime.compareAndSet(null, nanosSince(createNanos).convertToMostSuccinctTimeUnit()); + totalPlanningStartNanos.compareAndSet(null, tickerNanos()); return queryState.compareAndSet(QUEUED, PLANNING); } public boolean transitionToStarting() { - Duration durationSinceCreation = nanosSince(createNanos).convertToMostSuccinctTimeUnit(); - queuedTime.compareAndSet(null, durationSinceCreation); - totalPlanningTime.compareAndSet(null, durationSinceCreation); + queuedTime.compareAndSet(null, nanosSince(createNanos).convertToMostSuccinctTimeUnit()); + totalPlanningStartNanos.compareAndSet(null, tickerNanos()); + totalPlanningTime.compareAndSet(null, nanosSince(totalPlanningStartNanos.get())); return queryState.setIf(STARTING, currentState -> currentState == QUEUED || currentState == PLANNING); } @@ -488,7 +520,8 @@ public class QueryStateMachine { Duration durationSinceCreation = nanosSince(createNanos).convertToMostSuccinctTimeUnit(); queuedTime.compareAndSet(null, durationSinceCreation); - totalPlanningTime.compareAndSet(null, durationSinceCreation); + totalPlanningStartNanos.compareAndSet(null, tickerNanos()); + totalPlanningTime.compareAndSet(null, nanosSince(totalPlanningStartNanos.get())); executionStartTime.compareAndSet(null, DateTime.now()); return queryState.setIf(RUNNING, currentState -> currentState != RUNNING && currentState != FINISHING && !currentState.isDone()); @@ -498,10 +531,11 @@ public class QueryStateMachine { Duration durationSinceCreation = nanosSince(createNanos).convertToMostSuccinctTimeUnit(); queuedTime.compareAndSet(null, durationSinceCreation); - totalPlanningTime.compareAndSet(null, durationSinceCreation); + totalPlanningStartNanos.compareAndSet(null, tickerNanos()); + totalPlanningTime.compareAndSet(null, nanosSince(totalPlanningStartNanos.get())); DateTime now = DateTime.now(); executionStartTime.compareAndSet(null, now); - finishingStartNanos.compareAndSet(null, System.nanoTime()); + finishingStartNanos.compareAndSet(null, tickerNanos()); if (!queryState.setIf(FINISHING, currentState -> currentState != FINISHING && !currentState.isDone())) { return false; @@ -575,13 +609,14 @@ public class QueryStateMachine { Duration durationSinceCreation = nanosSince(createNanos).convertToMostSuccinctTimeUnit(); queuedTime.compareAndSet(null, durationSinceCreation); - totalPlanningTime.compareAndSet(null, durationSinceCreation); + totalPlanningStartNanos.compareAndSet(null, tickerNanos()); + totalPlanningTime.compareAndSet(null, nanosSince(totalPlanningStartNanos.get())); DateTime now = DateTime.now(); executionStartTime.compareAndSet(null, now); - finishingStartNanos.compareAndSet(null, System.nanoTime()); + finishingStartNanos.compareAndSet(null, tickerNanos()); finishingTime.compareAndSet(null, nanosSince(finishingStartNanos.get())); endTime.compareAndSet(null, now); - endNanos.compareAndSet(0, System.nanoTime()); + endNanos.compareAndSet(0, tickerNanos()); } public void addStateChangeListener(StateChangeListener<QueryState> stateChangeListener) @@ -693,4 +728,14 @@ public class QueryStateMachine ); finalQueryInfo.compareAndSet(finalInfo, Optional.of(prunedQueryInfo)); } + + private long tickerNanos() + { + return ticker.read(); + } + + private Duration nanosSince(long start) + { + return succinctNanos(tickerNanos() - start); + } } diff --git a/presto-main/src/test/java/com/facebook/presto/execution/TestQueryStateMachine.java b/presto-main/src/test/java/com/facebook/presto/execution/TestQueryStateMachine.java index 8dafa666ce..2417172563 100644 --- a/presto-main/src/test/java/com/facebook/presto/execution/TestQueryStateMachine.java +++ b/presto-main/src/test/java/com/facebook/presto/execution/TestQueryStateMachine.java @@ -21,8 +21,10 @@ import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.QueryId; import com.facebook.presto.spi.memory.MemoryPoolId; import com.facebook.presto.transaction.TransactionManager; +import com.google.common.base.Ticker; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import io.airlift.testing.TestingTicker; import io.airlift.units.Duration; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; @@ -243,6 +245,36 @@ public class TestQueryStateMachine assertFinalState(stateMachine, FAILED, new PrestoException(USER_CANCELED, "canceled")); } + @Test + public void testPlanningTimeDuration() + throws InterruptedException + { + TestingTicker mockTicker = new TestingTicker(); + QueryStateMachine stateMachine = createQueryStateMachineWithTicker(mockTicker); + assertState(stateMachine, QUEUED); + + mockTicker.increment(100, TimeUnit.MILLISECONDS); + assertTrue(stateMachine.transitionToPlanning()); + assertState(stateMachine, PLANNING); + + mockTicker.increment(500, TimeUnit.MILLISECONDS); + assertTrue(stateMachine.transitionToStarting()); + assertState(stateMachine, STARTING); + + mockTicker.increment(300, TimeUnit.MILLISECONDS); + assertTrue(stateMachine.transitionToRunning()); + assertState(stateMachine, RUNNING); + + mockTicker.increment(200, TimeUnit.MILLISECONDS); + assertTrue(stateMachine.transitionToFinishing()); + stateMachine.waitForStateChange(FINISHING, new Duration(2, TimeUnit.SECONDS)); + assertState(stateMachine, FINISHED); + + QueryStats queryStats = stateMachine.getQueryInfo(Optional.empty()).getQueryStats(); + assertTrue(queryStats.getQueuedTime().toMillis() == 100); + assertTrue(queryStats.getTotalPlanningTime().toMillis() == 500); + } + private static void assertFinalState(QueryStateMachine stateMachine, QueryState expectedState) { assertFinalState(stateMachine, expectedState, null); @@ -362,9 +394,14 @@ public class TestQueryStateMachine } private QueryStateMachine createQueryStateMachine() + { + return createQueryStateMachineWithTicker(Ticker.systemTicker()); + } + + private QueryStateMachine createQueryStateMachineWithTicker(Ticker ticker) { TransactionManager transactionManager = createTestTransactionManager(); - QueryStateMachine stateMachine = QueryStateMachine.begin(QUERY_ID, QUERY, TEST_SESSION, LOCATION, false, transactionManager, executor); + QueryStateMachine stateMachine = QueryStateMachine.beginWithTicker(QUERY_ID, QUERY, TEST_SESSION, LOCATION, false, transactionManager, executor, ticker); stateMachine.setInputs(INPUTS); stateMachine.setOutput(OUTPUT); stateMachine.setOutputFieldNames(OUTPUT_FIELD_NAMES);
['presto-main/src/main/java/com/facebook/presto/execution/QueryStateMachine.java', 'presto-main/src/test/java/com/facebook/presto/execution/TestQueryStateMachine.java']
{'.java': 2}
2
2
0
0
2
12,586,593
2,498,152
349,496
2,544
4,112
801
73
1
136
24
27
2
0
0
1970-01-01T00:24:33
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
194
prestodb/presto/6064/6059
prestodb
presto
https://github.com/prestodb/presto/issues/6059
https://github.com/prestodb/presto/pull/6064
https://github.com/prestodb/presto/pull/6064
1
fixes
Incorrect results when cross joining against aggregation over partitioned table
This query: ``` sql SELECT * FROM (VALUES 1, 2, 3) t CROSS JOIN (SELECT count(*) FROM table WHERE pk = 'non-existent') u ``` (`pk` is a partition key for `table`) produces an incorrect plan: ``` - Output[_col0, _col1] => [field:bigint, count:bigint] _col0 := field _col1 := count - InnerJoin[] => [field:bigint, count:bigint] - Filter[false] => [field:bigint] - Values => [field:bigint] (1) (2) (3) - Aggregate(FINAL) => [count:bigint] count := "count"("count_235") - Exchange[GATHER] => count_235:bigint - Aggregate(PARTIAL) => [count_235:bigint] count_235 := "count"(*) - TableScan[...] => [] :: NONE ``` It seems to be pushing the "false" predicate (due to no matching partitions) up through the aggregation and pushing it down on the left side.
b9bfdf045d2b5a6c1df0b25639e09987a66edeaf
dbb55b8e893f636c0ce7a2c422c2914c9ae68df1
https://github.com/prestodb/presto/compare/b9bfdf045d2b5a6c1df0b25639e09987a66edeaf...dbb55b8e893f636c0ce7a2c422c2914c9ae68df1
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/EffectivePredicateExtractor.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/EffectivePredicateExtractor.java index ac5ebf2d10..9f6ba10ef6 100644 --- a/presto-main/src/main/java/com/facebook/presto/sql/planner/EffectivePredicateExtractor.java +++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/EffectivePredicateExtractor.java @@ -100,6 +100,15 @@ public class EffectivePredicateExtractor @Override public Expression visitAggregation(AggregationNode node, Void context) { + // GROUP BY () always produces a group, regardless of whether there's any + // input (unlike the case where there are group by keys, which produce + // no output if there's no input). + // Therefore, we can't say anything about the effective predicate of the + // output of such an aggregation. + if (node.getGroupBy().isEmpty()) { + return TRUE_LITERAL; + } + Expression underlyingPredicate = node.getSource().accept(this, context); return pullExpressionThroughSymbols(underlyingPredicate, node.getGroupBy()); diff --git a/presto-main/src/test/java/com/facebook/presto/sql/planner/TestEffectivePredicateExtractor.java b/presto-main/src/test/java/com/facebook/presto/sql/planner/TestEffectivePredicateExtractor.java index b0eb0b7cf8..5b2b25836c 100644 --- a/presto-main/src/test/java/com/facebook/presto/sql/planner/TestEffectivePredicateExtractor.java +++ b/presto-main/src/test/java/com/facebook/presto/sql/planner/TestEffectivePredicateExtractor.java @@ -72,6 +72,7 @@ import static com.facebook.presto.sql.ExpressionUtils.and; import static com.facebook.presto.sql.ExpressionUtils.combineConjuncts; import static com.facebook.presto.sql.ExpressionUtils.or; import static com.facebook.presto.sql.tree.BooleanLiteral.FALSE_LITERAL; +import static com.facebook.presto.sql.tree.BooleanLiteral.TRUE_LITERAL; import static org.testng.Assert.assertEquals; @Test(singleThreaded = true) @@ -167,6 +168,28 @@ public class TestEffectivePredicateExtractor equals(BE, CE))); } + @Test + public void testGroupByEmpty() + throws Exception + { + PlanNode node = new AggregationNode( + newId(), + filter(baseTableScan, FALSE_LITERAL), + ImmutableList.of(), + ImmutableMap.of(), + ImmutableMap.of(), + ImmutableMap.of(), + ImmutableList.of(), + AggregationNode.Step.FINAL, + Optional.empty(), + 1.0, + Optional.empty()); + + Expression effectivePredicate = EffectivePredicateExtractor.extract(node, TYPES); + + assertEquals(effectivePredicate, TRUE_LITERAL); + } + @Test public void testFilter() throws Exception
['presto-main/src/test/java/com/facebook/presto/sql/planner/TestEffectivePredicateExtractor.java', 'presto-main/src/main/java/com/facebook/presto/sql/planner/EffectivePredicateExtractor.java']
{'.java': 2}
2
2
0
0
2
12,470,920
2,475,474
346,627
2,522
422
87
9
1
994
114
247
31
0
2
1970-01-01T00:24:33
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
211
prestodb/presto/4045/4043
prestodb
presto
https://github.com/prestodb/presto/issues/4043
https://github.com/prestodb/presto/pull/4045
https://github.com/prestodb/presto/pull/4045
1
fixes
The node_id column in deleted_shard_nodes should not be nullable
The table tracks shards for a node, so it should be `NOT NULL`. Being nullable is probably a leftover from when the same table was used for local and global shards (during development of the feature).
607cfd4aab6eb5c6f9d6a3f4e5a5dfb1a014205c
f4263193b0eb7ef43931ed8beb87d3ea8d75b7fa
https://github.com/prestodb/presto/compare/607cfd4aab6eb5c6f9d6a3f4e5a5dfb1a014205c...f4263193b0eb7ef43931ed8beb87d3ea8d75b7fa
diff --git a/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/SchemaDao.java b/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/SchemaDao.java index ab13aa5c8d..59efccbe72 100644 --- a/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/SchemaDao.java +++ b/presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/SchemaDao.java @@ -94,7 +94,7 @@ public interface SchemaDao @SqlUpdate("CREATE TABLE IF NOT EXISTS created_shards (\\n" + " shard_uuid BINARY(16) NOT NULL,\\n" + - " transaction_id bigint NOT NULL,\\n" + + " transaction_id BIGINT NOT NULL,\\n" + " PRIMARY KEY (shard_uuid),\\n" + " FOREIGN KEY (transaction_id) REFERENCES transactions (transaction_id)\\n" + ")") @@ -103,7 +103,7 @@ public interface SchemaDao @SqlUpdate("CREATE TABLE IF NOT EXISTS created_shard_nodes (\\n" + " shard_uuid BINARY(16) NOT NULL,\\n" + " node_id INT NOT NULL,\\n" + - " transaction_id bigint NOT NULL,\\n" + + " transaction_id BIGINT NOT NULL,\\n" + " PRIMARY KEY (shard_uuid, node_id),\\n" + " FOREIGN KEY (node_id) REFERENCES nodes (node_id),\\n" + " FOREIGN KEY (transaction_id) REFERENCES transactions (transaction_id)\\n" + @@ -120,7 +120,7 @@ public interface SchemaDao @SqlUpdate("CREATE TABLE IF NOT EXISTS deleted_shard_nodes (\\n" + " shard_uuid BINARY(16) NOT NULL,\\n" + - " node_id INT,\\n" + + " node_id INT NOT NULL,\\n" + " delete_time DATETIME NOT NULL,\\n" + " clean_time DATETIME,\\n" + " purge_time DATETIME,\\n" +
['presto-raptor/src/main/java/com/facebook/presto/raptor/metadata/SchemaDao.java']
{'.java': 1}
1
1
0
0
1
9,506,282
1,891,231
269,547
1,969
288
72
6
1
201
36
41
2
0
0
1970-01-01T00:24:08
14,935
Java
{'Java': 53409077, 'C++': 959227, 'JavaScript': 286856, 'Shell': 61154, 'Roff': 52281, 'Python': 39357, 'ANTLR': 33548, 'CMake': 33259, 'HTML': 29601, 'CSS': 28319, 'Mustache': 17803, 'Makefile': 17213, 'Thrift': 14675, 'NASL': 13553, 'Dockerfile': 8372, 'Batchfile': 795, 'PLSQL': 85}
Apache License 2.0
9,731
deeplearning4j/deeplearning4j/5363/5263
deeplearning4j
deeplearning4j
https://github.com/deeplearning4j/deeplearning4j/issues/5263
https://github.com/deeplearning4j/deeplearning4j/pull/5363
https://github.com/deeplearning4j/deeplearning4j/pull/5363
1
fixes
DataVec: Unit test failure - TestNativeImageLoader.testAsMatrix
This is very likely related to long shapes, but couldn't at first glance see what the fix would be. ``` java.lang.IndexOutOfBoundsException: 3 at org.bytedeco.javacpp.indexer.Indexer.checkIndex(Indexer.java:90) at org.bytedeco.javacpp.indexer.FloatRawIndexer.put(FloatRawIndexer.java:90) at org.bytedeco.javacpp.indexer.FloatRawIndexer.put(FloatRawIndexer.java:110) at org.datavec.image.loader.NativeImageLoader.asMat(NativeImageLoader.java:724) at org.datavec.image.loader.NativeImageLoader.asMat(NativeImageLoader.java:684) at org.datavec.image.loader.TestNativeImageLoader.testAsMatrix(TestNativeImageLoader.java:235) ```
d5f2f8d1c07d18813064598285fe6acccbd24393
3a6e80d1fe4d620320ab9e24ac38bceda2da8eba
https://github.com/deeplearning4j/deeplearning4j/compare/d5f2f8d1c07d18813064598285fe6acccbd24393...3a6e80d1fe4d620320ab9e24ac38bceda2da8eba
diff --git a/datavec/datavec-api/src/main/java/org/datavec/api/io/filters/BalancedPathFilter.java b/datavec/datavec-api/src/main/java/org/datavec/api/io/filters/BalancedPathFilter.java index 3242e0315a..8c0168d428 100644 --- a/datavec/datavec-api/src/main/java/org/datavec/api/io/filters/BalancedPathFilter.java +++ b/datavec/datavec-api/src/main/java/org/datavec/api/io/filters/BalancedPathFilter.java @@ -32,7 +32,7 @@ import java.util.*; public class BalancedPathFilter extends RandomPathFilter { protected PathLabelGenerator labelGenerator; - protected int maxLabels = 0, minPathsPerLabel = 0, maxPathsPerLabel = 0; + protected long maxLabels = 0, minPathsPerLabel = 0, maxPathsPerLabel = 0; protected String[] labels = null; /** Calls {@code this(random, extensions, labelGenerator, 0, 0, 0, 0)}. */ @@ -41,25 +41,25 @@ public class BalancedPathFilter extends RandomPathFilter { } /** Calls {@code this(random, null, labelGenerator, 0, 0, 0, maxPathsPerLabel)}. */ - public BalancedPathFilter(Random random, PathLabelGenerator labelGenerator, int maxPathsPerLabel) { + public BalancedPathFilter(Random random, PathLabelGenerator labelGenerator, long maxPathsPerLabel) { this(random, null, labelGenerator, 0, 0, 0, maxPathsPerLabel); } /** Calls {@code this(random, extensions, labelGenerator, 0, 0, 0, maxPathsPerLabel)}. */ public BalancedPathFilter(Random random, String[] extensions, PathLabelGenerator labelGenerator, - int maxPathsPerLabel) { + long maxPathsPerLabel) { this(random, extensions, labelGenerator, 0, 0, 0, maxPathsPerLabel); } /** Calls {@code this(random, extensions, labelGenerator, 0, maxLabels, 0, maxPathsPerLabel)}. */ - public BalancedPathFilter(Random random, PathLabelGenerator labelGenerator, int maxPaths, int maxLabels, - int maxPathsPerLabel) { + public BalancedPathFilter(Random random, PathLabelGenerator labelGenerator, long maxPaths, long maxLabels, + long maxPathsPerLabel) { this(random, null, labelGenerator, maxPaths, maxLabels, 0, maxPathsPerLabel); } /** Calls {@code this(random, extensions, labelGenerator, 0, maxLabels, 0, maxPathsPerLabel)}. */ - public BalancedPathFilter(Random random, String[] extensions, PathLabelGenerator labelGenerator, int maxLabels, - int maxPathsPerLabel) { + public BalancedPathFilter(Random random, String[] extensions, PathLabelGenerator labelGenerator, long maxLabels, + long maxPathsPerLabel) { this(random, extensions, labelGenerator, 0, maxLabels, 0, maxPathsPerLabel); } @@ -77,8 +77,8 @@ public class BalancedPathFilter extends RandomPathFilter { * @param maxPathsPerLabel max number of paths per labels to return (0 == unlimited) * @param labels of the paths to keep (empty set == keep all paths) */ - public BalancedPathFilter(Random random, String[] extensions, PathLabelGenerator labelGenerator, int maxPaths, - int maxLabels, int minPathsPerLabel, int maxPathsPerLabel, String... labels) { + public BalancedPathFilter(Random random, String[] extensions, PathLabelGenerator labelGenerator, long maxPaths, + long maxLabels, long minPathsPerLabel, long maxPathsPerLabel, String... labels) { super(random, extensions, maxPaths); this.labelGenerator = labelGenerator; this.maxLabels = maxLabels; @@ -121,14 +121,15 @@ public class BalancedPathFilter extends RandomPathFilter { pathList.add(path); } - int minCount = maxPathsPerLabel > 0 ? maxPathsPerLabel : Integer.MAX_VALUE; + int minCount = maxPathsPerLabel > 0 ? + (int)Math.min(maxPathsPerLabel, Integer.MAX_VALUE) : Integer.MAX_VALUE; for (List<URI> pathList : labelPaths.values()) { if (minCount > pathList.size()) { minCount = pathList.size(); } } if (minCount < minPathsPerLabel) { - minCount = minPathsPerLabel; + minCount = (int)Math.min(minPathsPerLabel, Integer.MAX_VALUE); } ArrayList<URI> newpaths = new ArrayList<URI>(); diff --git a/datavec/datavec-api/src/main/java/org/datavec/api/io/filters/RandomPathFilter.java b/datavec/datavec-api/src/main/java/org/datavec/api/io/filters/RandomPathFilter.java index 92158c0314..d1636731c6 100644 --- a/datavec/datavec-api/src/main/java/org/datavec/api/io/filters/RandomPathFilter.java +++ b/datavec/datavec-api/src/main/java/org/datavec/api/io/filters/RandomPathFilter.java @@ -29,7 +29,7 @@ public class RandomPathFilter implements PathFilter { protected Random random; protected String[] extensions; - protected int maxPaths = 0; + protected long maxPaths = 0; /** Calls {@code this(random, extensions, 0)}. */ public RandomPathFilter(Random random, String... extensions) { @@ -43,7 +43,7 @@ public class RandomPathFilter implements PathFilter { * @param extensions of files to keep * @param maxPaths max number of paths to return (0 == unlimited) */ - public RandomPathFilter(Random random, String[] extensions, int maxPaths) { + public RandomPathFilter(Random random, String[] extensions, long maxPaths) { this.random = random; this.extensions = extensions; this.maxPaths = maxPaths; diff --git a/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/BaseImageLoader.java b/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/BaseImageLoader.java index 9f6be773b1..28bd4e2244 100644 --- a/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/BaseImageLoader.java +++ b/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/BaseImageLoader.java @@ -43,9 +43,9 @@ public abstract class BaseImageLoader implements Serializable { public static final String[] ALLOWED_FORMATS = {"tif", "jpg", "png", "jpeg", "bmp", "JPEG", "JPG", "TIF", "PNG"}; protected Random rng = new Random(System.currentTimeMillis()); - protected int height = -1; - protected int width = -1; - protected int channels = -1; + protected long height = -1; + protected long width = -1; + protected long channels = -1; protected boolean centerCropIfNeeded = false; protected ImageTransform imageTransform = null; protected NativeImageLoader.MultiPageMode multiPageMode = null; diff --git a/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/ImageLoader.java b/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/ImageLoader.java index d00816c9a4..89c99224ea 100644 --- a/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/ImageLoader.java +++ b/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/ImageLoader.java @@ -65,7 +65,7 @@ public class ImageLoader extends BaseImageLoader { * @param width the width to load */ - public ImageLoader(int height, int width) { + public ImageLoader(long height, long width) { super(); this.height = height; this.width = width; @@ -79,7 +79,7 @@ public class ImageLoader extends BaseImageLoader { * @param width the width to load * @param channels the number of channels for the image* */ - public ImageLoader(int height, int width, int channels) { + public ImageLoader(long height, long width, long channels) { super(); this.height = height; this.width = width; @@ -94,7 +94,7 @@ public class ImageLoader extends BaseImageLoader { * @param channels the number of channels for the image* * @param centerCropIfNeeded to crop before rescaling and converting */ - public ImageLoader(int height, int width, int channels, boolean centerCropIfNeeded) { + public ImageLoader(long height, long width, long channels, boolean centerCropIfNeeded) { this(height, width, channels); this.centerCropIfNeeded = centerCropIfNeeded; } @@ -349,7 +349,9 @@ public class ImageLoader extends BaseImageLoader { int w = image.getWidth(), h = image.getHeight(); int bands = image.getSampleModel().getNumBands(); - int[][][] ret = new int[channels][h][w]; + int[][][] ret = new int[(int)Math.min(channels, Integer.MAX_VALUE)] + [(int)Math.min(h, Integer.MAX_VALUE)] + [(int)Math.min(w, Integer.MAX_VALUE)]; byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); for (int i = 0; i < h; i++) { @@ -357,7 +359,7 @@ public class ImageLoader extends BaseImageLoader { for (int k = 0; k < channels; k++) { if (k >= bands) break; - ret[k][i][j] = pixels[channels * w * i + channels * j + k]; + ret[k][i][j] = pixels[(int)Math.min(channels * w * i + channels * j + k, Integer.MAX_VALUE)]; } } } diff --git a/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/LFWLoader.java b/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/LFWLoader.java index 9b5b5d1a4a..1e08a43d50 100644 --- a/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/LFWLoader.java +++ b/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/LFWLoader.java @@ -83,13 +83,17 @@ public class LFWLoader extends BaseImageLoader implements Serializable { } public LFWLoader(boolean useSubset) { - this(new int[] {HEIGHT, WIDTH, CHANNELS,}, null, useSubset); + this(new long[] {HEIGHT, WIDTH, CHANNELS,}, null, useSubset); } public LFWLoader(int[] imgDim, boolean useSubset) { this(imgDim, null, useSubset); } + public LFWLoader(long[] imgDim, boolean useSubset) { + this(imgDim, null, useSubset); + } + public LFWLoader(int[] imgDim, ImageTransform imgTransform, boolean useSubset) { this.height = imgDim[0]; this.width = imgDim[1]; @@ -101,6 +105,17 @@ public class LFWLoader extends BaseImageLoader implements Serializable { generateLfwMaps(); } + public LFWLoader(long[] imgDim, ImageTransform imgTransform, boolean useSubset) { + this.height = imgDim[0]; + this.width = imgDim[1]; + this.channels = imgDim[2]; + this.imageTransform = imgTransform; + this.useSubset = useSubset; + this.localDir = useSubset ? localSubDir : localDir; + this.fullDir = new File(BASE_DIR, localDir); + generateLfwMaps(); + } + public void generateLfwMaps() { if (useSubset) { // Subset of just faces with a name starting with A @@ -124,7 +139,7 @@ public class LFWLoader extends BaseImageLoader implements Serializable { load(NUM_IMAGES, NUM_IMAGES, NUM_LABELS, LABEL_PATTERN, 1, rng); } - public void load(int batchSize, int numExamples, int numLabels, PathLabelGenerator labelGenerator, + public void load(long batchSize, long numExamples, long numLabels, PathLabelGenerator labelGenerator, double splitTrainTest, Random rng) { if (!imageFilesExist()) { if (!fullDir.exists() || fullDir.listFiles() == null || fullDir.listFiles().length == 0) { @@ -163,42 +178,69 @@ public class LFWLoader extends BaseImageLoader implements Serializable { } - public RecordReader getRecordReader(int numExamples) { - return getRecordReader(numExamples, numExamples, new int[] {height, width, channels}, + public RecordReader getRecordReader(long numExamples) { + return getRecordReader(numExamples, numExamples, new long[] {height, width, channels}, useSubset ? SUB_NUM_LABELS : NUM_LABELS, LABEL_PATTERN, true, 1, new Random(System.currentTimeMillis())); } - public RecordReader getRecordReader(int batchSize, int numExamples, int numLabels, Random rng) { - return getRecordReader(numExamples, batchSize, new int[] {height, width, channels}, numLabels, LABEL_PATTERN, + public RecordReader getRecordReader(long batchSize, long numExamples, long numLabels, Random rng) { + return getRecordReader(numExamples, batchSize, new long[] {height, width, channels}, numLabels, LABEL_PATTERN, true, 1, rng); } - public RecordReader getRecordReader(int batchSize, int numExamples, boolean train, double splitTrainTest) { - return getRecordReader(numExamples, batchSize, new int[] {height, width, channels}, + public RecordReader getRecordReader(long batchSize, long numExamples, boolean train, double splitTrainTest) { + return getRecordReader(numExamples, batchSize, new long[] {height, width, channels}, useSubset ? SUB_NUM_LABELS : NUM_LABELS, LABEL_PATTERN, train, splitTrainTest, new Random(System.currentTimeMillis())); } - public RecordReader getRecordReader(int batchSize, int numExamples, int[] imgDim, boolean train, + public RecordReader getRecordReader(long batchSize, long numExamples, int[] imgDim, boolean train, double splitTrainTest, Random rng) { return getRecordReader(numExamples, batchSize, imgDim, useSubset ? SUB_NUM_LABELS : NUM_LABELS, LABEL_PATTERN, train, splitTrainTest, rng); } - public RecordReader getRecordReader(int batchSize, int numExamples, PathLabelGenerator labelGenerator, + public RecordReader getRecordReader(long batchSize, long numExamples, long[] imgDim, boolean train, + double splitTrainTest, Random rng) { + return getRecordReader(numExamples, batchSize, imgDim, useSubset ? SUB_NUM_LABELS : NUM_LABELS, LABEL_PATTERN, + train, splitTrainTest, rng); + } + + public RecordReader getRecordReader(long batchSize, long numExamples, PathLabelGenerator labelGenerator, boolean train, double splitTrainTest, Random rng) { - return getRecordReader(numExamples, batchSize, new int[] {height, width, channels}, + return getRecordReader(numExamples, batchSize, new long[] {height, width, channels}, useSubset ? SUB_NUM_LABELS : NUM_LABELS, labelGenerator, train, splitTrainTest, rng); } - public RecordReader getRecordReader(int batchSize, int numExamples, int[] imgDim, PathLabelGenerator labelGenerator, + public RecordReader getRecordReader(long batchSize, long numExamples, int[] imgDim, PathLabelGenerator labelGenerator, boolean train, double splitTrainTest, Random rng) { return getRecordReader(numExamples, batchSize, imgDim, useSubset ? SUB_NUM_LABELS : NUM_LABELS, labelGenerator, train, splitTrainTest, rng); } - public RecordReader getRecordReader(int batchSize, int numExamples, int[] imgDim, int numLabels, + public RecordReader getRecordReader(long batchSize, long numExamples, long[] imgDim, PathLabelGenerator labelGenerator, + boolean train, double splitTrainTest, Random rng) { + return getRecordReader(numExamples, batchSize, imgDim, useSubset ? SUB_NUM_LABELS : NUM_LABELS, labelGenerator, + train, splitTrainTest, rng); + } + + public RecordReader getRecordReader(long batchSize, long numExamples, int[] imgDim, long numLabels, + PathLabelGenerator labelGenerator, boolean train, double splitTrainTest, Random rng) { + load(batchSize, numExamples, numLabels, labelGenerator, splitTrainTest, rng); + RecordReader recordReader = + new ImageRecordReader(imgDim[0], imgDim[1], imgDim[2], labelGenerator, imageTransform); + + try { + InputSplit data = train ? inputSplit[0] : inputSplit[1]; + recordReader.initialize(data); + } catch (IOException | InterruptedException e) { + e.printStackTrace(); + } + return recordReader; + } + + public RecordReader getRecordReader(long batchSize, long numExamples, long[] imgDim, long numLabels, PathLabelGenerator labelGenerator, boolean train, double splitTrainTest, Random rng) { load(batchSize, numExamples, numLabels, labelGenerator, splitTrainTest, rng); RecordReader recordReader = diff --git a/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/NativeImageLoader.java b/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/NativeImageLoader.java index fb3608f989..09e265201f 100644 --- a/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/NativeImageLoader.java +++ b/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/NativeImageLoader.java @@ -46,7 +46,7 @@ import static org.bytedeco.javacpp.opencv_imgproc.*; * @author saudet */ public class NativeImageLoader extends BaseImageLoader { - private static final int MIN_BUFFER_STEP_SIZE = 1024*1024; + private static final int MIN_BUFFER_STEP_SIZE = 64 * 1024; private byte[] buffer = null; private Mat bufferMat = null; @@ -72,7 +72,7 @@ public class NativeImageLoader extends BaseImageLoader { * @param width the width to load */ - public NativeImageLoader(int height, int width) { + public NativeImageLoader(long height, long width) { this.height = height; this.width = width; } @@ -85,7 +85,7 @@ public class NativeImageLoader extends BaseImageLoader { * @param width the width to load * @param channels the number of channels for the image* */ - public NativeImageLoader(int height, int width, int channels) { + public NativeImageLoader(long height, long width, long channels) { this.height = height; this.width = width; this.channels = channels; @@ -99,7 +99,7 @@ public class NativeImageLoader extends BaseImageLoader { * @param channels the number of channels for the image* * @param centerCropIfNeeded to crop before rescaling and converting */ - public NativeImageLoader(int height, int width, int channels, boolean centerCropIfNeeded) { + public NativeImageLoader(long height, long width, long channels, boolean centerCropIfNeeded) { this(height, width, channels); this.centerCropIfNeeded = centerCropIfNeeded; } @@ -112,7 +112,7 @@ public class NativeImageLoader extends BaseImageLoader { * @param channels the number of channels for the image* * @param imageTransform to use before rescaling and converting */ - public NativeImageLoader(int height, int width, int channels, ImageTransform imageTransform) { + public NativeImageLoader(long height, long width, long channels, ImageTransform imageTransform) { this(height, width, channels); this.imageTransform = imageTransform; } @@ -125,7 +125,7 @@ public class NativeImageLoader extends BaseImageLoader { * @param channels the number of channels for the image* * @param mode how to load multipage image */ - public NativeImageLoader(int height, int width, int channels, MultiPageMode mode) { + public NativeImageLoader(long height, long width, long channels, MultiPageMode mode) { this(height, width, channels); this.multiPageMode = mode; } @@ -347,9 +347,9 @@ public class NativeImageLoader extends BaseImageLoader { protected void fillNDArray(Mat image, INDArray ret) { - int rows = image.rows(); - int cols = image.cols(); - int channels = image.channels(); + long rows = image.rows(); + long cols = image.cols(); + long channels = image.channels(); if (ret.lengthLong() != rows * cols * channels) { throw new ND4JIllegalStateException("INDArray provided to store image not equal to image: {channels: " @@ -369,9 +369,9 @@ public class NativeImageLoader extends BaseImageLoader { new long[] {channels, rows, cols}, new long[] {stride[0], stride[1], stride[2]}, direct); if (idx instanceof UByteIndexer) { UByteIndexer ubyteidx = (UByteIndexer) idx; - for (int k = 0; k < channels; k++) { - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { + for (long k = 0; k < channels; k++) { + for (long i = 0; i < rows; i++) { + for (long j = 0; j < cols; j++) { retidx.put(k, i, j, ubyteidx.get(i, j, k)); } } @@ -379,9 +379,9 @@ public class NativeImageLoader extends BaseImageLoader { done = true; } else if (idx instanceof UShortIndexer) { UShortIndexer ushortidx = (UShortIndexer) idx; - for (int k = 0; k < channels; k++) { - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { + for (long k = 0; k < channels; k++) { + for (long i = 0; i < rows; i++) { + for (long j = 0; j < cols; j++) { retidx.put(k, i, j, ushortidx.get(i, j, k)); } } @@ -389,9 +389,9 @@ public class NativeImageLoader extends BaseImageLoader { done = true; } else if (idx instanceof IntIndexer) { IntIndexer intidx = (IntIndexer) idx; - for (int k = 0; k < channels; k++) { - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { + for (long k = 0; k < channels; k++) { + for (long i = 0; i < rows; i++) { + for (long j = 0; j < cols; j++) { retidx.put(k, i, j, intidx.get(i, j, k)); } } @@ -399,9 +399,9 @@ public class NativeImageLoader extends BaseImageLoader { done = true; } else if (idx instanceof FloatIndexer) { FloatIndexer floatidx = (FloatIndexer) idx; - for (int k = 0; k < channels; k++) { - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { + for (long k = 0; k < channels; k++) { + for (long i = 0; i < rows; i++) { + for (long j = 0; j < cols; j++) { retidx.put(k, i, j, floatidx.get(i, j, k)); } } @@ -413,9 +413,9 @@ public class NativeImageLoader extends BaseImageLoader { new long[] {channels, rows, cols}, new long[] {stride[0], stride[1], stride[2]}, direct); if (idx instanceof UByteIndexer) { UByteIndexer ubyteidx = (UByteIndexer) idx; - for (int k = 0; k < channels; k++) { - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { + for (long k = 0; k < channels; k++) { + for (long i = 0; i < rows; i++) { + for (long j = 0; j < cols; j++) { retidx.put(k, i, j, ubyteidx.get(i, j, k)); } } @@ -423,9 +423,9 @@ public class NativeImageLoader extends BaseImageLoader { done = true; } else if (idx instanceof UShortIndexer) { UShortIndexer ushortidx = (UShortIndexer) idx; - for (int k = 0; k < channels; k++) { - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { + for (long k = 0; k < channels; k++) { + for (long i = 0; i < rows; i++) { + for (long j = 0; j < cols; j++) { retidx.put(k, i, j, ushortidx.get(i, j, k)); } } @@ -433,9 +433,9 @@ public class NativeImageLoader extends BaseImageLoader { done = true; } else if (idx instanceof IntIndexer) { IntIndexer intidx = (IntIndexer) idx; - for (int k = 0; k < channels; k++) { - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { + for (long k = 0; k < channels; k++) { + for (long i = 0; i < rows; i++) { + for (long j = 0; j < cols; j++) { retidx.put(k, i, j, intidx.get(i, j, k)); } } @@ -443,9 +443,9 @@ public class NativeImageLoader extends BaseImageLoader { done = true; } else if (idx instanceof FloatIndexer) { FloatIndexer floatidx = (FloatIndexer) idx; - for (int k = 0; k < channels; k++) { - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { + for (long k = 0; k < channels; k++) { + for (long i = 0; i < rows; i++) { + for (long j = 0; j < cols; j++) { retidx.put(k, i, j, floatidx.get(i, j, k)); } } @@ -456,9 +456,9 @@ public class NativeImageLoader extends BaseImageLoader { if (!done) { - for (int k = 0; k < channels; k++) { - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { + for (long k = 0; k < channels; k++) { + for (long i = 0; i < rows; i++) { + for (long j = 0; j < cols; j++) { if (channels > 1) { ret.putScalar(k, i, j, idx.getDouble(i, j, k)); } else { @@ -522,7 +522,7 @@ public class NativeImageLoader extends BaseImageLoader { int code = -1; switch (image.channels()) { case 1: - switch (channels) { + switch ((int)channels) { case 3: code = CV_GRAY2BGR; break; @@ -532,7 +532,7 @@ public class NativeImageLoader extends BaseImageLoader { } break; case 3: - switch (channels) { + switch ((int)channels) { case 1: code = CV_BGR2GRAY; break; @@ -542,7 +542,7 @@ public class NativeImageLoader extends BaseImageLoader { } break; case 4: - switch (channels) { + switch ((int)channels) { case 1: code = CV_RGBA2GRAY; break; @@ -617,10 +617,12 @@ public class NativeImageLoader extends BaseImageLoader { return scalingIfNeed(image, height, width); } - protected Mat scalingIfNeed(Mat image, int dstHeight, int dstWidth) { + protected Mat scalingIfNeed(Mat image, long dstHeight, long dstWidth) { Mat scaled = image; if (dstHeight > 0 && dstWidth > 0 && (image.rows() != dstHeight || image.cols() != dstWidth)) { - resize(image, scaled = new Mat(), new Size(dstWidth, dstHeight)); + resize(image, scaled = new Mat(), new Size( + (int)Math.min(dstWidth, Integer.MAX_VALUE), + (int)Math.min(dstHeight, Integer.MAX_VALUE))); } return scaled; } @@ -708,7 +710,8 @@ public class NativeImageLoader extends BaseImageLoader { if (dataType < 0) { dataType = pointer instanceof DoublePointer ? CV_64F : CV_32F; } - Mat mat = new Mat(rows, cols, CV_MAKETYPE(dataType, (int) channels)); + Mat mat = new Mat((int)Math.min(rows, Integer.MAX_VALUE), (int)Math.min(cols, Integer.MAX_VALUE), + CV_MAKETYPE(dataType, (int)Math.min(channels, Integer.MAX_VALUE))); boolean direct = !Loader.getPlatform().startsWith("android"); Indexer matidx = mat.createIndexer(direct); @@ -718,9 +721,9 @@ public class NativeImageLoader extends BaseImageLoader { FloatIndexer ptridx = FloatIndexer.create((FloatPointer)pointer, new long[] {channels, rows, cols}, new long[] {stride[rank == 3 ? 0 : 1], stride[rank == 3 ? 1 : 2], stride[rank == 3 ? 2 : 3]}, direct); FloatIndexer idx = (FloatIndexer)matidx; - for (int k = 0; k < channels; k++) { - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { + for (long k = 0; k < channels; k++) { + for (long i = 0; i < rows; i++) { + for (long j = 0; j < cols; j++) { idx.put(i, j, k, ptridx.get(k, i, j)); } } @@ -730,9 +733,9 @@ public class NativeImageLoader extends BaseImageLoader { DoubleIndexer ptridx = DoubleIndexer.create((DoublePointer)pointer, new long[] {channels, rows, cols}, new long[] {stride[rank == 3 ? 0 : 1], stride[rank == 3 ? 1 : 2], stride[rank == 3 ? 2 : 3]}, direct); DoubleIndexer idx = (DoubleIndexer)matidx; - for (int k = 0; k < channels; k++) { - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { + for (long k = 0; k < channels; k++) { + for (long i = 0; i < rows; i++) { + for (long j = 0; j < cols; j++) { idx.put(i, j, k, ptridx.get(k, i, j)); } } @@ -741,9 +744,9 @@ public class NativeImageLoader extends BaseImageLoader { } if (!done) { - for (int k = 0; k < channels; k++) { - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { + for (long k = 0; k < channels; k++) { + for (long i = 0; i < rows; i++) { + for (long j = 0; j < cols; j++) { if (rank == 3) { matidx.putDouble(new long[] {i, j, k}, array.getDouble(k, i, j)); } else { @@ -764,7 +767,7 @@ public class NativeImageLoader extends BaseImageLoader { * @return INDArray * @throws IOException */ - private INDArray asMatrix(BytePointer bytes, int length) throws IOException { + private INDArray asMatrix(BytePointer bytes, long length) throws IOException { PIXA pixa; pixa = pixaReadMemMultipageTiff(bytes, length); INDArray data; diff --git a/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/recordreader/BaseImageRecordReader.java b/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/recordreader/BaseImageRecordReader.java index 4da2ec5477..383ef3e3fd 100644 --- a/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/recordreader/BaseImageRecordReader.java +++ b/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/recordreader/BaseImageRecordReader.java @@ -67,7 +67,7 @@ public abstract class BaseImageRecordReader extends BaseRecordReader { protected boolean writeLabel = false; protected List<Writable> record; protected boolean hitImage = false; - protected int height = 28, width = 28, channels = 1; + protected long height = 28, width = 28, channels = 1; protected boolean cropImage = false; protected ImageTransform imageTransform; protected BaseImageLoader imageLoader; @@ -86,20 +86,20 @@ public abstract class BaseImageRecordReader extends BaseRecordReader { public BaseImageRecordReader() {} - public BaseImageRecordReader(int height, int width, int channels, PathLabelGenerator labelGenerator) { + public BaseImageRecordReader(long height, long width, long channels, PathLabelGenerator labelGenerator) { this(height, width, channels, labelGenerator, null); } - public BaseImageRecordReader(int height, int width, int channels, PathMultiLabelGenerator labelGenerator) { + public BaseImageRecordReader(long height, long width, long channels, PathMultiLabelGenerator labelGenerator) { this(height, width, channels, null, labelGenerator,null); } - public BaseImageRecordReader(int height, int width, int channels, PathLabelGenerator labelGenerator, + public BaseImageRecordReader(long height, long width, long channels, PathLabelGenerator labelGenerator, ImageTransform imageTransform) { this(height, width, channels, labelGenerator, null, imageTransform); } - protected BaseImageRecordReader(int height, int width, int channels, PathLabelGenerator labelGenerator, + protected BaseImageRecordReader(long height, long width, long channels, PathLabelGenerator labelGenerator, PathMultiLabelGenerator labelMultiGenerator, ImageTransform imageTransform) { this.height = height; this.width = width; @@ -173,9 +173,9 @@ public abstract class BaseImageRecordReader extends BaseRecordReader { public void initialize(Configuration conf, InputSplit split) throws IOException, InterruptedException { this.appendLabel = conf.getBoolean(APPEND_LABEL, appendLabel); this.labels = new ArrayList<>(conf.getStringCollection(LABELS)); - this.height = conf.getInt(HEIGHT, height); - this.width = conf.getInt(WIDTH, width); - this.channels = conf.getInt(CHANNELS, channels); + this.height = conf.getLong(HEIGHT, height); + this.width = conf.getLong(WIDTH, width); + this.channels = conf.getLong(CHANNELS, channels); this.cropImage = conf.getBoolean(CROP_IMAGE, cropImage); if ("imageio".equals(conf.get(IMAGE_LOADER))) { this.imageLoader = new ImageLoader(height, width, channels, cropImage); @@ -327,7 +327,7 @@ public abstract class BaseImageRecordReader extends BaseRecordReader { cnt++; } - INDArray features = Nd4j.createUninitialized(new int[] {cnt, channels, height, width}, 'c'); + INDArray features = Nd4j.createUninitialized(new long[] {cnt, channels, height, width}, 'c'); Nd4j.getAffinityManager().tagLocation(features, AffinityManager.Location.HOST); for (int i = 0; i < cnt; i++) { try { diff --git a/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/recordreader/ImageRecordReader.java b/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/recordreader/ImageRecordReader.java index 0855f04cfa..7195ea4790 100644 --- a/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/recordreader/ImageRecordReader.java +++ b/datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/recordreader/ImageRecordReader.java @@ -40,38 +40,38 @@ public class ImageRecordReader extends BaseImageRecordReader { } /** Loads images with given height, width, and channels, appending labels returned by the generator. */ - public ImageRecordReader(int height, int width, int channels, PathLabelGenerator labelGenerator) { + public ImageRecordReader(long height, long width, long channels, PathLabelGenerator labelGenerator) { super(height, width, channels, labelGenerator); } /** Loads images with given height, width, and channels, appending labels returned by the generator. */ - public ImageRecordReader(int height, int width, int channels, PathMultiLabelGenerator labelGenerator) { + public ImageRecordReader(long height, long width, long channels, PathMultiLabelGenerator labelGenerator) { super(height, width, channels, labelGenerator); } /** Loads images with given height, width, and channels, appending no labels. */ - public ImageRecordReader(int height, int width, int channels) { + public ImageRecordReader(long height, long width, long channels) { super(height, width, channels, (PathLabelGenerator) null); } /** Loads images with given height, width, and channels, appending labels returned by the generator. */ - public ImageRecordReader(int height, int width, int channels, PathLabelGenerator labelGenerator, + public ImageRecordReader(long height, long width, long channels, PathLabelGenerator labelGenerator, ImageTransform imageTransform) { super(height, width, channels, labelGenerator, imageTransform); } /** Loads images with given height, width, and channels, appending no labels. */ - public ImageRecordReader(int height, int width, int channels, ImageTransform imageTransform) { + public ImageRecordReader(long height, long width, long channels, ImageTransform imageTransform) { super(height, width, channels, null, imageTransform); } /** Loads images with given height, width, and channels, appending labels returned by the generator. */ - public ImageRecordReader(int height, int width, PathLabelGenerator labelGenerator) { + public ImageRecordReader(long height, long width, PathLabelGenerator labelGenerator) { super(height, width, 1, labelGenerator); } /** Loads images with given height, width, and channels = 1, appending no labels. */ - public ImageRecordReader(int height, int width) { + public ImageRecordReader(long height, long width) { super(height, width, 1, null, null); } diff --git a/datavec/datavec-data/datavec-data-image/src/test/java/org/datavec/image/loader/LoaderTests.java b/datavec/datavec-data/datavec-data-image/src/test/java/org/datavec/image/loader/LoaderTests.java index d78e356bcb..28791810d0 100644 --- a/datavec/datavec-data/datavec-data-image/src/test/java/org/datavec/image/loader/LoaderTests.java +++ b/datavec/datavec-data/datavec-data-image/src/test/java/org/datavec/image/loader/LoaderTests.java @@ -56,7 +56,7 @@ public class LoaderTests { rr.initialize(inputSplit[0]); List<String> exptedLabel = rr.getLabels(); - RecordReader rr2 = new LFWLoader(new int[] {250, 250, 3}, true).getRecordReader(1, 1, 1, new Random(42)); + RecordReader rr2 = new LFWLoader(new long[] {250, 250, 3}, true).getRecordReader(1, 1, 1, new Random(42)); assertEquals(exptedLabel.get(0), rr2.getLabels().get(0)); } diff --git a/datavec/datavec-data/datavec-data-image/src/test/java/org/datavec/image/loader/TestNativeImageLoader.java b/datavec/datavec-data/datavec-data-image/src/test/java/org/datavec/image/loader/TestNativeImageLoader.java index 6a161f83ab..a81728d526 100644 --- a/datavec/datavec-data/datavec-data-image/src/test/java/org/datavec/image/loader/TestNativeImageLoader.java +++ b/datavec/datavec-data/datavec-data-image/src/test/java/org/datavec/image/loader/TestNativeImageLoader.java @@ -121,7 +121,7 @@ public class TestNativeImageLoader { assertEquals(w4, array6.size(3)); int ch5 = 4, pages1 = 1; - NativeImageLoader loader6 = new NativeImageLoader(h4, w4, ch5, NativeImageLoader.MultiPageMode.CHANNELS); + NativeImageLoader loader6 = new NativeImageLoader(h4, w4, 1, NativeImageLoader.MultiPageMode.CHANNELS); INDArray array7 = null; try { array7 = loader6.asMatrix( @@ -249,6 +249,14 @@ public class TestNativeImageLoader { Java2DNativeImageLoader loader4 = new Java2DNativeImageLoader(); BufferedImage img12 = loader4.asBufferedImage(array1); assertEquals(array1, loader4.asMatrix(img12)); + + NativeImageLoader loader5 = new NativeImageLoader(0, 0, 0); + INDArray array7 = loader5.asMatrix(f3); + assertEquals(4, array7.rank()); + assertEquals(1, array7.size(0)); + assertEquals(3, array7.size(1)); + assertEquals(32, array7.size(2)); + assertEquals(32, array7.size(3)); } @Test
['datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/LFWLoader.java', 'datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/BaseImageLoader.java', 'datavec/datavec-data/datavec-data-image/src/test/java/org/datavec/image/loader/TestNativeImageLoader.java', 'datavec/datavec-api/src/main/java/org/datavec/api/io/filters/BalancedPathFilter.java', 'datavec/datavec-data/datavec-data-image/src/test/java/org/datavec/image/loader/LoaderTests.java', 'datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/ImageLoader.java', 'datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/recordreader/ImageRecordReader.java', 'datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/loader/NativeImageLoader.java', 'datavec/datavec-data/datavec-data-image/src/main/java/org/datavec/image/recordreader/BaseImageRecordReader.java', 'datavec/datavec-api/src/main/java/org/datavec/api/io/filters/RandomPathFilter.java']
{'.java': 10}
10
10
0
0
10
21,996,612
4,852,416
596,661
3,654
16,775
3,878
252
8
643
35
159
12
0
1
1970-01-01T00:25:27
13,099
Java
{'Java': 42895752, 'C++': 17237193, 'Cuda': 2203734, 'Kotlin': 2030453, 'JavaScript': 296767, 'C': 172853, 'CMake': 126415, 'Shell': 96643, 'TypeScript': 81217, 'Python': 77566, 'FreeMarker': 77257, 'HTML': 18609, 'CSS': 12974, 'PureBasic': 12254, 'Cython': 12094, 'Ruby': 4558, 'Batchfile': 1458, 'Scala': 1026, 'Smarty': 975, 'Starlark': 931}
Apache License 2.0
9,734
deeplearning4j/deeplearning4j/5079/4534
deeplearning4j
deeplearning4j
https://github.com/deeplearning4j/deeplearning4j/issues/4534
https://github.com/deeplearning4j/deeplearning4j/pull/5079
https://github.com/deeplearning4j/deeplearning4j/pull/5079
1
closes
Unet: Error importing model for training with Conv2D as last layer (0.9.2-SNAPSHOT)
#### Issue Description Hi so I have a model in keras that looks like this. ``` python def get_unet(): conv_params = dict(activation='relu', border_mode='same') merge_params = dict(mode='concat', concat_axis=1) inputs = Input((8, 256, 256)) conv1 = Convolution2D(32, 3, 3, **conv_params)(inputs) conv1 = Convolution2D(32, 3, 3, **conv_params)(conv1) pool1 = MaxPooling2D(pool_size=(2, 2))(conv1) conv2 = Convolution2D(64, 3, 3, **conv_params)(pool1) conv2 = Convolution2D(64, 3, 3, **conv_params)(conv2) pool2 = MaxPooling2D(pool_size=(2, 2))(conv2) conv3 = Convolution2D(128, 3, 3, **conv_params)(pool2) conv3 = Convolution2D(128, 3, 3, **conv_params)(conv3) pool3 = MaxPooling2D(pool_size=(2, 2))(conv3) conv4 = Convolution2D(256, 3, 3, **conv_params)(pool3) conv4 = Convolution2D(256, 3, 3, **conv_params)(conv4) pool4 = MaxPooling2D(pool_size=(2, 2))(conv4) conv5 = Convolution2D(512, 3, 3, **conv_params)(pool4) conv5 = Convolution2D(512, 3, 3, **conv_params)(conv5) up6 = merge_l([UpSampling2D(size=(2, 2))(conv5), conv4], **merge_params) conv6 = Convolution2D(256, 3, 3, **conv_params)(up6) conv6 = Convolution2D(256, 3, 3, **conv_params)(conv6) up7 = merge_l([UpSampling2D(size=(2, 2))(conv6), conv3], **merge_params) conv7 = Convolution2D(128, 3, 3, **conv_params)(up7) conv7 = Convolution2D(128, 3, 3, **conv_params)(conv7) up8 = merge_l([UpSampling2D(size=(2, 2))(conv7), conv2], **merge_params) conv8 = Convolution2D(64, 3, 3, **conv_params)(up8) conv8 = Convolution2D(64, 3, 3, **conv_params)(conv8) up9 = merge_l([UpSampling2D(size=(2, 2))(conv8), conv1], **merge_params) conv9 = Convolution2D(32, 3, 3, **conv_params)(up9) conv9 = Convolution2D(32, 3, 3, **conv_params)(conv9) conv10 = Convolution2D(1, 1, 1, activation='sigmoid')(conv9) optimizer = SGD(lr=0.01, momentum=0.9, nesterov=True) model = Model(input=inputs, output=conv10) model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy', jaccard_coef, jaccard_coef_int]) return model ``` And saved like this ``` python model = get_unet() #train model on lots of images.... model.save('unet.h5') ``` I would like to try loading this trained model into dl4j. I tried to do this with ``` scala val unet = KerasModelImport.importKerasModelAndWeights("src/main/resources/unet.h5") ``` However I got the following error: ``` Exception in thread "main" java.lang.IllegalStateException: Invalid input type (layer index = -1, layer name="convolution2d_19_loss"): expected FeedForward input type. Got: InputTypeConvolutional(h=256,w=256,d=1) ``` Any ideas? This model works as expected in keras. I had to use the snapshot build so that the merge layers will work in dl4j. Not sure why it doesn't like that the first layer is convolutional. keras==1.0.0 theano==0.9.0 inside keras.json ``` { "image_dim_ordering": "th", "epsilon": 1e-07, "floatx": "float32", "backend": "theano" } ```
c533a2d61d253f917af48b38c7161fa926ff9d26
1b9b2a54a3cdce9276a9d86a6822680f392d0119
https://github.com/deeplearning4j/deeplearning4j/compare/c533a2d61d253f917af48b38c7161fa926ff9d26...1b9b2a54a3cdce9276a9d86a6822680f392d0119
diff --git a/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/KerasModel.java b/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/KerasModel.java index c11dd47493..1b23683f2f 100644 --- a/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/KerasModel.java +++ b/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/KerasModel.java @@ -322,17 +322,10 @@ public class KerasModel { if (preprocessor != null) preprocessors.put(layer.getLayerName(), preprocessor); graphBuilder.addLayer(layer.getLayerName(), layer.getLayer(), inboundLayerNamesArray); - if (this.outputLayerNames.contains(layer.getLayerName()) && !(layer.getLayer() instanceof IOutputLayer)) - log.warn("Model cannot be trained: output layer " + layer.getLayerName() - + " is not an IOutputLayer (no loss function specified)"); } else if (layer.isVertex()) { // Ignore "preprocessor" layers for now if (preprocessor != null) preprocessors.put(layer.getLayerName(), preprocessor); graphBuilder.addVertex(layer.getLayerName(), layer.getVertex(), inboundLayerNamesArray); - if (this.outputLayerNames.contains(layer.getLayerName()) - && !(layer.getVertex() instanceof IOutputLayer)) - log.warn("Model cannot be trained: output vertex " + layer.getLayerName() - + " is not an IOutputLayer (no loss function specified)"); } else if (layer.isInputPreProcessor()) { if (preprocessor == null) throw new UnsupportedKerasConfigurationException("Layer " + layer.getLayerName() @@ -340,10 +333,6 @@ public class KerasModel { graphBuilder.addVertex(layer.getLayerName(), new PreprocessorVertex(preprocessor), inboundLayerNamesArray); } - - if (this.outputLayerNames.contains(layer.getLayerName())) - log.warn("Model cannot be trained: output " + layer.getLayerName() - + " is not an IOutputLayer (no loss function specified)"); } graphBuilder.setInputPreProcessors(preprocessors); diff --git a/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/layers/KerasLoss.java b/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/layers/KerasLoss.java index 33884e2121..4e264de468 100644 --- a/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/layers/KerasLoss.java +++ b/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/layers/KerasLoss.java @@ -4,7 +4,10 @@ import lombok.Data; import lombok.EqualsAndHashCode; import lombok.extern.slf4j.Slf4j; import org.deeplearning4j.nn.conf.inputs.InputType; +import org.deeplearning4j.nn.conf.layers.CnnLossLayer; +import org.deeplearning4j.nn.conf.layers.FeedForwardLayer; import org.deeplearning4j.nn.conf.layers.LossLayer; +import org.deeplearning4j.nn.conf.layers.RnnLossLayer; import org.deeplearning4j.nn.modelimport.keras.KerasLayer; import org.deeplearning4j.nn.modelimport.keras.exceptions.InvalidKerasConfigurationException; import org.deeplearning4j.nn.modelimport.keras.exceptions.UnsupportedKerasConfigurationException; @@ -25,6 +28,8 @@ import static org.deeplearning4j.nn.modelimport.keras.utils.KerasLossUtils.mapLo public class KerasLoss extends KerasLayer { private final String KERAS_CLASS_NAME_LOSS = "Loss"; + private LossFunctions.LossFunction loss; + /** * Constructor from layer name and input shape. @@ -58,7 +63,6 @@ public class KerasLoss extends KerasLayer { this.dimOrder = DimOrder.NONE; this.inboundLayerNames = new ArrayList<>(); this.inboundLayerNames.add(inboundLayerName); - LossFunctions.LossFunction loss; try { loss = mapLossFunction(kerasLoss, conf); } catch (UnsupportedKerasConfigurationException e) { @@ -67,7 +71,6 @@ public class KerasLoss extends KerasLayer { log.warn("Unsupported Keras loss function. Replacing with MSE."); loss = LossFunctions.LossFunction.SQUARED_LOSS; } - this.layer = new LossLayer.Builder(loss).name(layerName).build(); } /** @@ -75,8 +78,20 @@ public class KerasLoss extends KerasLayer { * * @return LossLayer */ - public LossLayer getLossLayer() { - return (LossLayer) this.layer; + public FeedForwardLayer getLossLayer(InputType type) throws UnsupportedKerasConfigurationException { + if (type instanceof InputType.InputTypeFeedForward) { + this.layer = new LossLayer.Builder(loss).name(this.layerName).build(); + } + else if (type instanceof InputType.InputTypeRecurrent) { + this.layer = new RnnLossLayer.Builder(loss).name(this.layerName).build(); + } + else if (type instanceof InputType.InputTypeConvolutional) { + this.layer = new CnnLossLayer.Builder(loss).name(this.layerName).build(); + } else { + throw new UnsupportedKerasConfigurationException("Unsupported output layer type" + + "got : " + type.toString()); + } + return (FeedForwardLayer) this.layer; } /** @@ -87,10 +102,11 @@ public class KerasLoss extends KerasLayer { * @throws InvalidKerasConfigurationException Invalid Keras config */ @Override - public InputType getOutputType(InputType... inputType) throws InvalidKerasConfigurationException { + public InputType getOutputType(InputType... inputType) throws InvalidKerasConfigurationException, + UnsupportedKerasConfigurationException { if (inputType.length > 1) throw new InvalidKerasConfigurationException( "Keras Loss layer accepts only one input (received " + inputType.length + ")"); - return this.getLossLayer().getOutputType(-1, inputType[0]); + return this.getLossLayer(inputType[0]).getOutputType(-1, inputType[0]); } } diff --git a/deeplearning4j-modelimport/src/test/java/org/deeplearning4j/nn/modelimport/keras/e2e/KerasModelEndToEndTest.java b/deeplearning4j-modelimport/src/test/java/org/deeplearning4j/nn/modelimport/keras/e2e/KerasModelEndToEndTest.java index 68c8f89e49..8d0cf1d141 100644 --- a/deeplearning4j-modelimport/src/test/java/org/deeplearning4j/nn/modelimport/keras/e2e/KerasModelEndToEndTest.java +++ b/deeplearning4j-modelimport/src/test/java/org/deeplearning4j/nn/modelimport/keras/e2e/KerasModelEndToEndTest.java @@ -287,6 +287,15 @@ public class KerasModelEndToEndTest { importFunctionalModelH5Test("modelimport/keras/examples/reshape_to_rnn/reshape_model.h5"); } + /** + * U-Net + */ + @Test + public void importUnetTfKeras2() throws Exception { + importFunctionalModelH5Test( + "modelimport/keras/examples/unet/unet_keras_2_tf.h5", null, true); + } + /** * ResNet50 */ @@ -329,7 +338,8 @@ public class KerasModelEndToEndTest { @Ignore // Takes unreasonably long, but works public void importInception() throws Exception { - ComputationGraph graph = importFunctionalModelH5Test("modelimport/keras/examples/inception/inception_v3_complete.h5"); + ComputationGraph graph = importFunctionalModelH5Test( + "modelimport/keras/examples/inception/inception_v3_complete.h5"); INDArray input = Nd4j.ones(10, 3, 299, 299); graph.output(input); System.out.println(graph.summary()); @@ -343,23 +353,22 @@ public class KerasModelEndToEndTest { public void importXception() throws Exception { int[] inputShape = new int[]{299, 299, 3}; ComputationGraph graph = importFunctionalModelH5Test( - "modelimport/keras/examples/xception/xception_tf_keras_2.h5", inputShape); + "modelimport/keras/examples/xception/xception_tf_keras_2.h5", inputShape, false); } - private ComputationGraph importFunctionalModelH5Test(String modelPath) throws Exception { - return importFunctionalModelH5Test(modelPath, null); + return importFunctionalModelH5Test(modelPath, null, false); } - private ComputationGraph importFunctionalModelH5Test(String modelPath, int[] inputShape) throws Exception { + private ComputationGraph importFunctionalModelH5Test(String modelPath, int[] inputShape, boolean train) throws Exception { ClassPathResource modelResource = new ClassPathResource(modelPath, KerasModelEndToEndTest.class.getClassLoader()); File modelFile = File.createTempFile(TEMP_MODEL_FILENAME, H5_EXTENSION); Files.copy(modelResource.getInputStream(), modelFile.toPath(), StandardCopyOption.REPLACE_EXISTING); KerasModelBuilder builder = new KerasModel().modelBuilder().modelHdf5Filename(modelFile.getAbsolutePath()) - .enforceTrainingConfig(false); + .enforceTrainingConfig(train); if (inputShape != null) { builder.inputShape(inputShape); }
['deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/KerasModel.java', 'deeplearning4j-modelimport/src/test/java/org/deeplearning4j/nn/modelimport/keras/e2e/KerasModelEndToEndTest.java', 'deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/layers/KerasLoss.java']
{'.java': 3}
3
3
0
0
3
8,036,914
1,743,338
216,858
1,388
2,501
502
39
2
3,164
325
1,040
83
0
5
1970-01-01T00:25:25
13,099
Java
{'Java': 42895752, 'C++': 17237193, 'Cuda': 2203734, 'Kotlin': 2030453, 'JavaScript': 296767, 'C': 172853, 'CMake': 126415, 'Shell': 96643, 'TypeScript': 81217, 'Python': 77566, 'FreeMarker': 77257, 'HTML': 18609, 'CSS': 12974, 'PureBasic': 12254, 'Cython': 12094, 'Ruby': 4558, 'Batchfile': 1458, 'Scala': 1026, 'Smarty': 975, 'Starlark': 931}
Apache License 2.0
9,735
deeplearning4j/deeplearning4j/5078/5029
deeplearning4j
deeplearning4j
https://github.com/deeplearning4j/deeplearning4j/issues/5029
https://github.com/deeplearning4j/deeplearning4j/pull/5078
https://github.com/deeplearning4j/deeplearning4j/pull/5078
1
closes
Unable to load pre-trained weights on dl4j from keras
#### Issue Description I am trying to load pretrained wieghts from python on dl4j ComputationGraph org.deeplearning4j.nn.modelimport.keras.KerasModelImport.importKerasModelAndWeights(KerasModelImport.java:193) here is the error: HDF5-DIAG: Error detected in HDF5 (1.10.1) thread 0: #000: H5A.c line 436 in H5Aopen(): unable to load attribute info from object header for attribute: 'weight_names' major: Attribute minor: Unable to initialize object #001: H5Oattribute.c line 528 in H5O_attr_open_by_name(): can't locate attribute: 'weight_names' major: Attribute minor: Object not found #### Version Information * Deeplearning4j 1.0.0-alpha * MacOS Sierra * keras (2.1.4) * TF(1.3.0) * cpu #### Contributing // loading the model try{ model = KerasModelImport.importKerasModelAndWeights(model_json, model_weights); } catch (Exception e) { e.printStackTrace(); return null; }
3afd3f36940cb1d13cb34a6bfc98b70d86bb8bc5
677d6f5ec475b3f0506793c20f7fa2cf2309007f
https://github.com/deeplearning4j/deeplearning4j/compare/3afd3f36940cb1d13cb34a6bfc98b70d86bb8bc5...677d6f5ec475b3f0506793c20f7fa2cf2309007f
diff --git a/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/utils/KerasModelBuilder.java b/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/utils/KerasModelBuilder.java index 5fda8bd49a..ae0912b255 100644 --- a/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/utils/KerasModelBuilder.java +++ b/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/utils/KerasModelBuilder.java @@ -118,8 +118,13 @@ public class KerasModelBuilder implements Cloneable, Closeable { return this; } - public KerasModelBuilder weightsHdf5Filename(String weightsHdf5Filename) { + public KerasModelBuilder weightsHdf5Filename(String weightsHdf5Filename) + throws InvalidKerasConfigurationException { this.weightsArchive = new Hdf5Archive(weightsHdf5Filename); + this.weightsRoot = config.getTrainingWeightsRoot(); + if (!this.weightsArchive.hasAttribute(config.getTrainingModelConfigAttribute())) + throw new InvalidKerasConfigurationException( + "Model configuration attribute missing from " + weightsHdf5Filename + " archive."); return this; } @@ -143,7 +148,8 @@ public class KerasModelBuilder implements Cloneable, Closeable { return sequentialModel; } - @Override public void close() { + @Override + public void close() { if (trainingArchive != null && trainingArchive != weightsArchive) { trainingArchive.close(); trainingArchive = null;
['deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/utils/KerasModelBuilder.java']
{'.java': 1}
1
1
0
0
1
8,035,302
1,742,994
216,834
1,388
608
114
10
1
972
104
253
29
0
0
1970-01-01T00:25:25
13,099
Java
{'Java': 42895752, 'C++': 17237193, 'Cuda': 2203734, 'Kotlin': 2030453, 'JavaScript': 296767, 'C': 172853, 'CMake': 126415, 'Shell': 96643, 'TypeScript': 81217, 'Python': 77566, 'FreeMarker': 77257, 'HTML': 18609, 'CSS': 12974, 'PureBasic': 12254, 'Cython': 12094, 'Ruby': 4558, 'Batchfile': 1458, 'Scala': 1026, 'Smarty': 975, 'Starlark': 931}
Apache License 2.0
9,736
deeplearning4j/deeplearning4j/5042/5041
deeplearning4j
deeplearning4j
https://github.com/deeplearning4j/deeplearning4j/issues/5041
https://github.com/deeplearning4j/deeplearning4j/pull/5042
https://github.com/deeplearning4j/deeplearning4j/pull/5042
1
fix
Workspace exception in 1.0.0 snapshot
#### Issue Description Running the following method results in a Workspace exception being thrown: public static void main(String[] args) { final int[] inputShape = {1, 1, 4, 4}; final INDArray input = Nd4j.rand(inputShape); final INDArray label = Nd4j.create(new double[]{1}); final String inputName = "input"; final String outputName = "output"; ComputationGraphConfiguration graphConf = new NeuralNetConfiguration.Builder() .weightInit(WeightInit.RELU_UNIFORM) .activation(Activation.IDENTITY) // Will be set later on .optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT) .updater(new Nesterovs(0.01, 0.9)) .trainingWorkspaceMode(WorkspaceMode.ENABLED) .inferenceWorkspaceMode(WorkspaceMode.ENABLED) .graphBuilder() .addInputs(inputName) .backprop(true) .pretrain(false) .setInputTypes(InputType.convolutional(inputShape[3], inputShape[2], inputShape[1])) .layer("conv", new ConvolutionLayer.Builder(3,3) .nIn(1) .nOut(1) .build(), inputName) .addVertex("mv", new MergeVertex(), "conv") .addVertex("add", new ElementWiseVertex(ElementWiseVertex.Op.Add), "mv", "conv") .layer("gp", new GlobalPoolingLayer.Builder().build(), "add") .layer(outputName, new CenterLossOutputLayer.Builder() .lossFunction(new LossMCXENT()) .nOut(label.length()) .build(), "gp") .setOutputs(outputName) .build(); final ComputationGraph graph = new ComputationGraph(graphConf); graph.init(); graph.fit(new INDArray[] {input}, new INDArray[] {label}); } Exception thrown: Exception in thread "main" java.lang.IllegalStateException: Backprop: array (ACTIVATION_GRAD) workspace validation failed (vertex mv - class: MergeVertex) - array is defined in incorrect workspace at org.deeplearning4j.nn.graph.ComputationGraph.validateArrayWorkspaces(ComputationGraph.java:1603) at org.deeplearning4j.nn.graph.ComputationGraph.calcBackpropGradients(ComputationGraph.java:2319) at org.deeplearning4j.nn.graph.ComputationGraph.computeGradientAndScore(ComputationGraph.java:1218) at org.deeplearning4j.nn.graph.ComputationGraph.computeGradientAndScore(ComputationGraph.java:1179) at org.deeplearning4j.optimize.solvers.BaseOptimizer.gradientAndScore(BaseOptimizer.java:178) at org.deeplearning4j.optimize.solvers.StochasticGradientDescent.optimize(StochasticGradientDescent.java:60) at org.deeplearning4j.optimize.Solver.optimize(Solver.java:54) at org.deeplearning4j.nn.graph.ComputationGraph.fit(ComputationGraph.java:1052) at org.deeplearning4j.nn.graph.ComputationGraph.fit(ComputationGraph.java:998) at ampControl.model.training.model.layerblocks.graph.WorkspaceException.main(WorkspaceException.java:63) Caused by: org.nd4j.linalg.workspace.ND4JWorkspaceException: Array workspace validation failed: Array of type ACTIVATION_GRAD should be in workspace "WS_LAYER_ACT_1" but is in workspace "WS_LAYER_ACT_0" at org.nd4j.linalg.workspace.BaseWorkspaceMgr.validateArrayLocation(BaseWorkspaceMgr.java:221) at org.deeplearning4j.nn.workspace.LayerWorkspaceMgr.validateArrayLocation(LayerWorkspaceMgr.java:66) at org.deeplearning4j.nn.graph.ComputationGraph.validateArrayWorkspaces(ComputationGraph.java:1594) ... 9 more #### Version Information Please indicate relevant versions, including, if relevant: * Deeplearning4j version : 1.0.0 snapshot (pom refreshed ~1 hour before post in case it matters). * platform information: Windows 10 * CUDA version, if used: CUDA 8.0, cudnn 6.0 * NVIDIA driver version, if in use: 391.35 #### Contributing Would ofc love to help out, but I don't think I'll be able to help out efficiently here.
693e1ef0ca08d93fa3deae263b1393822f368aff
5a656ecc0891ce370690cbfd881e02ce930d24ff
https://github.com/deeplearning4j/deeplearning4j/compare/693e1ef0ca08d93fa3deae263b1393822f368aff...5a656ecc0891ce370690cbfd881e02ce930d24ff
diff --git a/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/graph/vertex/impl/MergeVertex.java b/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/graph/vertex/impl/MergeVertex.java index 8c4a1d4d30..73a1da33e0 100644 --- a/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/graph/vertex/impl/MergeVertex.java +++ b/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/graph/vertex/impl/MergeVertex.java @@ -82,7 +82,7 @@ public class MergeVertex extends BaseGraphVertex { //No-op case int[] shape = inputs[0].shape(); forwardPassShapes = new int[][] {Arrays.copyOf(shape, shape.length)}; - return inputs[0]; + return workspaceMgr.leverageTo(ArrayType.ACTIVATIONS, inputs[0]); } forwardPassShapes = new int[inputs.length][0]; @@ -120,7 +120,7 @@ public class MergeVertex extends BaseGraphVertex { if (forwardPassShapes.length == 1) { //No op case - return new Pair<>(null, new INDArray[] {epsilon}); + return new Pair<>(null, new INDArray[] {workspaceMgr.leverageTo(ArrayType.ACTIVATION_GRAD, epsilon)}); } //Split the epsilons in the opposite way that the activations were merged
['deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/graph/vertex/impl/MergeVertex.java']
{'.java': 1}
1
1
0
0
1
8,020,374
1,739,852
216,483
1,385
289
64
4
1
4,151
262
947
78
0
0
1970-01-01T00:25:25
13,099
Java
{'Java': 42895752, 'C++': 17237193, 'Cuda': 2203734, 'Kotlin': 2030453, 'JavaScript': 296767, 'C': 172853, 'CMake': 126415, 'Shell': 96643, 'TypeScript': 81217, 'Python': 77566, 'FreeMarker': 77257, 'HTML': 18609, 'CSS': 12974, 'PureBasic': 12254, 'Cython': 12094, 'Ruby': 4558, 'Batchfile': 1458, 'Scala': 1026, 'Smarty': 975, 'Starlark': 931}
Apache License 2.0
9,733
deeplearning4j/deeplearning4j/5081/4294
deeplearning4j
deeplearning4j
https://github.com/deeplearning4j/deeplearning4j/issues/4294
https://github.com/deeplearning4j/deeplearning4j/pull/5081
https://github.com/deeplearning4j/deeplearning4j/pull/5081
1
closes
Keras Model Import API Loss Layer inconsistencies
#### Issue Description KerasModelImport.importKerasModelAndWeights(modelFileName, enforceTrain) vs KerasModelImport.importKerasModelAndWeights(jsonConfig, weightsFile, enforceTrain) produces different results (one includes a Loss Layer to the tail while the other does not): Reference the following gist for summary output: https://gist.github.com/akamlani/3a73df77fc1d3cbbc09101ba560a5efc In addition, it also is unable to handle the Loss Layer: Reference the following Keras gist for model architecture: https://gist.github.com/akamlani/f0371c3f91ad3e809a706b026bbf8ddb ``` KerasModel - Model cannot be trained: output layer outputLayer_a_loss is not an IOutputLayer (no loss function specified) KerasModel - Model cannot be trained: output outputLayer_a_loss is not an IOutputLayer (no loss function specified) ``` Unable to perform training nor inference, as no Output Layer recognized. #### Version Information * 0.9.2-SNAPSHOT (Per 11/12) * Keras 2.0.7 + TensorFlow 1.3.0 * MacOS * CPU Based
d1749c9f7cb79423f2273931b91d4947523f45af
4f058e80f1f9cf14d80b2700f3cb66bdb3965f37
https://github.com/deeplearning4j/deeplearning4j/compare/d1749c9f7cb79423f2273931b91d4947523f45af...4f058e80f1f9cf14d80b2700f3cb66bdb3965f37
diff --git a/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/KerasModel.java b/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/KerasModel.java index 1b23683f2f..90f57bdef0 100644 --- a/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/KerasModel.java +++ b/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/KerasModel.java @@ -158,8 +158,12 @@ public class KerasModel { prepareLayers((List<Object>) layerLists.get((config.getModelFieldLayers()))); /* Import training configuration. */ - if (trainingJson != null && enforceTrainingConfig) - importTrainingConfiguration(trainingJson); + if (enforceTrainingConfig) { + if (trainingJson != null) + importTrainingConfiguration(trainingJson); + else throw new UnsupportedKerasConfigurationException("If enforceTrainingConfig is true, a training " + + "configuration object (JSON) has to be provided."); + } /* Infer output types for each layer. */ inferOutputTypes(inputShape); diff --git a/deeplearning4j-modelimport/src/test/java/org/deeplearning4j/nn/modelimport/keras/e2e/KerasModelEndToEndTest.java b/deeplearning4j-modelimport/src/test/java/org/deeplearning4j/nn/modelimport/keras/e2e/KerasModelEndToEndTest.java index 8d0cf1d141..dc1c7e9a08 100644 --- a/deeplearning4j-modelimport/src/test/java/org/deeplearning4j/nn/modelimport/keras/e2e/KerasModelEndToEndTest.java +++ b/deeplearning4j-modelimport/src/test/java/org/deeplearning4j/nn/modelimport/keras/e2e/KerasModelEndToEndTest.java @@ -287,6 +287,30 @@ public class KerasModelEndToEndTest { importFunctionalModelH5Test("modelimport/keras/examples/reshape_to_rnn/reshape_model.h5"); } + /** + * Functional LSTM test + */ + @Test + public void importFunctionalLstmTfKeras2() throws Exception { + String modelPath = "modelimport/keras/examples/functional_lstm/lstm_functional_tf_keras_2.h5"; + + // No training enabled + ComputationGraph graphNoTrain = importFunctionalModelH5Test(modelPath, null, false); + System.out.println(graphNoTrain.summary()); + + // Training enabled + ComputationGraph graph = importFunctionalModelH5Test(modelPath, null, true); + System.out.println(graph.summary()); + + // Make predictions + int miniBatch = 32; + INDArray input = Nd4j.ones(miniBatch, 4, 10); + INDArray[] out = graph.output(input); + + // Fit model + graph.fit(new INDArray[] {input}, out); + } + /** * U-Net */
['deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/KerasModel.java', 'deeplearning4j-modelimport/src/test/java/org/deeplearning4j/nn/modelimport/keras/e2e/KerasModelEndToEndTest.java']
{'.java': 2}
2
2
0
0
2
8,036,922
1,743,361
216,863
1,388
453
77
8
1
1,026
117
266
24
2
1
1970-01-01T00:25:25
13,099
Java
{'Java': 42895752, 'C++': 17237193, 'Cuda': 2203734, 'Kotlin': 2030453, 'JavaScript': 296767, 'C': 172853, 'CMake': 126415, 'Shell': 96643, 'TypeScript': 81217, 'Python': 77566, 'FreeMarker': 77257, 'HTML': 18609, 'CSS': 12974, 'PureBasic': 12254, 'Cython': 12094, 'Ruby': 4558, 'Batchfile': 1458, 'Scala': 1026, 'Smarty': 975, 'Starlark': 931}
Apache License 2.0
9,732
deeplearning4j/deeplearning4j/5352/5351
deeplearning4j
deeplearning4j
https://github.com/deeplearning4j/deeplearning4j/issues/5351
https://github.com/deeplearning4j/deeplearning4j/pull/5352
https://github.com/deeplearning4j/deeplearning4j/pull/5352
1
fix
"Expected no workspace active" exception during evaluation
Training a simple MLP on MNIST with an EvaluativeListener, I get the following workspace-related exception: `Exception in thread "main" org.nd4j.linalg.workspace.ND4JWorkspaceException: Expected no workspace active in outputOfLayerDetached - Open/active workspaces: [WS_ALL_LAYERS_ACT]` It happens on the first call to `doEvaluation(...)` inside of the listener, so it likely has to do with the inference workspace mode...? Here's a full stack trace for the exception: ``` Exception in thread "main" org.nd4j.linalg.workspace.ND4JWorkspaceException: Expected no workspace active in outputOfLayerDetached - Open/active workspaces: [WS_ALL_LAYERS_ACT] at org.nd4j.linalg.workspace.WorkspaceUtils.assertNoWorkspacesOpen(WorkspaceUtils.java:38) at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.outputOfLayerDetached(MultiLayerNetwork.java:1030) at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.doEvaluation(MultiLayerNetwork.java:3052) at org.deeplearning4j.optimize.listeners.EvaluativeListener.invokeListener(EvaluativeListener.java:211) at org.deeplearning4j.optimize.listeners.EvaluativeListener.onBackwardPass(EvaluativeListener.java:188) at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.computeGradientAndScore(MultiLayerNetwork.java:2460) at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.computeGradientAndScore(MultiLayerNetwork.java:2395) at org.deeplearning4j.optimize.solvers.BaseOptimizer.gradientAndScore(BaseOptimizer.java:178) at org.deeplearning4j.optimize.solvers.StochasticGradientDescent.optimize(StochasticGradientDescent.java:60) at org.deeplearning4j.optimize.Solver.optimize(Solver.java:54) at org.deeplearning4j.nn.multilayer.MultiLayerNetwork.fit(MultiLayerNetwork.java:1459) at org.deeplearning4j.distributed.BasicTrainingExperimentDriver.entryPoint(BasicTrainingExperimentDriver.java:127) at org.deeplearning4j.distributed.BasicTrainingExperimentDriver.main(BasicTrainingExperimentDriver.java:58) ```
a589d2c42700c62eef32dee7a9d9ffb875d46aa7
df681f07aef9dbe8e98814f9ca96d718c027eb6a
https://github.com/deeplearning4j/deeplearning4j/compare/a589d2c42700c62eef32dee7a9d9ffb875d46aa7...df681f07aef9dbe8e98814f9ca96d718c027eb6a
diff --git a/deeplearning4j/deeplearning4j-core/src/test/java/org/deeplearning4j/eval/EvalTest.java b/deeplearning4j/deeplearning4j-core/src/test/java/org/deeplearning4j/eval/EvalTest.java index c71b5ab115..bf36fe97db 100644 --- a/deeplearning4j/deeplearning4j-core/src/test/java/org/deeplearning4j/eval/EvalTest.java +++ b/deeplearning4j/deeplearning4j-core/src/test/java/org/deeplearning4j/eval/EvalTest.java @@ -43,6 +43,7 @@ import org.deeplearning4j.nn.conf.layers.RnnOutputLayer; import org.deeplearning4j.nn.graph.ComputationGraph; import org.deeplearning4j.nn.multilayer.MultiLayerNetwork; import org.deeplearning4j.nn.weights.WeightInit; +import org.deeplearning4j.optimize.listeners.EvaluativeListener; import org.deeplearning4j.optimize.listeners.ScoreIterationListener; import org.junit.Test; import org.nd4j.linalg.activations.Activation; @@ -1249,6 +1250,40 @@ public class EvalTest extends BaseDL4JTest { System.out.println("\\n\\n\\n\\n"); System.out.println(e.stats(false, true)); + } + + + + @Test + public void testEvaluativeListenerSimple(){ + //Sanity check: https://github.com/deeplearning4j/deeplearning4j/issues/5351 + + // Network config + MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder() + + .optimizationAlgo(OptimizationAlgorithm.LINE_GRADIENT_DESCENT).seed(42) + .updater(new Sgd(1e-6)).list() + .layer(0, new DenseLayer.Builder().nIn(4).nOut(2).activation(Activation.TANH) + .weightInit(WeightInit.XAVIER).build()) + .layer(1, new org.deeplearning4j.nn.conf.layers.OutputLayer.Builder( + LossFunctions.LossFunction.MCXENT).nIn(2).nOut(3).weightInit(WeightInit.XAVIER) + .activation(Activation.SOFTMAX).build()) + .build(); + + // Instantiate model + MultiLayerNetwork net = new MultiLayerNetwork(conf); + net.init(); + + // Train-test split + DataSetIterator iter = new IrisDataSetIterator(30, 150); + DataSetIterator iterTest = new IrisDataSetIterator(30, 150); + + net.setListeners(new EvaluativeListener(iterTest, 3)); + + for( int i=0; i<10; i++ ){ + net.fit(iter); + } + } } diff --git a/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/optimize/listeners/EvaluativeListener.java b/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/optimize/listeners/EvaluativeListener.java index d8168c0b12..82e6d2aad3 100644 --- a/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/optimize/listeners/EvaluativeListener.java +++ b/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/optimize/listeners/EvaluativeListener.java @@ -152,7 +152,8 @@ public class EvaluativeListener extends BaseTrainingListener { */ @Override public void iterationDone(Model model, int iteration, int epoch) { - // no-op + if (invocationType == InvocationType.ITERATION_END) + invokeListener(model); } @Override @@ -167,27 +168,6 @@ public class EvaluativeListener extends BaseTrainingListener { invokeListener(model); } - @Override - public void onForwardPass(Model model, List<INDArray> activations) { - // no-op - } - - @Override - public void onForwardPass(Model model, Map<String, INDArray> activations) { - // no-op - } - - @Override - public void onGradientCalculation(Model model) { - // no-op - } - - @Override - public void onBackwardPass(Model model) { - if (invocationType == InvocationType.ITERATION_END) - invokeListener(model); - } - protected void invokeListener(Model model) { if (iterationCount.get() == null) iterationCount.set(new AtomicLong(0));
['deeplearning4j/deeplearning4j-core/src/test/java/org/deeplearning4j/eval/EvalTest.java', 'deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/optimize/listeners/EvaluativeListener.java']
{'.java': 2}
2
2
0
0
2
21,997,016
4,852,517
596,681
3,654
617
139
24
1
1,978
104
480
21
0
1
1970-01-01T00:25:27
13,099
Java
{'Java': 42895752, 'C++': 17237193, 'Cuda': 2203734, 'Kotlin': 2030453, 'JavaScript': 296767, 'C': 172853, 'CMake': 126415, 'Shell': 96643, 'TypeScript': 81217, 'Python': 77566, 'FreeMarker': 77257, 'HTML': 18609, 'CSS': 12974, 'PureBasic': 12254, 'Cython': 12094, 'Ruby': 4558, 'Batchfile': 1458, 'Scala': 1026, 'Smarty': 975, 'Starlark': 931}
Apache License 2.0
9,739
deeplearning4j/deeplearning4j/4664/4635
deeplearning4j
deeplearning4j
https://github.com/deeplearning4j/deeplearning4j/issues/4635
https://github.com/deeplearning4j/deeplearning4j/pull/4664
https://github.com/deeplearning4j/deeplearning4j/pull/4664
1
fix
Error using TransferLearningHelper with TinyYOLO
Hi By calling the following code: TinyYOLO model = new TinyYOLO(nClasses, seed); ComputationGraph computationGraph = (ComputationGraph) model.initPretrained(); TransferLearningHelper transferLearningHelper = new TransferLearningHelper(computationGraph, "conv2d_9"); We get the following exception stacktrace: Exception in thread "main" org.nd4j.linalg.exception.ND4JIllegalStateException: Invalid shape: Requested INDArray shape [1, 0] contains dimension size values < 1 (all dimensions must be 1 or more) at org.nd4j.linalg.factory.Nd4j.checkShapeValues(Nd4j.java:5122) at org.nd4j.linalg.factory.Nd4j.create(Nd4j.java:5112) at org.nd4j.linalg.factory.Nd4j.create(Nd4j.java:5065) at org.nd4j.linalg.factory.Nd4j.create(Nd4j.java:4170) at org.deeplearning4j.nn.graph.ComputationGraph.init(ComputationGraph.java:452) at org.deeplearning4j.nn.graph.ComputationGraph.init(ComputationGraph.java:377) at org.deeplearning4j.nn.transferlearning.TransferLearning$GraphBuilder.build(TransferLearning.java:755) at org.deeplearning4j.nn.transferlearning.TransferLearningHelper.initHelperGraph(TransferLearningHelper.java:252) at org.deeplearning4j.nn.transferlearning.TransferLearningHelper.<init>(TransferLearningHelper.java:56) at nlb.ai.deeplearning.dl4j.image.objectdetection.PersonsDetection.main(PersonsDetection.java:39) It works perfectly well with VGG16. * Deeplearning4j version 0.9.2-SANPSHOT * windows 10 * neither CUDA nor NVIDIA are used
6edd2e893be21e465790af47c8410851a8094c57
3e36a29d08219be90dfaa13ebd865a2e05b64ee1
https://github.com/deeplearning4j/deeplearning4j/compare/6edd2e893be21e465790af47c8410851a8094c57...3e36a29d08219be90dfaa13ebd865a2e05b64ee1
diff --git a/deeplearning4j-core/src/test/java/org/deeplearning4j/nn/graph/TestComputationGraphNetwork.java b/deeplearning4j-core/src/test/java/org/deeplearning4j/nn/graph/TestComputationGraphNetwork.java index 76098e52ca..8c776ce99c 100644 --- a/deeplearning4j-core/src/test/java/org/deeplearning4j/nn/graph/TestComputationGraphNetwork.java +++ b/deeplearning4j-core/src/test/java/org/deeplearning4j/nn/graph/TestComputationGraphNetwork.java @@ -6,8 +6,10 @@ import org.datavec.api.records.reader.RecordReader; import org.datavec.api.records.reader.impl.csv.CSVRecordReader; import org.datavec.api.split.FileSplit; import org.deeplearning4j.BaseDL4JTest; +import org.deeplearning4j.TestUtils; import org.deeplearning4j.datasets.datavec.RecordReaderMultiDataSetIterator; import org.deeplearning4j.datasets.iterator.impl.IrisDataSetIterator; +import org.deeplearning4j.datasets.iterator.impl.MnistDataSetIterator; import org.deeplearning4j.eval.Evaluation; import org.deeplearning4j.exception.DL4JException; import org.deeplearning4j.nn.api.OptimizationAlgorithm; @@ -1340,4 +1342,32 @@ public class TestComputationGraphNetwork extends BaseDL4JTest { assertEquals(13, net.layerSize("3")); } + @Test + public void testZeroParamNet() throws Exception { + + ComputationGraphConfiguration conf = new NeuralNetConfiguration.Builder() + .graphBuilder() + .addInputs("in") + .layer("0", new SubsamplingLayer.Builder().kernelSize(2,2).stride(2,2).build(), "in") + .layer("1", new LossLayer.Builder().activation(Activation.SIGMOID).lossFunction(LossFunctions.LossFunction.MSE).build(), "0") + .setOutputs("1") + .setInputTypes(InputType.convolutionalFlat(28,28,1)) + .build(); + + ComputationGraph net = new ComputationGraph(conf); + net.init(); + + DataSet ds = new MnistDataSetIterator(16, true, 12345).next(); + + INDArray out = net.outputSingle(ds.getFeatures()); + + INDArray labelTemp = Nd4j.create(out.shape()); + ds.setLabels(labelTemp); + + net.fit(ds); + + ComputationGraph net2 = TestUtils.testModelSerialization(net); + INDArray out2 = net2.outputSingle(ds.getFeatures()); + assertEquals(out, out2); + } } diff --git a/deeplearning4j-core/src/test/java/org/deeplearning4j/nn/multilayer/MultiLayerTest.java b/deeplearning4j-core/src/test/java/org/deeplearning4j/nn/multilayer/MultiLayerTest.java index 6b3b87d013..af21fb6c08 100644 --- a/deeplearning4j-core/src/test/java/org/deeplearning4j/nn/multilayer/MultiLayerTest.java +++ b/deeplearning4j-core/src/test/java/org/deeplearning4j/nn/multilayer/MultiLayerTest.java @@ -1245,4 +1245,32 @@ public class MultiLayerTest extends BaseDL4JTest { assertEquals(30, net.layerSize(2)); assertEquals(13, net.layerSize(3)); } + + + @Test + public void testZeroParamNet() throws Exception { + + MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder() + .list() + .layer(new SubsamplingLayer.Builder().kernelSize(2,2).stride(2,2).build()) + .layer(new LossLayer.Builder().activation(Activation.SIGMOID).lossFunction(LossFunctions.LossFunction.MSE).build()) + .setInputType(InputType.convolutionalFlat(28,28,1)) + .build(); + + MultiLayerNetwork net = new MultiLayerNetwork(conf); + net.init(); + + DataSet ds = new MnistDataSetIterator(16, true, 12345).next(); + + INDArray out = net.output(ds.getFeatures()); + + INDArray labelTemp = Nd4j.create(out.shape()); + ds.setLabels(labelTemp); + + net.fit(ds); + + MultiLayerNetwork net2 = TestUtils.testModelSerialization(net); + INDArray out2 = net2.output(ds.getFeatures()); + assertEquals(out, out2); + } } diff --git a/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/gradient/DefaultGradient.java b/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/gradient/DefaultGradient.java index d09015682b..dea4e3e4d3 100644 --- a/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/gradient/DefaultGradient.java +++ b/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/gradient/DefaultGradient.java @@ -93,7 +93,7 @@ public class DefaultGradient implements Gradient { } } flattenedGradient = Nd4j.toFlattened(DEFAULT_FLATTENING_ORDER, toFlatten); - } else { + } else if( !gradients.values().isEmpty() ){ //Edge case: can be empty for nets with 0 params //Standard case: flatten all to f order flattenedGradient = Nd4j.toFlattened(DEFAULT_FLATTENING_ORDER, gradients.values()); } diff --git a/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/graph/ComputationGraph.java b/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/graph/ComputationGraph.java index 59399df257..db983b45b1 100755 --- a/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/graph/ComputationGraph.java +++ b/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/graph/ComputationGraph.java @@ -449,9 +449,12 @@ public class ComputationGraph implements Serializable, Model, NeuralNetwork { flattenedParams = parameters; initializeParams = false; - } else { + } else if(numParams > 0){ flattenedParams = Nd4j.create(1, numParams); initializeParams = true; + } else { + flattenedParams = null; + initializeParams = false; } //Set RNG seed, for repeatability between initializations when set @@ -632,7 +635,10 @@ public class ComputationGraph implements Serializable, Model, NeuralNetwork { numParams += numParamsForVertex[i]; i++; } - flattenedGradients = Nd4j.create(1, numParams); + + if(numParams > 0) { + flattenedGradients = Nd4j.create(1, numParams); + } //Given the topological ordering: work out the subset of the gradient array used for each layer, and set it int paramOffsetSoFar = 0; @@ -1138,6 +1144,10 @@ public class ComputationGraph implements Serializable, Model, NeuralNetwork { * @param labelMaskArrays Mas arrays for the labels/outputs. Typically used for RNN training. May be null. */ public void fit(INDArray[] inputs, INDArray[] labels, INDArray[] featureMaskArrays, INDArray[] labelMaskArrays) { + if (numParams() == 0) { + return; //Edge case: net with no params: fitting is a no-op + } + if (flattenedGradients == null) { initGradientsView(); } diff --git a/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/multilayer/MultiLayerNetwork.java b/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/multilayer/MultiLayerNetwork.java index b220483e91..ce19832f2a 100755 --- a/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/multilayer/MultiLayerNetwork.java +++ b/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/multilayer/MultiLayerNetwork.java @@ -604,9 +604,13 @@ public class MultiLayerNetwork implements Serializable, Classifier, Layer, Neura flattenedParams = parameters; initializeParams = false; - } else { + } else if(paramLength > 0){ flattenedParams = Nd4j.create(1, paramLength); initializeParams = true; + } else { + //Edge case: 0 params in network + flattenedParams = null; + initializeParams = false; } //Set RNG seed, for repeatability between initializations when set @@ -693,7 +697,9 @@ public class MultiLayerNetwork implements Serializable, Classifier, Layer, Neura paramLength += nParamsPerLayer[i]; } - flattenedGradients = Nd4j.zeros(new int[] {1, paramLength}, 'f'); //No need to initialize, as each layer will do it each iteration anyway + if(paramLength > 0) { + flattenedGradients = Nd4j.zeros(new int[]{1, paramLength}, 'f'); //No need to initialize, as each layer will do it each iteration anyway + } int backpropParamsSoFar = 0; for (int i = 0; i < layers.length; i++) { @@ -1861,6 +1867,10 @@ public class MultiLayerNetwork implements Serializable, Classifier, Layer, Neura * @param labelsMask The mask array for the labels (used for variable length time series, etc). May be null. */ public void fit(INDArray features, INDArray labels, INDArray featuresMask, INDArray labelsMask) { + if(numParams() == 0){ + //No op: can't fit a network with 0 parameters + return; + } setInput(features); setLabels(labels); diff --git a/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/updater/BaseMultiLayerUpdater.java b/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/updater/BaseMultiLayerUpdater.java index ba08beb97f..da46b30e77 100644 --- a/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/updater/BaseMultiLayerUpdater.java +++ b/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/updater/BaseMultiLayerUpdater.java @@ -299,7 +299,11 @@ public abstract class BaseMultiLayerUpdater<T extends Model> implements Updater gradient.gradient().divi(batchSize); } else { //Standard case - getFlattenedGradientsView().divi(batchSize); + INDArray grad = getFlattenedGradientsView(); + if(grad != null) { + //May be null for nets with no parameters + grad.divi(batchSize); + } } } } diff --git a/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/ModelSerializer.java b/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/ModelSerializer.java index e0644a9f1b..70694cc547 100644 --- a/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/ModelSerializer.java +++ b/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/ModelSerializer.java @@ -125,12 +125,18 @@ public class ModelSerializer { ZipEntry coefficients = new ZipEntry("coefficients.bin"); zipfile.putNextEntry(coefficients); DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(zipfile)); - try { - Nd4j.write(model.params(), dos); - } finally { - dos.flush(); - if (!saveUpdater) - dos.close(); + INDArray params = model.params(); + if(params != null) { + try { + Nd4j.write(model.params(), dos); + } finally { + dos.flush(); + if (!saveUpdater) + dos.close(); + } + } else { + ZipEntry noParamsMarker = new ZipEntry("noParams.marker"); + zipfile.putNextEntry(noParamsMarker); } if (saveUpdater) { @@ -225,13 +231,18 @@ public class ModelSerializer { ZipEntry coefficients = zipFile.getEntry("coefficients.bin"); - if (coefficients != null) { - InputStream stream = zipFile.getInputStream(coefficients); - DataInputStream dis = new DataInputStream(new BufferedInputStream(stream)); - params = Nd4j.read(dis); + if (coefficients != null ) { + if(coefficients.getSize() > 0) { + InputStream stream = zipFile.getInputStream(coefficients); + DataInputStream dis = new DataInputStream(new BufferedInputStream(stream)); + params = Nd4j.read(dis); - dis.close(); - gotCoefficients = true; + dis.close(); + gotCoefficients = true; + } else { + ZipEntry noParamsMarker = zipFile.getEntry("noParams.marker"); + gotCoefficients = (noParamsMarker != null); + } } if (loadUpdater) { @@ -470,12 +481,17 @@ public class ModelSerializer { ZipEntry coefficients = zipFile.getEntry("coefficients.bin"); if (coefficients != null) { - InputStream stream = zipFile.getInputStream(coefficients); - DataInputStream dis = new DataInputStream(new BufferedInputStream(stream)); - params = Nd4j.read(dis); + if(coefficients.getSize() > 0) { + InputStream stream = zipFile.getInputStream(coefficients); + DataInputStream dis = new DataInputStream(new BufferedInputStream(stream)); + params = Nd4j.read(dis); - dis.close(); - gotCoefficients = true; + dis.close(); + gotCoefficients = true; + } else { + ZipEntry noParamsMarker = zipFile.getEntry("noParams.marker"); + gotCoefficients = (noParamsMarker != null); + } } diff --git a/deeplearning4j-zoo/src/test/java/org/deeplearning4j/zoo/TestInstantiation.java b/deeplearning4j-zoo/src/test/java/org/deeplearning4j/zoo/TestInstantiation.java index 66d0b54f95..10232887cd 100644 --- a/deeplearning4j-zoo/src/test/java/org/deeplearning4j/zoo/TestInstantiation.java +++ b/deeplearning4j-zoo/src/test/java/org/deeplearning4j/zoo/TestInstantiation.java @@ -5,6 +5,7 @@ import org.deeplearning4j.datasets.iterator.impl.BenchmarkDataSetIterator; import org.deeplearning4j.nn.api.Model; import org.deeplearning4j.nn.graph.ComputationGraph; import org.deeplearning4j.nn.multilayer.MultiLayerNetwork; +import org.deeplearning4j.nn.transferlearning.TransferLearningHelper; import org.deeplearning4j.zoo.model.Darknet19; import org.deeplearning4j.zoo.model.GoogLeNet; import org.deeplearning4j.zoo.model.ResNet50; @@ -139,4 +140,16 @@ public class TestInstantiation { assertArrayEquals(result[0].shape(), new int[] {1, 125, 13, 13}); } + + @Test + public void testYolo4635() throws Exception { + //https://github.com/deeplearning4j/deeplearning4j/issues/4635 + + int nClasses = 10; + int seed = 12345; + TinyYOLO model = new TinyYOLO(nClasses, seed); + ComputationGraph computationGraph = (ComputationGraph) model.initPretrained(); + TransferLearningHelper transferLearningHelper = new TransferLearningHelper(computationGraph, "conv2d_9"); + } + }
['deeplearning4j-core/src/test/java/org/deeplearning4j/nn/multilayer/MultiLayerTest.java', 'deeplearning4j-zoo/src/test/java/org/deeplearning4j/zoo/TestInstantiation.java', 'deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/graph/ComputationGraph.java', 'deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/gradient/DefaultGradient.java', 'deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/multilayer/MultiLayerNetwork.java', 'deeplearning4j-core/src/test/java/org/deeplearning4j/nn/graph/TestComputationGraphNetwork.java', 'deeplearning4j-nn/src/main/java/org/deeplearning4j/util/ModelSerializer.java', 'deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/updater/BaseMultiLayerUpdater.java']
{'.java': 8}
8
8
0
0
8
7,878,422
1,707,448
215,784
1,363
3,741
728
86
5
1,486
94
389
29
0
0
1970-01-01T00:25:18
13,099
Java
{'Java': 42895752, 'C++': 17237193, 'Cuda': 2203734, 'Kotlin': 2030453, 'JavaScript': 296767, 'C': 172853, 'CMake': 126415, 'Shell': 96643, 'TypeScript': 81217, 'Python': 77566, 'FreeMarker': 77257, 'HTML': 18609, 'CSS': 12974, 'PureBasic': 12254, 'Cython': 12094, 'Ruby': 4558, 'Batchfile': 1458, 'Scala': 1026, 'Smarty': 975, 'Starlark': 931}
Apache License 2.0
9,730
deeplearning4j/deeplearning4j/5381/2104
deeplearning4j
deeplearning4j
https://github.com/deeplearning4j/deeplearning4j/issues/2104
https://github.com/deeplearning4j/deeplearning4j/pull/5381
https://github.com/deeplearning4j/deeplearning4j/pull/5381
1
closes
Poor GPU performance relative to CPU
This issue is similar to #2053, with a few key differences: - I'm using a recurrent neural network. - Performance is consistently and significantly _worse_ with the GPU backend (not merely comparable). - I have a small dataset (16x9x308), which is probably at least partly to blame. However, the nsight profiling results with a larger dataset may suggest that DL4J can close the gap somewhat (see below). I'm using the latest release of DeepLearning4J (0.5.0). **Minimized Test Case** ``` java package com.stottlerhenke.illuminate; import java.util.List; import com.stottlerhenke.illuminate.training.PerformanceListener; import org.deeplearning4j.nn.api.OptimizationAlgorithm; import org.deeplearning4j.nn.conf.*; import org.deeplearning4j.nn.conf.layers.GravesLSTM; import org.deeplearning4j.nn.conf.layers.RnnOutputLayer; import org.deeplearning4j.nn.multilayer.MultiLayerNetwork; import org.deeplearning4j.nn.weights.WeightInit; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.dataset.DataSet; import org.nd4j.linalg.dataset.api.DataSetPreProcessor; import org.nd4j.linalg.dataset.api.iterator.DataSetIterator; import org.nd4j.linalg.factory.Nd4j; import org.nd4j.linalg.lossfunctions.LossFunctions; public class GpuProblem { public static int timeSeriesCount = 16; public static int inputCount = 9; public static int timeSteps = 308; public static int numHiddenNodes = 20; public static int truncatedBPTTLength = 100; public static int epochCount = 3; public static class MyDatasetIterator implements DataSetIterator { private DataSetPreProcessor preProcessor; int cursor = 0; @Override public boolean hasNext() { return cursor < epochCount; } @Override public DataSet next() { return next(1); } @Override public DataSet next(int num) { DataSet ds = createDataset(); if (preProcessor != null) preProcessor.preProcess(ds); cursor += num; System.out.println("NEW CURSOR " + cursor); return ds; } private DataSet createDataset() { INDArray createDataSetinput = Nd4j.zeros(timeSeriesCount, inputCount, timeSteps); INDArray createDataSetlabels = Nd4j.zeros(timeSeriesCount, 2, timeSteps); return new DataSet(createDataSetinput, createDataSetlabels); } @Override public int totalExamples() { throw new UnsupportedOperationException(); } @Override public int inputColumns() { return inputCount; } @Override public int totalOutcomes() { return 2; } @Override public boolean resetSupported() { return true; } @Override public void reset() { cursor = 0; System.out.println("RESET NEW CURSOR " + cursor); } @Override public int batch() { return timeSeriesCount; } @Override public int cursor() { throw new UnsupportedOperationException(); } @Override public int numExamples() { throw new UnsupportedOperationException(); } @Override public void setPreProcessor(DataSetPreProcessor preProcessor) { this.preProcessor = preProcessor; } @Override public DataSetPreProcessor getPreProcessor() { return this.preProcessor; } @Override public List<String> getLabels() { return null; } } public static void main(String[] args) { MultiLayerConfiguration.Builder builder = new NeuralNetConfiguration.Builder() .optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT).iterations(1) .updater(Updater.ADAM).adamMeanDecay(0.9).adamVarDecay(0.999) .regularization(true).l1(1e-4).dropOut(0.5) .weightInit(WeightInit.XAVIER) .learningRate(5e-4) .list() .layer(0, new GravesLSTM.Builder().nIn(inputCount).nOut(numHiddenNodes) .activation("tanh").build()) .layer(1, new RnnOutputLayer.Builder().nIn(numHiddenNodes) .activation("softmax") .lossFunction(LossFunctions.LossFunction.MCXENT) .nIn(numHiddenNodes).nOut(2).build()) .pretrain(false) .backprop(true) .backpropType(BackpropType.TruncatedBPTT) .tBPTTBackwardLength(truncatedBPTTLength).tBPTTForwardLength(truncatedBPTTLength); MultiLayerNetwork net = new MultiLayerNetwork(builder.build()); net.init(); net.setListeners(new PerformanceListener(1)); net.fit(new MyDatasetIterator()); } } ``` **Performance Results** CPU ``` iteration 1; iteration time: 341 ms; samples/sec: 46.921; batches/sec: 2.933; iteration 2; iteration time: 170 ms; samples/sec: 94.118; batches/sec: 5.882; iteration 3; iteration time: 158 ms; samples/sec: 101.266; batches/sec: 6.329; iteration 4; iteration time: 181 ms; samples/sec: 88.398; batches/sec: 5.525; iteration 5; iteration time: 127 ms; samples/sec: 125.984; batches/sec: 7.874; iteration 6; iteration time: 122 ms; samples/sec: 131.148; batches/sec: 8.197; iteration 7; iteration time: 122 ms; samples/sec: 131.148; batches/sec: 8.197; iteration 8; iteration time: 119 ms; samples/sec: 134.454; batches/sec: 8.403; iteration 9; iteration time: 119 ms; samples/sec: 134.454; batches/sec: 8.403; ``` GPU ``` iteration 1; iteration time: 1667 ms; samples/sec: 9.598; batches/sec: 0.600; iteration 2; iteration time: 1266 ms; samples/sec: 12.638; batches/sec: 0.790; iteration 3; iteration time: 1241 ms; samples/sec: 12.893; batches/sec: 0.806; iteration 4; iteration time: 1192 ms; samples/sec: 13.423; batches/sec: 0.839; iteration 5; iteration time: 1204 ms; samples/sec: 13.289; batches/sec: 0.831; iteration 6; iteration time: 1178 ms; samples/sec: 13.582; batches/sec: 0.849; iteration 7; iteration time: 1137 ms; samples/sec: 14.072; batches/sec: 0.880; iteration 8; iteration time: 1141 ms; samples/sec: 14.023; batches/sec: 0.876; iteration 9; iteration time: 1183 ms; samples/sec: 13.525; batches/sec: 0.845; ``` I also tested with more data by increasing the number of time series from 16 to 16,000. With this change, the GPU does outperform the CPU (as expected); however, profiling with nsight shows only 9.1% GPU utilization (although I was only able to profile one iteration due to an issue with nsight that caused the test application to terminate early with an access violation, and the utilization percentage is probably unduly influenced by the time period before network training begins).
f076de2362651f28469efc117a2e240cc9ced031
8e1619c81dcabcd3d6d8f21fc992666b4a674154
https://github.com/deeplearning4j/deeplearning4j/compare/f076de2362651f28469efc117a2e240cc9ced031...8e1619c81dcabcd3d6d8f21fc992666b4a674154
diff --git a/nd4j/nd4j-buffer/src/main/java/org/nd4j/linalg/api/buffer/BaseDataBuffer.java b/nd4j/nd4j-buffer/src/main/java/org/nd4j/linalg/api/buffer/BaseDataBuffer.java index e56a3abaa1..6660e2b6d2 100644 --- a/nd4j/nd4j-buffer/src/main/java/org/nd4j/linalg/api/buffer/BaseDataBuffer.java +++ b/nd4j/nd4j-buffer/src/main/java/org/nd4j/linalg/api/buffer/BaseDataBuffer.java @@ -822,8 +822,7 @@ public abstract class BaseDataBuffer implements DataBuffer { @Override public void assign(Number value) { - for (int i = 0; i < length(); i++) - assign(value, i); + assign(value, 0); }
['nd4j/nd4j-buffer/src/main/java/org/nd4j/linalg/api/buffer/BaseDataBuffer.java']
{'.java': 1}
1
1
0
0
1
22,023,858
4,858,335
597,412
3,656
101
29
3
1
7,097
642
1,704
191
0
3
1970-01-01T00:25:27
13,099
Java
{'Java': 42895752, 'C++': 17237193, 'Cuda': 2203734, 'Kotlin': 2030453, 'JavaScript': 296767, 'C': 172853, 'CMake': 126415, 'Shell': 96643, 'TypeScript': 81217, 'Python': 77566, 'FreeMarker': 77257, 'HTML': 18609, 'CSS': 12974, 'PureBasic': 12254, 'Cython': 12094, 'Ruby': 4558, 'Batchfile': 1458, 'Scala': 1026, 'Smarty': 975, 'Starlark': 931}
Apache License 2.0
9,729
deeplearning4j/deeplearning4j/5643/5605
deeplearning4j
deeplearning4j
https://github.com/deeplearning4j/deeplearning4j/issues/5605
https://github.com/deeplearning4j/deeplearning4j/pull/5643
https://github.com/deeplearning4j/deeplearning4j/pull/5643
1
fixes
Unable to broadcast dimension 1 due to shape mismatch exception with Deconvolution2D layers
I tried to set up a neural net using a ComputationGraph based on some research paper. This net has an encoder-decoder like structure: it uses Deconvolution2D layers for the decoding part. After putting together the net, I found that I can run the training with batch size 1, but any higher batch size value causes the net to stop with a message similar to the below: Exception in thread "main" java.lang.IllegalArgumentException: Unable to broadcast dimension 1 due to shape mismatch. Right shape must be 1. Left array shape: [2, 16, 33, 33], right array shape: [16, 2, 33, 33] I spent a lot of time debugging the issue to see what did I miss. I simplified the net to the smallest possible size, it now only has a Convolution, Deconvolution2D and an Output layer. I can still reproduce my original problem: with batch size 1, it works fine, otherwise it stops. Looking at the array shapes in the error message it seems that the minibatch size and the number of channels is mixed up whenever I receive this error. I created a GIST for this in the hope that someone could check and give me a hint on how to fix this. https://gist.github.com/bekkon/7fd406d21d1320d08a5d2fe82e2a0331 After tracing back the calls, I found that I can seemingly fix this error by modifying the backpropGradient method in Deconvolution2D class. At the very end of the method, it does a permutation of the previously prepared outEps: "outEps = outEps.permute(1, 0, 2 , 3);" If I change this to "outEps = outEps.permute(0, 1, 2 , 3);", the exception goes away, backpropagation succeeds in the preceding layer. Please check if this is indeed an error in Deconvolution2D. If not, please help me understand what did I do wrong in my network setup to end up with this error. (The attached net in the GIST is just for reproducing the error, it is not supposed to be meaningful, for network-help I'll share the complex net in a separate GIST ) Thanks :)
50b5e6427c0ad19ae6216bc82f9e15030de55408
e338b026a120ea6634bf7d67c45b07dfd6f11e9d
https://github.com/deeplearning4j/deeplearning4j/compare/50b5e6427c0ad19ae6216bc82f9e15030de55408...e338b026a120ea6634bf7d67c45b07dfd6f11e9d
diff --git a/deeplearning4j/deeplearning4j-cuda/src/test/java/org/deeplearning4j/gradientcheck/CNNGradientCheckTest.java b/deeplearning4j/deeplearning4j-cuda/src/test/java/org/deeplearning4j/gradientcheck/CNNGradientCheckTest.java index 22f33a7f31..5c656c807d 100644 --- a/deeplearning4j/deeplearning4j-cuda/src/test/java/org/deeplearning4j/gradientcheck/CNNGradientCheckTest.java +++ b/deeplearning4j/deeplearning4j-cuda/src/test/java/org/deeplearning4j/gradientcheck/CNNGradientCheckTest.java @@ -861,7 +861,7 @@ public class CNNGradientCheckTest extends BaseDL4JTest { public void testDeconvolution2D() { int nOut = 2; - int[] minibatchSizes = new int[]{1, 3, 1, 3, 1, 3, 1, 3}; + int[] minibatchSizes = new int[]{1, 4, 1, 4, 1, 1, 2, 1}; int[] kernelSizes = new int[]{1, 1, 3, 3, 1, 1, 3, 3}; int[] strides = {1, 1, 1, 1, 2, 2, 2, 2}; int[] dilation = {1, 2, 2, 1, 1, 1, 2, 2}; @@ -895,13 +895,23 @@ public class CNNGradientCheckTest extends BaseDL4JTest { .updater(new NoOp()) .activation(act) .list() + .layer(new Deconvolution2D.Builder().name("deconvolution_2D_layer-0") + .cudnnAllowFallback(false) + .kernelSize(1, 1) + .stride(1, 1) + .dilation(0, 0) + .convolutionMode(cm) + .nIn(inputDepth) + .nOut(inputDepth) + .build()) .layer(new Deconvolution2D.Builder().name("deconvolution_2D_layer") .cudnnAllowFallback(false) .kernelSize(k, k) .stride(s, s) .dilation(d, d) .convolutionMode(cm) - .nIn(inputDepth).nOut(nOut).build()); + .nIn(inputDepth).nOut(nOut) + .build()); MultiLayerConfiguration conf = b.layer(new OutputLayer.Builder(LossFunctions.LossFunction.MCXENT) .activation(Activation.SOFTMAX).nOut(nOut).build()) diff --git a/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/convolution/Deconvolution2DLayer.java b/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/convolution/Deconvolution2DLayer.java index e86b583fef..f609d4e06e 100644 --- a/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/convolution/Deconvolution2DLayer.java +++ b/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/convolution/Deconvolution2DLayer.java @@ -132,8 +132,6 @@ public class Deconvolution2DLayer extends ConvolutionLayer { retGradient.setGradientFor(DeconvolutionParamInitializer.WEIGHT_KEY, weightGradView, 'c'); weightNoiseParams.clear(); - outEps = outEps.permute(1, 0, 2 , 3); - return new Pair<>(retGradient, outEps); }
['deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/convolution/Deconvolution2DLayer.java', 'deeplearning4j/deeplearning4j-cuda/src/test/java/org/deeplearning4j/gradientcheck/CNNGradientCheckTest.java']
{'.java': 2}
2
2
0
0
2
22,432,400
4,941,774
606,321
3,699
48
22
2
1
1,946
334
489
18
1
0
1970-01-01T00:25:29
13,099
Java
{'Java': 42895752, 'C++': 17237193, 'Cuda': 2203734, 'Kotlin': 2030453, 'JavaScript': 296767, 'C': 172853, 'CMake': 126415, 'Shell': 96643, 'TypeScript': 81217, 'Python': 77566, 'FreeMarker': 77257, 'HTML': 18609, 'CSS': 12974, 'PureBasic': 12254, 'Cython': 12094, 'Ruby': 4558, 'Batchfile': 1458, 'Scala': 1026, 'Smarty': 975, 'Starlark': 931}
Apache License 2.0
9,724
deeplearning4j/deeplearning4j/9552/9536
deeplearning4j
deeplearning4j
https://github.com/deeplearning4j/deeplearning4j/issues/9536
https://github.com/deeplearning4j/deeplearning4j/pull/9552
https://github.com/deeplearning4j/deeplearning4j/pull/9552
1
fixes
SpecifiedIndex and put(): changes not reflected (1.0.0M1)
#### Issue Description Please describe your issue, along with: - expected behavior When setting a value using `INDArray.put(SpecifiedIndex, element)`, the changes should be reflected in the original array as well as the returned array. - encountered behavior Changes are not reflected in the array (and hence neither in the returned array). #### Version Information 1.0.0-M1.1 Please indicate relevant versions, including, if relevant: * Deeplearning4j version nd4j-native 1.0.0-M1.1 * platform information (OS, etc) Linux * CUDA version, if used None * NVIDIA driver version, if in use #N/A #### Contributing Happy to fix it - let me know what approaches have been attempted/considered previously. In BaseNDArray: ``` @Override public INDArray put(INDArrayIndex[] indices, Number element) { Nd4j.getCompressor().autoDecompress(this); INDArray get = get(indices); for (int i = 0; i < get.length(); i++) get.putScalar(i, element.doubleValue()); return this; } ``` Here, the get is not a view but a detached copy, and therefore the changes done in `get.putScalar` is not propagated to the original array. Using ``` INDArray original = ...; original.put(INDArrayIndex[] indices, INDArray element) ``` does solve the issue by copying item-by-item from the element array to the original array, but requires element to be of the same size as the original array - which could waste RAM. Test case (Kotlin): ``` val a1 = Nd4j.arange(12.0).reshape(2L, 3, 2).castTo(DataType.INT16); println("Original"); println(a1); val indices = arrayOf(all(), indices(0, 2), point(1)); a1.put(indices, Nd4j.onesLike(a1).muli(-1).castTo(DataType.INT16)); println("a1.put(arrayOf(all(), indices(0,2), point(1)), Nd4j.onesLike(a1).muli(-1).castTo(DataType.INT16))"); println(a1); ``` Is there a better solution? First reported in https://github.com/deeplearning4j/nd4j/issues/611
71ee908d10edef8165424b67a46f4797a202168c
c0c191f869a7004faca796dce2fe76ea0ee113f7
https://github.com/deeplearning4j/deeplearning4j/compare/71ee908d10edef8165424b67a46f4797a202168c...c0c191f869a7004faca796dce2fe76ea0ee113f7
diff --git a/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ndarray/BaseNDArray.java b/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ndarray/BaseNDArray.java index 9e057e5814..729d24fc5f 100644 --- a/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ndarray/BaseNDArray.java +++ b/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ndarray/BaseNDArray.java @@ -2182,14 +2182,14 @@ public abstract class BaseNDArray implements INDArray, Iterable { INDArrayIndex[] destinationIndices = indices.clone(); //Shallow clone INDArrayIndex[] sourceIndices = indices.clone(); - for( int i=0; i<indices.length; i++){ + for( int i = 0; i < indices.length; i++) { INDArrayIndex idx = indices[i]; - if(idx instanceof SpecifiedIndex){ + if(idx instanceof SpecifiedIndex) { numSpecified++; long[] idxs = ((SpecifiedIndex) idx).getIndexes(); specifiedIdxs.add(idxs); specifiedIdxDims.add(i); - } else if(idx instanceof PointIndex){ + } else if(idx instanceof PointIndex) { //Example: [2,3,3].put(point(1), ..., [1,x,y]) -> can't use point(1) on [1,x,y] sourceIndices[i] = NDArrayIndex.point(0); } @@ -2202,9 +2202,9 @@ public abstract class BaseNDArray implements INDArray, Iterable { } NdIndexIterator iter = new NdIndexIterator(counts); - while(iter.hasNext()){ + while(iter.hasNext()) { long[] iterationIdxs = iter.next(); - for(int i=0; i<iterationIdxs.length; i++ ){ + for(int i = 0; i < iterationIdxs.length; i++) { long[] indicesForDim = specifiedIdxs.get(i); destinationIndices[dims[i]] = NDArrayIndex.point(indicesForDim[(int)iterationIdxs[i]]); sourceIndices[dims[i]] = NDArrayIndex.point(iterationIdxs[i]); @@ -2212,7 +2212,7 @@ public abstract class BaseNDArray implements INDArray, Iterable { INDArray sourceView = element.get(sourceIndices); INDArray destinationView = this.get(destinationIndices); - destinationView.assign(sourceView); + return destinationView.assign(sourceView); } } return this; diff --git a/nd4j/nd4j-backends/nd4j-tests/src/test/java/org/nd4j/linalg/api/indexing/IndexingTestsC.java b/nd4j/nd4j-backends/nd4j-tests/src/test/java/org/nd4j/linalg/api/indexing/IndexingTestsC.java index 08ee5b9cd0..02b15daf6d 100644 --- a/nd4j/nd4j-backends/nd4j-tests/src/test/java/org/nd4j/linalg/api/indexing/IndexingTestsC.java +++ b/nd4j/nd4j-backends/nd4j-tests/src/test/java/org/nd4j/linalg/api/indexing/IndexingTestsC.java @@ -51,6 +51,15 @@ public class IndexingTestsC extends BaseNd4jTestWithBackends { + @ParameterizedTest + @MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs") + public void testSpecifiedIndexPut(Nd4jBackend backend) { + INDArray arr = Nd4j.arange(12.0).reshape(2,3,2); + INDArrayIndex[] indices = {NDArrayIndex.all(),NDArrayIndex.indices(0,2),NDArrayIndex.point(1)}; + INDArray put = arr.put(indices,Nd4j.onesLike(arr.muli(-1))); + assertNotEquals(arr,put); + } + @ParameterizedTest @MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
['nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ndarray/BaseNDArray.java', 'nd4j/nd4j-backends/nd4j-tests/src/test/java/org/nd4j/linalg/api/indexing/IndexingTestsC.java']
{'.java': 2}
2
2
0
0
2
24,717,412
5,398,846
653,490
3,955
634
130
12
1
1,948
239
513
58
1
3
1970-01-01T00:27:18
13,099
Java
{'Java': 42895752, 'C++': 17237193, 'Cuda': 2203734, 'Kotlin': 2030453, 'JavaScript': 296767, 'C': 172853, 'CMake': 126415, 'Shell': 96643, 'TypeScript': 81217, 'Python': 77566, 'FreeMarker': 77257, 'HTML': 18609, 'CSS': 12974, 'PureBasic': 12254, 'Cython': 12094, 'Ruby': 4558, 'Batchfile': 1458, 'Scala': 1026, 'Smarty': 975, 'Starlark': 931}
Apache License 2.0
9,725
deeplearning4j/deeplearning4j/9406/9403
deeplearning4j
deeplearning4j
https://github.com/deeplearning4j/deeplearning4j/issues/9403
https://github.com/deeplearning4j/deeplearning4j/pull/9406
https://github.com/deeplearning4j/deeplearning4j/pull/9406
1
fix
MultiLayerConfiguration.Builder child class is missing new parameter while building
#### Issue Description When building a new configuration via `NeuralNetConfiguration.Builder`, such as the one in the main README of the repo: ``` MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder() .seed(seed) .l2(0.0005) .weightInit(WeightInit.XAVIER) .updater(new Adam(1e-3)) .list() ... .build(); ``` a child class instance, one that extends `MultiLayerConfiguration.Builder`, is being returned and used to build the overall configuration. That _builder_ is not using at least one configuration parameter which was recently introduced for the original `MultiLayerConfiguration`: - `public Builder overrideNinUponBuild(boolean overrideNinUponBuild)` #### Version Information * Impacted: * **1.0.0-M1** * **1.0.0-M1.1** #### Additional Information Class in question, that seems to be misbehaving: `NeuralNetConfiguration.ListBuilder`
a066e465f4eee86bf1f50b0525373f97c359a512
12badf53ec2c27b7617fceafc6819238e7b9a5dc
https://github.com/deeplearning4j/deeplearning4j/compare/a066e465f4eee86bf1f50b0525373f97c359a512...12badf53ec2c27b7617fceafc6819238e7b9a5dc
diff --git a/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/conf/NeuralNetConfiguration.java b/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/conf/NeuralNetConfiguration.java index 6907e79ae2..0225c889f6 100755 --- a/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/conf/NeuralNetConfiguration.java +++ b/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/conf/NeuralNetConfiguration.java @@ -181,6 +181,83 @@ public class NeuralNetConfiguration implements Serializable, Cloneable { return layerwise; } + @Override + public ListBuilder overrideNinUponBuild(boolean overrideNinUponBuild) { + super.overrideNinUponBuild(overrideNinUponBuild); + return this; + } + + @Override + public ListBuilder inputPreProcessor(Integer layer, InputPreProcessor processor) { + super.inputPreProcessor(layer, processor); + return this; + } + + @Override + public ListBuilder inputPreProcessors(Map<Integer, InputPreProcessor> processors) { + super.inputPreProcessors(processors); + return this; + } + + @Override + public ListBuilder cacheMode(@NonNull CacheMode cacheMode) { + super.cacheMode(cacheMode); + return this; + } + + @Override + public MultiLayerConfiguration.Builder backpropType(@NonNull BackpropType type) { + super.backpropType(type); + return this; + } + + @Override + public ListBuilder tBPTTLength(int bpttLength) { + super.tBPTTLength(bpttLength); + return this; + } + + @Override + public ListBuilder tBPTTForwardLength(int forwardLength) { + super.tBPTTForwardLength(forwardLength); + return this; + } + + @Override + public ListBuilder tBPTTBackwardLength(int backwardLength) { + super.tBPTTBackwardLength(backwardLength); + return this; + } + + @Override + public ListBuilder confs(List<NeuralNetConfiguration> confs) { + super.confs(confs); + return this; + } + + @Override + public ListBuilder validateOutputLayerConfig(boolean validate) { + super.validateOutputLayerConfig(validate); + return this; + } + + @Override + public ListBuilder validateTbpttConfig(boolean validate) { + super.validateTbpttConfig(validate); + return this; + } + + @Override + public ListBuilder dataType(@NonNull DataType dataType) { + super.dataType(dataType); + return this; + } + + @Override + protected void finalize() throws Throwable { + super.finalize(); + } + @Override public ListBuilder setInputType(InputType inputType){ return (ListBuilder)super.setInputType(inputType); @@ -228,12 +305,12 @@ public class NeuralNetConfiguration implements Serializable, Cloneable { for (int i = 0; i < layerwise.size(); i++) { if (layerwise.get(i) == null) { throw new IllegalStateException("Invalid configuration: layer number " + i - + " not specified. Expect layer " + "numbers to be 0 to " + (layerwise.size() - 1) - + " inclusive (number of layers defined: " + layerwise.size() + ")"); + + " not specified. Expect layer " + "numbers to be 0 to " + (layerwise.size() - 1) + + " inclusive (number of layers defined: " + layerwise.size() + ")"); } if (layerwise.get(i).getLayer() == null) throw new IllegalStateException("Cannot construct network: Layer config for" + "layer with index " - + i + " is not defined)"); + + i + " is not defined)"); //Layer names: set to default, if not set if (layerwise.get(i).getLayer().getLayerName() == null) { @@ -248,12 +325,12 @@ public class NeuralNetConfiguration implements Serializable, Cloneable { return new MultiLayerConfiguration.Builder().inputPreProcessors(inputPreProcessors) - .backpropType(backpropType).tBPTTForwardLength(tbpttFwdLength) - .tBPTTBackwardLength(tbpttBackLength).setInputType(this.inputType) - .trainingWorkspaceMode(wsmTrain).cacheMode(globalConfig.cacheMode) - .inferenceWorkspaceMode(wsmTest).confs(list).validateOutputLayerConfig(validateOutputConfig) - .dataType(globalConfig.dataType) - .build(); + .backpropType(backpropType).tBPTTForwardLength(tbpttFwdLength) + .tBPTTBackwardLength(tbpttBackLength).setInputType(this.inputType) + .trainingWorkspaceMode(wsmTrain).cacheMode(globalConfig.cacheMode) + .inferenceWorkspaceMode(wsmTest).confs(list).validateOutputLayerConfig(validateOutputConfig) + .dataType(globalConfig.dataType) + .build(); } /** Helper class for setting input types */ @@ -651,7 +728,7 @@ public class NeuralNetConfiguration implements Serializable, Cloneable { */ public Builder weightInit(WeightInit weightInit) { if(weightInit == WeightInit.DISTRIBUTION) { - // throw new UnsupportedOperationException("Not supported!, Use weightInit(Distribution distribution) instead!"); + // throw new UnsupportedOperationException("Not supported!, Use weightInit(Distribution distribution) instead!"); } this.weightInitFn = weightInit.getWeightInitFunction();
['deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/conf/NeuralNetConfiguration.java']
{'.java': 1}
1
1
0
0
1
25,717,732
5,619,856
662,540
3,972
4,093
775
97
1
997
98
216
26
0
1
1970-01-01T00:27:07
13,099
Java
{'Java': 42895752, 'C++': 17237193, 'Cuda': 2203734, 'Kotlin': 2030453, 'JavaScript': 296767, 'C': 172853, 'CMake': 126415, 'Shell': 96643, 'TypeScript': 81217, 'Python': 77566, 'FreeMarker': 77257, 'HTML': 18609, 'CSS': 12974, 'PureBasic': 12254, 'Cython': 12094, 'Ruby': 4558, 'Batchfile': 1458, 'Scala': 1026, 'Smarty': 975, 'Starlark': 931}
Apache License 2.0
9,726
deeplearning4j/deeplearning4j/9400/9393
deeplearning4j
deeplearning4j
https://github.com/deeplearning4j/deeplearning4j/issues/9393
https://github.com/deeplearning4j/deeplearning4j/pull/9400
https://github.com/deeplearning4j/deeplearning4j/pull/9400
1
fixes
INDArray.match(Number, Condition) not returning expected results.
**Expected behavior:** `array.match(n, Conditions.equals())` should return a mask such that each entry `mask.get(i)` is `array[i] == n` **Encountered behavior:** the mask contains incorrect booleans for anything but `n=0`. #### Version Information Please indicate relevant versions, including, if relevant: * nd4j version beta 7. * Platform information (OS, etc): Windows 10 Enterprise #### To reproduce: The following code will reproduce the error for `i > 0`: int[] assignments = {0,0,0,1,0,2,2}; int[] indexes = {0,1,2,3,4,5,7}; INDArray asarray = Nd4j.createFromArray(assignments); INDArray idxarray = Nd4j.createFromArray(indexes); int i = 1; INDArray mask = asarray.match(i, Conditions.equals()); - `i=1` results in the mask ` [ false, false, false, true, false, true, true]` - `i=2` results in the mask ` [ false, false, false, false, false, false, false]` There seem to be similar problems with `notEquals()` and `notEquals(someNumber)`. Everything is inverted or totally incorrect. #### Contributing I would love to contribute, but might need guidance.
a7a123592854e34f039dcff40c2c0000b1dfb809
e8d92d25341a4e6c9a83fc54a170f55abdadb704
https://github.com/deeplearning4j/deeplearning4j/compare/a7a123592854e34f039dcff40c2c0000b1dfb809...e8d92d25341a4e6c9a83fc54a170f55abdadb704
diff --git a/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ndarray/BaseNDArray.java b/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ndarray/BaseNDArray.java index c3594696d5..98bf9d16e5 100644 --- a/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ndarray/BaseNDArray.java +++ b/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ndarray/BaseNDArray.java @@ -1889,7 +1889,9 @@ public abstract class BaseNDArray implements INDArray, Iterable { @Override public INDArray match(Number comp, Condition condition) { - return Nd4j.getExecutioner().exec(new MatchConditionTransform(this,comp.doubleValue(), condition)); + //override the value so the value gets parsed properly + condition.setValue(comp); + return Nd4j.getExecutioner().exec(new MatchConditionTransform(this, EPS_THRESHOLD, condition)); } @Override diff --git a/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ops/impl/transforms/bool/MatchConditionTransform.java b/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ops/impl/transforms/bool/MatchConditionTransform.java index 2ae0e0c0f5..7a94c3fd22 100644 --- a/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ops/impl/transforms/bool/MatchConditionTransform.java +++ b/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ops/impl/transforms/bool/MatchConditionTransform.java @@ -45,7 +45,7 @@ public class MatchConditionTransform extends BaseTransformBoolOp { this.compare = condition.getValue(); this.mode = condition.condtionNum(); this.eps = Nd4j.EPS_THRESHOLD; - this.extraArgs = new Object[] {compare, eps, (double) mode}; + this.extraArgs = new Object[] {compare,1.0, eps, mode}; } public MatchConditionTransform() {} @@ -70,7 +70,7 @@ public class MatchConditionTransform extends BaseTransformBoolOp { this.mode = condition.condtionNum(); this.eps = eps; - this.extraArgs = new Object[] {compare, eps, (double) mode}; + this.extraArgs = new Object[] {compare, eps, mode}; } public MatchConditionTransform(INDArray x, double eps, @NonNull Condition condition) { diff --git a/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/BaseCondition.java b/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/BaseCondition.java index 0b5b619a67..207cfc9d3f 100644 --- a/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/BaseCondition.java +++ b/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/BaseCondition.java @@ -29,6 +29,11 @@ public abstract class BaseCondition implements Condition { this.value = value; } + @Override + public void setValue(Number value) { + this.value = value; + } + @Override public double epsThreshold() { return Nd4j.EPS_THRESHOLD; diff --git a/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/Condition.java b/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/Condition.java index 7f92450f38..acfc47b9d6 100644 --- a/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/Condition.java +++ b/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/Condition.java @@ -21,9 +21,47 @@ package org.nd4j.linalg.indexing.conditions; import org.nd4j.common.function.Function; - +/** + * + * Sets a condition in correspondence with the MatchConditionalBool op + * (op num 5 in the legacy operations) + * + * Condition number is affected by the ops internals, see here for the comprehensive overview: + * https://github.com/eclipse/deeplearning4j/blob/master/libnd4j/include/ops/ops.h#L2253 + * + * As of this writing (July 27,2021), the following operations are relevant: + * 0: equals + * 1: not equals + * 2: less than + * 3: greater than + * 4: less than or equal + * 5: greater than or equal + * 6: absolute difference less than + * 7: absolute difference greater than + * 8: is infinite + * 9: is nan + * 10: absolute equals + * 11: not equals + * 12: absolute difference greater or equal to + * 13: absolute difference less than or equal to + * 14: is finite + * 15: is infinite + * + * @return + */ public interface Condition extends Function<Number, Boolean> { + /** + * Allows overriding of the value. + * + * @param value + */ + default void setValue(Number value) { + //no-op for aggregate conditions. Mainly used for providing an api to end users such as: + //INDArray.match(input,Conditions.equals()) + //See: https://github.com/eclipse/deeplearning4j/issues/9393 + } + /** * Returns condition ID for native side * diff --git a/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/ConditionEquals.java b/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/ConditionEquals.java index cd8e78b873..edbc1368a4 100644 --- a/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/ConditionEquals.java +++ b/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/ConditionEquals.java @@ -28,6 +28,7 @@ public class ConditionEquals implements Condition { this.conditions = conditions; } + /** * Returns condition ID for native side * diff --git a/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/EqualsCondition.java b/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/EqualsCondition.java index a535f807ea..bceb885beb 100644 --- a/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/EqualsCondition.java +++ b/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/EqualsCondition.java @@ -38,12 +38,14 @@ public class EqualsCondition extends BaseCondition { /** * Returns condition ID for native side + * Condition number is affected by: + * https://github.com/eclipse/deeplearning4j/blob/0ba0f933a95d2dceeff3651bc540d03b5f3b1631/libnd4j/include/ops/ops.h#L2253 * * @return */ @Override public int condtionNum() { - return 10; + return 0; } @Override diff --git a/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/Not.java b/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/Not.java index db6cfd6a70..9e911c0e03 100644 --- a/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/Not.java +++ b/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/Not.java @@ -24,6 +24,7 @@ public class Not implements Condition { private Condition opposite; + /** * Returns condition ID for native side * diff --git a/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/Or.java b/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/Or.java index 6c1f6adeed..65ae169ae2 100644 --- a/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/Or.java +++ b/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/Or.java @@ -28,6 +28,7 @@ public class Or implements Condition { this.conditions = conditions; } + /** * Returns condition ID for native side * diff --git a/nd4j/nd4j-backends/nd4j-backend-impls/nd4j-native/src/main/java/org/nd4j/linalg/cpu/nativecpu/ops/NativeOpExecutioner.java b/nd4j/nd4j-backends/nd4j-backend-impls/nd4j-native/src/main/java/org/nd4j/linalg/cpu/nativecpu/ops/NativeOpExecutioner.java index bec01aa6ee..7c204de133 100644 --- a/nd4j/nd4j-backends/nd4j-backend-impls/nd4j-native/src/main/java/org/nd4j/linalg/cpu/nativecpu/ops/NativeOpExecutioner.java +++ b/nd4j/nd4j-backends/nd4j-backend-impls/nd4j-native/src/main/java/org/nd4j/linalg/cpu/nativecpu/ops/NativeOpExecutioner.java @@ -819,6 +819,8 @@ public class NativeOpExecutioner extends DefaultOpExecutioner { case TRANSFORM_FLOAT: { val xtraz = getPointerForExtraArgs(op, z.dataType()); + + loop.execTransformFloat(dummy, op.opNum(), xb, (LongPointer) x.shapeInfoDataBuffer().addressPointer(), null, zb, (LongPointer) z.shapeInfoDataBuffer().addressPointer(), diff --git a/nd4j/nd4j-backends/nd4j-backend-impls/nd4j-native/src/main/java/org/nd4j/nativeblas/Nd4jCpu.java b/nd4j/nd4j-backends/nd4j-backend-impls/nd4j-native/src/main/java/org/nd4j/nativeblas/Nd4jCpu.java index 4b6cd2b079..750c024a98 100644 --- a/nd4j/nd4j-backends/nd4j-backend-impls/nd4j-native/src/main/java/org/nd4j/nativeblas/Nd4jCpu.java +++ b/nd4j/nd4j-backends/nd4j-backend-impls/nd4j-native/src/main/java/org/nd4j/nativeblas/Nd4jCpu.java @@ -3392,9 +3392,6 @@ public native int getRandomGeneratorRelativeInt(OpaqueRandomGenerator ptr, @Cast public native @Cast("Nd4jLong") long getRandomGeneratorRelativeLong(OpaqueRandomGenerator ptr, @Cast("Nd4jLong") long index); public native void deleteRandomGenerator(OpaqueRandomGenerator ptr); -public native @Cast("char*") String runLightBenchmarkSuit(@Cast("bool") boolean printOut); -public native @Cast("char*") String runFullBenchmarkSuit(@Cast("bool") boolean printOut); - public native OpaqueLaunchContext defaultLaunchContext(); public native @Cast("Nd4jPointer") Pointer lcScalarPointer(OpaqueLaunchContext lc); public native @Cast("Nd4jPointer") Pointer lcReductionPointer(OpaqueLaunchContext lc); diff --git a/nd4j/nd4j-backends/nd4j-tests/src/test/java/org/nd4j/linalg/custom/CustomOpsTests.java b/nd4j/nd4j-backends/nd4j-tests/src/test/java/org/nd4j/linalg/custom/CustomOpsTests.java index 4bc2de4b21..35a6bc66d3 100644 --- a/nd4j/nd4j-backends/nd4j-tests/src/test/java/org/nd4j/linalg/custom/CustomOpsTests.java +++ b/nd4j/nd4j-backends/nd4j-tests/src/test/java/org/nd4j/linalg/custom/CustomOpsTests.java @@ -1497,6 +1497,30 @@ public class CustomOpsTests extends BaseNd4jTestWithBackends { assertEquals(exp, z); } + @ParameterizedTest + @MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs") + public void testMatch_2(Nd4jBackend backend) { + int[] assignments = {0,0,0,1,0,2,2}; + int[] indexes = {0,1,2,3,4,5,7}; + + INDArray asarray = Nd4j.createFromArray(assignments); + INDArray idxarray = Nd4j.createFromArray(indexes); + + int[] testIndicesForMask = new int[] {1,2}; + INDArray[] assertions = { + Nd4j.createFromArray(false,false,false,true,false,false,false), + Nd4j.createFromArray(false,false,false,false,false,true,true) + }; + + for(int j = 0; j < testIndicesForMask.length; j++) { + INDArray mask = asarray.match(testIndicesForMask[j], Conditions.equals()); + assertEquals(assertions[j],mask); + + } + + } + + @ParameterizedTest @MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
['nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/ConditionEquals.java', 'nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ndarray/BaseNDArray.java', 'nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/EqualsCondition.java', 'nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/Not.java', 'nd4j/nd4j-backends/nd4j-backend-impls/nd4j-native/src/main/java/org/nd4j/linalg/cpu/nativecpu/ops/NativeOpExecutioner.java', 'nd4j/nd4j-backends/nd4j-tests/src/test/java/org/nd4j/linalg/custom/CustomOpsTests.java', 'nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/BaseCondition.java', 'nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ops/impl/transforms/bool/MatchConditionTransform.java', 'nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/Or.java', 'nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/indexing/conditions/Condition.java', 'nd4j/nd4j-backends/nd4j-backend-impls/nd4j-native/src/main/java/org/nd4j/nativeblas/Nd4jCpu.java']
{'.java': 11}
11
11
0
0
11
25,716,424
5,619,489
662,491
3,972
2,257
585
65
10
1,173
147
305
38
0
0
1970-01-01T00:27:07
13,099
Java
{'Java': 42895752, 'C++': 17237193, 'Cuda': 2203734, 'Kotlin': 2030453, 'JavaScript': 296767, 'C': 172853, 'CMake': 126415, 'Shell': 96643, 'TypeScript': 81217, 'Python': 77566, 'FreeMarker': 77257, 'HTML': 18609, 'CSS': 12974, 'PureBasic': 12254, 'Cython': 12094, 'Ruby': 4558, 'Batchfile': 1458, 'Scala': 1026, 'Smarty': 975, 'Starlark': 931}
Apache License 2.0
9,737
deeplearning4j/deeplearning4j/4795/4792
deeplearning4j
deeplearning4j
https://github.com/deeplearning4j/deeplearning4j/issues/4792
https://github.com/deeplearning4j/deeplearning4j/pull/4795
https://github.com/deeplearning4j/deeplearning4j/pull/4795
1
fix
MNIST downloader *still* doesn't reliably handle download errors
Even with multiple passes on it, MNIST downloader *still* manages to not automatically handle download issues :/ Here's output (test failure) from most recent run of MnistFetcherTest.testMnistDataFetcher - master versions of codebase all round: ``` java.io.EOFException: Unexpected end of ZLIB input stream at java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:240) at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158) at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:117) at java.io.FilterInputStream.read(FilterInputStream.java:107) at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1792) at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1769) at org.nd4j.util.ArchiveUtils.unzipFileTo(ArchiveUtils.java:131) at org.deeplearning4j.base.MnistFetcher.downloadAndUntar(MnistFetcher.java:159) at org.deeplearning4j.base.MnistFetcherTest.testMnistDataFetcher(MnistFetcherTest.java:51) ```
4f61de3511c6ff5a4902eb57cddde59f2beba5d8
a1ba8ac48b4ccf87ccf41dfa27a36bcbc0d54767
https://github.com/deeplearning4j/deeplearning4j/compare/4f61de3511c6ff5a4902eb57cddde59f2beba5d8...a1ba8ac48b4ccf87ccf41dfa27a36bcbc0d54767
diff --git a/deeplearning4j-core/src/main/java/org/deeplearning4j/base/MnistFetcher.java b/deeplearning4j-core/src/main/java/org/deeplearning4j/base/MnistFetcher.java index 30187ad22e..d2a502ea04 100755 --- a/deeplearning4j-core/src/main/java/org/deeplearning4j/base/MnistFetcher.java +++ b/deeplearning4j-core/src/main/java/org/deeplearning4j/base/MnistFetcher.java @@ -149,47 +149,50 @@ public class MnistFetcher { } log.info("Downloading {}...", getName()); - // getFromOrigin training records - File tarFile = new File(baseDir, getTrainingFilesFilename()); - File testFileLabels = new File(baseDir, getTestFilesFilename()); + // get features + File trainFeatures = new File(baseDir, getTrainingFilesFilename()); + File testFeatures = new File(baseDir, getTestFilesFilename()); - tryDownloadingAFewTimes(new URL(getTrainingFilesURL()), tarFile, getTrainingFilesMD5()); - tryDownloadingAFewTimes(new URL(getTestFilesURL()), testFileLabels, getTestFilesMD5()); + downloadAndExtract(new URL(getTrainingFilesURL()), trainFeatures, baseDir, getTrainingFilesMD5()); + downloadAndExtract(new URL(getTestFilesURL()), testFeatures, baseDir, getTestFilesMD5()); - ArchiveUtils.unzipFileTo(tarFile.getAbsolutePath(), baseDir.getAbsolutePath()); - ArchiveUtils.unzipFileTo(testFileLabels.getAbsolutePath(), baseDir.getAbsolutePath()); + // get labels + File trainLabels = new File(baseDir, getTrainingFileLabelsFilename()); + File testLabels = new File(baseDir, getTestFileLabelsFilename()); - // getFromOrigin training records - File labels = new File(baseDir, getTrainingFileLabelsFilename()); - File labelsTest = new File(baseDir, getTestFileLabelsFilename()); - - tryDownloadingAFewTimes(new URL(getTrainingFileLabelsURL()), labels, getTrainingFileLabelsMD5()); - tryDownloadingAFewTimes(new URL(getTestFileLabelsURL()), labelsTest, getTestFileLabelsMD5()); - - ArchiveUtils.unzipFileTo(labels.getAbsolutePath(), baseDir.getAbsolutePath()); - ArchiveUtils.unzipFileTo(labelsTest.getAbsolutePath(), baseDir.getAbsolutePath()); + downloadAndExtract(new URL(getTrainingFileLabelsURL()), trainLabels, baseDir, getTrainingFileLabelsMD5()); + downloadAndExtract(new URL(getTestFileLabelsURL()), testLabels, baseDir, getTestFileLabelsMD5()); fileDir = baseDir; return fileDir; } - private void tryDownloadingAFewTimes(URL url, File f, String targetMD5) throws IOException { - tryDownloadingAFewTimes(0, url, f, targetMD5); + private void downloadAndExtract(URL url, File f, File extractToDir, String targetMD5) throws IOException { + downloadAndExtract(0, url, f, extractToDir, targetMD5); } - private void tryDownloadingAFewTimes(int attempt, URL url, File f, String targetMD5) throws IOException { + private void downloadAndExtract(int attempt, URL url, File f, File extractToDir, String targetMD5) throws IOException { int maxTries = 3; - boolean isCorrectFile = f.isFile(); - if (attempt < maxTries && !isCorrectFile) { - FileUtils.copyURLToFile(url, f); - if (!checkMD5OfFile(targetMD5, f)) { + boolean isCorrectFile = f.exists() && f.isFile() && checkMD5OfFile(targetMD5, f); + if (attempt < maxTries) { + if(!isCorrectFile) { + FileUtils.copyURLToFile(url, f); + if (!checkMD5OfFile(targetMD5, f)) { + f.delete(); + downloadAndExtract(attempt + 1, url, f, extractToDir, targetMD5); + } + } + // try extracting + try{ + ArchiveUtils.unzipFileTo(f.getAbsolutePath(), extractToDir.getAbsolutePath()); + } catch (Throwable t){ + log.warn("Error extracting MNIST files from file {} - retrying...", f.getAbsolutePath(), t); f.delete(); - tryDownloadingAFewTimes(attempt + 1, url, f, targetMD5); + downloadAndExtract(attempt + 1, url, f, extractToDir, targetMD5); } - } else if (isCorrectFile) { - // do nothing, file downloaded - } else { - throw new IOException("Could not download " + url.getPath() + "\\n properly despite trying " + maxTries + } else if (!isCorrectFile) { + //Too many attempts + throw new IOException("Could not download and extract " + url.getPath() + "\\n properly despite trying " + maxTries + " times, check your connection. File info:" + "\\nTarget MD5: " + targetMD5 + "\\nHash matches: " + checkMD5OfFile(targetMD5, f) + "\\nIs valid file: " + f.isFile()); } diff --git a/deeplearning4j-core/src/main/java/org/deeplearning4j/datasets/fetchers/MnistDataFetcher.java b/deeplearning4j-core/src/main/java/org/deeplearning4j/datasets/fetchers/MnistDataFetcher.java index 93dbbb6b73..22a143fedc 100755 --- a/deeplearning4j-core/src/main/java/org/deeplearning4j/datasets/fetchers/MnistDataFetcher.java +++ b/deeplearning4j-core/src/main/java/org/deeplearning4j/datasets/fetchers/MnistDataFetcher.java @@ -163,7 +163,7 @@ public class MnistDataFetcher extends BaseDataFetcher { @Override public void fetch(int numExamples) { if (!hasMore()) { - throw new IllegalStateException("Unable to getFromOrigin more; there are no more images"); + throw new IllegalStateException("Unable to get more; there are no more images"); } float[][] featureData = new float[numExamples][0]; diff --git a/deeplearning4j-nearestneighbors-parent/nearestneighbor-core/src/main/java/org/deeplearning4j/clustering/util/MathUtils.java b/deeplearning4j-nearestneighbors-parent/nearestneighbor-core/src/main/java/org/deeplearning4j/clustering/util/MathUtils.java index 3622d4dc20..0bd6c3d082 100755 --- a/deeplearning4j-nearestneighbors-parent/nearestneighbor-core/src/main/java/org/deeplearning4j/clustering/util/MathUtils.java +++ b/deeplearning4j-nearestneighbors-parent/nearestneighbor-core/src/main/java/org/deeplearning4j/clustering/util/MathUtils.java @@ -89,7 +89,7 @@ public class MathUtils { /** * See: http://stackoverflow.com/questions/466204/rounding-off-to-nearest-power-of-2 - * @param v the number to getFromOrigin the next power of 2 for + * @param v the number to get the next power of 2 for * @return the next power of 2 for the passed in value */ public static long nextPowOf2(long v) { @@ -364,7 +364,7 @@ public class MathUtils { * This returns the minimized loss values for a given vector. * It is assumed that the x, y pairs are at * vector[i], vector[i+1] - * @param vector the vector of numbers to getFromOrigin the weights for + * @param vector the vector of numbers to get the weights for * @return a double array with w_0 and w_1 are the associated indices. */ public static double[] weightsFor(List<Double> vector) { @@ -430,7 +430,7 @@ public class MathUtils { * This returns the minimized loss values for a given vector. * It is assumed that the x, y pairs are at * vector[i], vector[i+1] - * @param vector the vector of numbers to getFromOrigin the weights for + * @param vector the vector of numbers to get the weights for * @return a double array with w_0 and w_1 are the associated indices. */ public static double[] weightsFor(double[] vector) { @@ -544,7 +544,7 @@ public class MathUtils { /** * This returns the given column over an n arrays - * @param column the column to getFromOrigin values for + * @param column the column to get values for * @param nums the arrays to extract values from * @return a double array containing all of the numbers in that column * for all of the arrays. @@ -668,7 +668,7 @@ public class MathUtils { /** * This returns the x values of the given vector. * These are assumed to be the even values of the vector. - * @param vector the vector to getFromOrigin the values for + * @param vector the vector to get the values for * @return the x values of the given vector */ public static double[] xVals(double[] vector) { @@ -767,7 +767,7 @@ public class MathUtils { /** * This returns the entropy (information gain, or uncertainty of a random variable). - * @param vector the vector of values to getFromOrigin the entropy for + * @param vector the vector of values to get the entropy for * @return the entropy of the given vector */ public static double entropy(double[] vector) { @@ -875,7 +875,7 @@ public class MathUtils { /** * This returns the entropy for a given vector of probabilities. - * @param probabilities the probabilities to getFromOrigin the entropy for + * @param probabilities the probabilities to get the entropy for * @return the entropy of the given probabilities. */ public static double information(double[] probabilities) { @@ -912,7 +912,7 @@ public class MathUtils { /** * This will return the factorial of the given number n. - * @param n the number to getFromOrigin the factorial for + * @param n the number to get the factorial for * @return the factorial for this number */ public static double factorial(double n) { diff --git a/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/datasets/loader/ReutersNewsGroupsLoader.java b/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/datasets/loader/ReutersNewsGroupsLoader.java deleted file mode 100755 index 2f2342e50e..0000000000 --- a/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/datasets/loader/ReutersNewsGroupsLoader.java +++ /dev/null @@ -1,98 +0,0 @@ -/*- - * - * * Copyright 2015 Skymind,Inc. - * * - * * Licensed 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.deeplearning4j.datasets.loader; - -/** - * @author Adam Gibson - */ -// public class ReutersNewsGroupsLoader extends BaseDataFetcher { - -// private TextVectorizer textVectorizer; -// private boolean tfidf; -// public final static String NEWSGROUP_URL = "http://qwone.com/~jason/20Newsgroups/20news-18828.tar.gz"; -// private File reutersRootDir; -// private static final Logger log = LoggerFactory.getLogger(ReutersNewsGroupsLoader.class); -// private DataSet load; - - -// public ReutersNewsGroupsLoader(boolean tfidf) throws Exception { -// getIfNotExists(); -// LabelAwareSentenceIterator iter = new LabelAwareFileSentenceIterator(reutersRootDir); -// List<String> labels =new ArrayList<>(); -// for(File f : reutersRootDir.listFiles()) { -// if(f.isDirectory()) -// labels.add(f.getName()); -// } -// TokenizerFactory tokenizerFactory = new UimaTokenizerFactory(); - -// if(tfidf) -// this.textVectorizer = new TfidfVectorizer.Builder() -// .iterate(iter).labels(labels).tokenize(tokenizerFactory).build(); - -// else -// this.textVectorizer = new BagOfWordsVectorizer.Builder() -// .iterate(iter).labels(labels).tokenize(tokenizerFactory).build(); - -// load = this.textVectorizer.vectorize(); -// } - -// private void getIfNotExists() throws Exception { -// String home = System.getProperty("user.home"); -// String rootDir = home + File.separator + "reuters"; -// reutersRootDir = new File(rootDir); -// if(!reutersRootDir.exists()) -// reutersRootDir.mkdir(); -// else if(reutersRootDir.exists()) -// return; - - -// File rootTarFile = new File(reutersRootDir,"20news-18828.tar.gz"); -// if(rootTarFile.exists()) -// rootTarFile.delete(); -// rootTarFile.createNewFile(); - -// FileUtils.copyURLToFile(new URL(NEWSGROUP_URL), rootTarFile); -// ArchiveUtils.unzipFileTo(rootTarFile.getAbsolutePath(), reutersRootDir.getAbsolutePath()); -// rootTarFile.delete(); -// FileUtils.copyDirectory(new File(reutersRootDir,"20news-18828"),reutersRootDir); -// FileUtils.deleteDirectory(new File(reutersRootDir,"20news-18828")); -// if(reutersRootDir.listFiles() == null) -// throw new IllegalStateException("No files found!"); - -// } - - -// /** -// * Fetches the next dataset. You need to call this -// * to getFromOrigin a new dataset, otherwise {@link #next()} -// * just returns the last data applyTransformToDestination fetch -// * -// * @param numExamples the number of examples to fetch -// */ -// @Override -// public void fetch(int numExamples) { -// List<DataSet> newData = new ArrayList<>(); -// for(int grabbed = 0; grabbed < numExamples && cursor < load.numExamples(); cursor++,grabbed++) { -// newData.add(load.get(cursor)); -// } - -// this.curr = DataSet.merge(newData); - -// } -// } diff --git a/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/text/movingwindow/WindowConverter.java b/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/text/movingwindow/WindowConverter.java index bc64873266..b0c69be645 100755 --- a/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/text/movingwindow/WindowConverter.java +++ b/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/text/movingwindow/WindowConverter.java @@ -48,7 +48,7 @@ public class WindowConverter { * Keep in mind each window is a multi word context. * * From there, each word uses the passed in model - * as a lookup table to getFromOrigin what vectors are relevant + * as a lookup table to get what vectors are relevant * to the passed in windows * @param window the window to take in. * @param vec the model to use as a lookup table @@ -84,7 +84,7 @@ public class WindowConverter { * Keep in mind each window is a multi word context. * * From there, each word uses the passed in model - * as a lookup table to getFromOrigin what vectors are relevant + * as a lookup table to get what vectors are relevant * to the passed in windows * @param window the window to take in. * @param vec the model to use as a lookup table diff --git a/deeplearning4j-nn/src/main/java/org/deeplearning4j/datasets/iterator/DataSetFetcher.java b/deeplearning4j-nn/src/main/java/org/deeplearning4j/datasets/iterator/DataSetFetcher.java index fa4955d68b..86fe05477d 100755 --- a/deeplearning4j-nn/src/main/java/org/deeplearning4j/datasets/iterator/DataSetFetcher.java +++ b/deeplearning4j-nn/src/main/java/org/deeplearning4j/datasets/iterator/DataSetFetcher.java @@ -47,7 +47,7 @@ public interface DataSetFetcher extends Serializable { /** * Fetches the next dataset. You need to call this - * to getFromOrigin a new dataset, otherwise {@link #next()} + * to get a new dataset, otherwise {@link #next()} * just returns the last data applyTransformToDestination fetch * @param numExamples the number of examples to fetch */ diff --git a/deeplearning4j-nn/src/main/java/org/deeplearning4j/datasets/iterator/impl/MovingWindowDataSetFetcher.java b/deeplearning4j-nn/src/main/java/org/deeplearning4j/datasets/iterator/impl/MovingWindowDataSetFetcher.java index 79c292a9e4..08571a5752 100644 --- a/deeplearning4j-nn/src/main/java/org/deeplearning4j/datasets/iterator/impl/MovingWindowDataSetFetcher.java +++ b/deeplearning4j-nn/src/main/java/org/deeplearning4j/datasets/iterator/impl/MovingWindowDataSetFetcher.java @@ -64,7 +64,7 @@ public class MovingWindowDataSetFetcher extends BaseDataFetcher { /** * Fetches the next dataset. You need to call this - * to getFromOrigin a new dataset, otherwise {@link #next()} + * to get a new dataset, otherwise {@link #next()} * just returns the last data applyTransformToDestination fetch * * @param numExamples the number of examples to fetch diff --git a/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/feedforward/autoencoder/recursive/Tree.java b/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/feedforward/autoencoder/recursive/Tree.java index 7a06599184..200ef06759 100644 --- a/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/feedforward/autoencoder/recursive/Tree.java +++ b/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/feedforward/autoencoder/recursive/Tree.java @@ -204,7 +204,7 @@ public class Tree implements Serializable { /** * Returns the distance between this node * and the specified subnode - * @param node the node to getFromOrigin the distance from + * @param node the node to get the distance from * @return the distance between the 2 nodes */ public int depth(Tree node) { diff --git a/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/multilayer/MultiLayerNetwork.java b/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/multilayer/MultiLayerNetwork.java index 435c1fc8ca..f594bc4754 100755 --- a/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/multilayer/MultiLayerNetwork.java +++ b/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/multilayer/MultiLayerNetwork.java @@ -2169,7 +2169,7 @@ public class MultiLayerNetwork implements Serializable, Classifier, Layer, Neura * Assigns the parameters of this model to the ones specified by this * network. This is used in loading from input streams, factory methods, etc * - * @param network the network to getFromOrigin parameters from + * @param network the network to get parameters from */ public void update(MultiLayerNetwork network) { this.defaultConfiguration = diff --git a/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/Dl4jReflection.java b/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/Dl4jReflection.java index 5cbff31c42..b403aeb07b 100755 --- a/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/Dl4jReflection.java +++ b/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/Dl4jReflection.java @@ -35,7 +35,7 @@ public class Dl4jReflection { /** * Gets the empty constructor from a class - * @param clazz the class to getFromOrigin the constructor from + * @param clazz the class to get the constructor from * @return the empty constructor for the class */ public static Constructor<?> getEmptyConstructor(Class<?> clazz) { diff --git a/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/StringGrid.java b/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/StringGrid.java index 55199ddac4..066dde28f0 100755 --- a/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/StringGrid.java +++ b/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/StringGrid.java @@ -350,7 +350,7 @@ public class StringGrid extends ArrayList<List<String>> { //wtf is wrong with you people? if (chosenKey == null) { - //getFromOrigin the max value of the cluster + //get the max value of the cluster String max2 = maximalValue(cluster); StringTokenizer val = new StringTokenizer(max2); List<String> list = new ArrayList<>(); diff --git a/deeplearning4j-scaleout/deeplearning4j-aws/src/main/java/org/deeplearning4j/aws/ec2/provision/ClusterSetup.java b/deeplearning4j-scaleout/deeplearning4j-aws/src/main/java/org/deeplearning4j/aws/ec2/provision/ClusterSetup.java index 975112576f..eac5798bb9 100755 --- a/deeplearning4j-scaleout/deeplearning4j-aws/src/main/java/org/deeplearning4j/aws/ec2/provision/ClusterSetup.java +++ b/deeplearning4j-scaleout/deeplearning4j-aws/src/main/java/org/deeplearning4j/aws/ec2/provision/ClusterSetup.java @@ -81,7 +81,7 @@ public class ClusterSetup { boxCreator.create(); boxCreator.blockTillAllRunning(); List<String> hosts = boxCreator.getHosts(); - //provisionMaster(hosts.getFromOrigin(0)); + //provisionMaster(hosts.get(0)); provisionWorkers(hosts); diff --git a/deeplearning4j-scaleout/deeplearning4j-aws/src/main/java/org/deeplearning4j/aws/s3/reader/S3Downloader.java b/deeplearning4j-scaleout/deeplearning4j-aws/src/main/java/org/deeplearning4j/aws/s3/reader/S3Downloader.java index 213503e462..1f55d66e2a 100755 --- a/deeplearning4j-scaleout/deeplearning4j-aws/src/main/java/org/deeplearning4j/aws/s3/reader/S3Downloader.java +++ b/deeplearning4j-scaleout/deeplearning4j-aws/src/main/java/org/deeplearning4j/aws/s3/reader/S3Downloader.java @@ -86,7 +86,7 @@ public class S3Downloader extends BaseS3 { /** * Iterator style one list at a time - * @param list the list to getFromOrigin the next batch for + * @param list the list to get the next batch for * @return the next batch of objects or null if * none are left */
['deeplearning4j-nn/src/main/java/org/deeplearning4j/util/Dl4jReflection.java', 'deeplearning4j-nn/src/main/java/org/deeplearning4j/util/StringGrid.java', 'deeplearning4j-scaleout/deeplearning4j-aws/src/main/java/org/deeplearning4j/aws/s3/reader/S3Downloader.java', 'deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/feedforward/autoencoder/recursive/Tree.java', 'deeplearning4j-core/src/main/java/org/deeplearning4j/datasets/fetchers/MnistDataFetcher.java', 'deeplearning4j-scaleout/deeplearning4j-aws/src/main/java/org/deeplearning4j/aws/ec2/provision/ClusterSetup.java', 'deeplearning4j-nearestneighbors-parent/nearestneighbor-core/src/main/java/org/deeplearning4j/clustering/util/MathUtils.java', 'deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/multilayer/MultiLayerNetwork.java', 'deeplearning4j-core/src/main/java/org/deeplearning4j/base/MnistFetcher.java', 'deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/text/movingwindow/WindowConverter.java', 'deeplearning4j-nn/src/main/java/org/deeplearning4j/datasets/iterator/impl/MovingWindowDataSetFetcher.java', 'deeplearning4j-nn/src/main/java/org/deeplearning4j/datasets/iterator/DataSetFetcher.java', 'deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/datasets/loader/ReutersNewsGroupsLoader.java']
{'.java': 13}
13
13
0
0
13
7,801,053
1,690,593
213,511
1,369
10,267
2,258
195
13
966
61
226
16
0
1
1970-01-01T00:25:20
13,099
Java
{'Java': 42895752, 'C++': 17237193, 'Cuda': 2203734, 'Kotlin': 2030453, 'JavaScript': 296767, 'C': 172853, 'CMake': 126415, 'Shell': 96643, 'TypeScript': 81217, 'Python': 77566, 'FreeMarker': 77257, 'HTML': 18609, 'CSS': 12974, 'PureBasic': 12254, 'Cython': 12094, 'Ruby': 4558, 'Batchfile': 1458, 'Scala': 1026, 'Smarty': 975, 'Starlark': 931}
Apache License 2.0
9,727
deeplearning4j/deeplearning4j/9353/9349
deeplearning4j
deeplearning4j
https://github.com/deeplearning4j/deeplearning4j/issues/9349
https://github.com/deeplearning4j/deeplearning4j/pull/9353
https://github.com/deeplearning4j/deeplearning4j/pull/9353
1
fixes
M1: Parameters of Keras MaxPooling1D layer are incorrectly read
#### Issue Description I trained a model using Tensorflow/Keras version 2.4.1 in Python. This model contains a MaxPooling1D layer. I then saved the model as the (default) .hdf5 file. Loading this file in Keras and saving its config as json, reveals the following layer: ``` json { "class_name": "MaxPooling1D", "config": { "name": "max_pooling1d_3", "trainable": true, "dtype": "float32", "strides": [ 836 ], "pool_size": [ 836 ], "padding": "valid", "data_format": "channels_last" }, "name": "max_pooling1d_3", "inbound_nodes": [ [ [ "conv1d_3", 0, 0, {} ] ] ] }, ``` Please note that the **data_format** is set to "channels_last" which is the default value in Keras. This corresponds to NHWC. The stride is loaded as `(836,)` in Keras - a 1-tuple holding only the value (836). If I now load the model in 1.0.0-M1 using `importKerasModelAndWeights()`, this specific layer is loaded as a `Subsampling1DLayer`. Unfortunately, the parameter values are incorrectly parsed. The `Cnn2dDataFormat` is set to `NCHW`. The stride is loaded as `[836,2]` which leads to incorrect dimensions in the following layer. I believe that `[836,1]` is the correct value for the stride. When I overwrite these two parameter values in my loaded network, then everything runs as expected. #### Version Information Please indicate relevant versions, including, if relevant: * Deeplearning4j version: 1.0.0-M1 * Tensorflow version 2.4.1 (same error exists for models trained in Tensorflow 1.14) * Platform information: Ubuntu 20.04
9026d172ac882f861a03ac1ff57ee6d8ce4535d9
f446c74bf4e90f6447be8f98ea1a81f882fd82b5
https://github.com/deeplearning4j/deeplearning4j/compare/9026d172ac882f861a03ac1ff57ee6d8ce4535d9...f446c74bf4e90f6447be8f98ea1a81f882fd82b5
diff --git a/deeplearning4j/deeplearning4j-core/src/test/java/org/deeplearning4j/nn/layers/HelperUtilsTest.java b/deeplearning4j/deeplearning4j-core/src/test/java/org/deeplearning4j/nn/layers/HelperUtilsTest.java index 71f01b0235..81de2dae85 100644 --- a/deeplearning4j/deeplearning4j-core/src/test/java/org/deeplearning4j/nn/layers/HelperUtilsTest.java +++ b/deeplearning4j/deeplearning4j-core/src/test/java/org/deeplearning4j/nn/layers/HelperUtilsTest.java @@ -57,6 +57,7 @@ import org.nd4j.linalg.lossfunctions.LossFunctions; import java.util.List; +import static org.deeplearning4j.common.config.DL4JSystemProperties.DISABLE_HELPER_PROPERTY; import static org.junit.jupiter.api.Assertions.*; /** @@ -75,7 +76,7 @@ public class HelperUtilsTest extends BaseDL4JTest { @Test @DisplayName("Test instance creation of various helpers") public void testOneDnnHelperCreation() { - System.setProperty(HelperUtils.DISABLE_HELPER_PROPERTY,"false"); + System.setProperty(DISABLE_HELPER_PROPERTY,"false"); assertNotNull(HelperUtils.createHelper("", MKLDNNLSTMHelper.class.getName(), LSTMHelper.class,"layername",getDataType())); assertNotNull(HelperUtils.createHelper("", MKLDNNBatchNormHelper.class.getName(), diff --git a/deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/layers/pooling/KerasPooling1D.java b/deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/layers/pooling/KerasPooling1D.java index bb27e7d816..6030e5c38f 100644 --- a/deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/layers/pooling/KerasPooling1D.java +++ b/deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/layers/pooling/KerasPooling1D.java @@ -66,6 +66,7 @@ public class KerasPooling1D extends KerasLayer { Subsampling1DLayer.Builder builder = new Subsampling1DLayer.Builder( KerasPoolingUtils.mapPoolingType(this.className, conf)).name(this.layerName) .dropOut(this.dropout) + .dataFormat(dimOrder == DimOrder.TENSORFLOW ? CNN2DFormat.NHWC : CNN2DFormat.NCHW) .convolutionMode(getConvolutionModeFromConfig(layerConfig, conf)) .kernelSize(getKernelSizeFromConfig(layerConfig, 1, conf, kerasMajorVersion)[0]) .stride(getStrideFromConfig(layerConfig, 1, conf)[0]); diff --git a/deeplearning4j/deeplearning4j-modelimport/src/test/java/org/deeplearning4j/nn/modelimport/keras/layers/pooling/KerasPooling1DTest.java b/deeplearning4j/deeplearning4j-modelimport/src/test/java/org/deeplearning4j/nn/modelimport/keras/layers/pooling/KerasPooling1DTest.java index a7163d1cfb..a81a7bb7af 100644 --- a/deeplearning4j/deeplearning4j-modelimport/src/test/java/org/deeplearning4j/nn/modelimport/keras/layers/pooling/KerasPooling1DTest.java +++ b/deeplearning4j/deeplearning4j-modelimport/src/test/java/org/deeplearning4j/nn/modelimport/keras/layers/pooling/KerasPooling1DTest.java @@ -19,21 +19,31 @@ */ package org.deeplearning4j.nn.modelimport.keras.layers.pooling; +import org.deeplearning4j.nn.api.Layer; +import org.deeplearning4j.nn.conf.CNN2DFormat; import org.deeplearning4j.nn.conf.ConvolutionMode; import org.deeplearning4j.nn.conf.layers.PoolingType; import org.deeplearning4j.nn.conf.layers.Subsampling1DLayer; import org.deeplearning4j.BaseDL4JTest; +import org.deeplearning4j.nn.graph.ComputationGraph; +import org.deeplearning4j.nn.graph.vertex.GraphVertex; +import org.deeplearning4j.nn.modelimport.keras.KerasModelImport; import org.deeplearning4j.nn.modelimport.keras.config.Keras1LayerConfiguration; import org.deeplearning4j.nn.modelimport.keras.config.Keras2LayerConfiguration; import org.deeplearning4j.nn.modelimport.keras.config.KerasLayerConfiguration; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; + +import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.extension.ExtendWith; +import org.nd4j.common.resources.Resources; import org.nd4j.common.tests.tags.NativeTag; import org.nd4j.common.tests.tags.TagNames; @@ -111,4 +121,18 @@ class KerasPooling1DTest extends BaseDL4JTest { assertEquals(ConvolutionMode.Truncate, layer.getConvolutionMode()); assertEquals(VALID_PADDING[0], layer.getPadding()[0]); } + + + @Test + public void testPooling1dNWHC() throws Exception { + File file = Resources.asFile("modelimport/keras/tfkeras/issue_9349.hdf5"); + ComputationGraph computationGraph = KerasModelImport.importKerasModelAndWeights(file.getAbsolutePath()); + GraphVertex maxpooling1d = computationGraph.getVertex("max_pooling1d"); + assertNotNull(maxpooling1d); + Layer layer = maxpooling1d.getLayer(); + org.deeplearning4j.nn.layers.convolution.subsampling.Subsampling1DLayer subsampling1DLayer = (org.deeplearning4j.nn.layers.convolution.subsampling.Subsampling1DLayer) layer; + assertEquals(CNN2DFormat.NHWC,subsampling1DLayer.layerConf().getCnn2dDataFormat()); + } + + } diff --git a/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/conf/layers/SubsamplingLayer.java b/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/conf/layers/SubsamplingLayer.java index f0ebd4e7a9..91d97ff437 100644 --- a/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/conf/layers/SubsamplingLayer.java +++ b/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/conf/layers/SubsamplingLayer.java @@ -100,10 +100,12 @@ public class SubsamplingLayer extends NoParamLayer { this.stride = builder.stride; this.padding = builder.padding; this.convolutionMode = builder.convolutionMode; + this.cnn2dDataFormat = builder.cnn2DFormat; + if (builder instanceof Builder) { this.dilation = ((Builder) builder).dilation; - this.cnn2dDataFormat = ((Builder) builder).dataFormat; } + this.pnorm = builder.pnorm; this.eps = builder.eps; this.cudnnAllowFallback = builder.cudnnAllowFallback; @@ -239,7 +241,6 @@ public class SubsamplingLayer extends NoParamLayer { * Dilation for kernel */ private int[] dilation = new int[] {1, 1}; - protected CNN2DFormat dataFormat = CNN2DFormat.NCHW; public Builder(PoolingType poolingType, int[] kernelSize, int[] stride) { super(poolingType, kernelSize, stride); @@ -318,16 +319,7 @@ public class SubsamplingLayer extends NoParamLayer { return this; } - /** - * Set the data format for the CNN activations - NCHW (channels first) or NHWC (channels last). - * See {@link CNN2DFormat} for more details.<br> - * Default: NCHW - * @param format Format for activations (in and out) - */ - public Builder dataFormat(CNN2DFormat format){ - this.dataFormat = format; - return this; - } + /** * Kernel dilation. Default: {1, 1}, which is standard convolutions. Used for implementing dilated convolutions, @@ -382,7 +374,7 @@ public class SubsamplingLayer extends NoParamLayer { } public void setDataFormat(CNN2DFormat format){ - this.dataFormat = format; + this.cnn2DFormat = format; } } @@ -418,6 +410,11 @@ public class SubsamplingLayer extends NoParamLayer { protected boolean cudnnAllowFallback = true; protected boolean avgPoolIncludePadInDivisor = false; + /** + * Configure the 2d data format + */ + protected CNN2DFormat cnn2DFormat = CNN2DFormat.NCHW; + protected BaseSubsamplingBuilder(PoolingType poolingType, int[] kernelSize, int[] stride) { this.setPoolingType(poolingType.toPoolingType()); this.setKernelSize(kernelSize); @@ -477,7 +474,7 @@ public class SubsamplingLayer extends NoParamLayer { this.pnorm = pnorm; } - public void setEps(double eps){ + public void setEps(double eps) { ValidationUtils.validateNonNegative(eps, "eps"); this.eps = eps; } @@ -490,6 +487,17 @@ public class SubsamplingLayer extends NoParamLayer { this.convolutionMode = convolutionMode; } + /** + * Set the data format for the CNN activations - NCHW (channels first) or NHWC (channels last). + * See {@link CNN2DFormat} for more details.<br> + * Default: NCHW + * @param cnn2DFormat Format for activations (in and out) + */ + public T dataFormat(CNN2DFormat cnn2DFormat) { + this.cnn2DFormat = cnn2DFormat; + return (T) this; + } + /** * Set the convolution mode for the Convolution layer. See {@link ConvolutionMode} for more details * diff --git a/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/convolution/subsampling/SubsamplingLayer.java b/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/convolution/subsampling/SubsamplingLayer.java index ebaa7008a3..3e5dc3c377 100644 --- a/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/convolution/subsampling/SubsamplingLayer.java +++ b/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/convolution/subsampling/SubsamplingLayer.java @@ -87,7 +87,7 @@ public class SubsamplingLayer extends AbstractLayer<org.deeplearning4j.nn.conf.l CNN2DFormat dataFormat = layerConf().getCnn2dDataFormat(); int hIdx = 2; int wIdx = 3; - if(dataFormat == CNN2DFormat.NHWC){ + if(dataFormat == CNN2DFormat.NHWC) { hIdx = 1; wIdx = 2; }
['deeplearning4j/deeplearning4j-modelimport/src/test/java/org/deeplearning4j/nn/modelimport/keras/layers/pooling/KerasPooling1DTest.java', 'deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/layers/pooling/KerasPooling1D.java', 'deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/convolution/subsampling/SubsamplingLayer.java', 'deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/conf/layers/SubsamplingLayer.java', 'deeplearning4j/deeplearning4j-core/src/test/java/org/deeplearning4j/nn/layers/HelperUtilsTest.java']
{'.java': 5}
5
5
0
0
5
25,713,969
5,618,780
662,416
3,972
1,514
377
39
3
1,735
226
451
47
0
1
1970-01-01T00:27:03
13,099
Java
{'Java': 42895752, 'C++': 17237193, 'Cuda': 2203734, 'Kotlin': 2030453, 'JavaScript': 296767, 'C': 172853, 'CMake': 126415, 'Shell': 96643, 'TypeScript': 81217, 'Python': 77566, 'FreeMarker': 77257, 'HTML': 18609, 'CSS': 12974, 'PureBasic': 12254, 'Cython': 12094, 'Ruby': 4558, 'Batchfile': 1458, 'Scala': 1026, 'Smarty': 975, 'Starlark': 931}
Apache License 2.0