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
162
square/okhttp/1085/1034
square
okhttp
https://github.com/square/okhttp/issues/1034
https://github.com/square/okhttp/pull/1085
https://github.com/square/okhttp/pull/1085
1
closes
SpdyConnection.pushExecutor has zero keep-alive time
https://github.com/square/okhttp/blob/master/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java#L158 Because of the 0ms keep-alive time, the pushExecutor creates (and destroys) a new thread on every callback. This seems unnecessarily expensive, compared to reusing the thread, particularly in settings where push callbacks are invoked frequently. Is there a reason why you'd want the threads created for this executor to be effectively single-use?
9aa1268899524f0f750ab35fa363f2ed3cec29cf
712e56de25c8c212d8c85c6b316faeb8789d731c
https://github.com/square/okhttp/compare/9aa1268899524f0f750ab35fa363f2ed3cec29cf...712e56de25c8c212d8c85c6b316faeb8789d731c
diff --git a/okhttp/src/main/java/com/squareup/okhttp/Connection.java b/okhttp/src/main/java/com/squareup/okhttp/Connection.java index 11bf1f217..0806c7954 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/Connection.java +++ b/okhttp/src/main/java/com/squareup/okhttp/Connection.java @@ -85,7 +85,7 @@ public final class Connection { "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", // 0x00,0x33 Android 2.3 "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", // 0x00,0x32 Android 2.3 "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", // 0x00,0x39 Android 2.3 - "TLS_RSA_WITH_AES_128_GCM_SHA256", // 0x00,0x9C + "TLS_RSA_WITH_AES_128_GCM_SHA256", // 0x00,0x9C Android L "TLS_RSA_WITH_AES_128_CBC_SHA", // 0x00,0x2F Android 2.3 "TLS_RSA_WITH_AES_256_CBC_SHA", // 0x00,0x35 Android 2.3 "SSL_RSA_WITH_3DES_EDE_CBC_SHA", // 0x00,0x0A Android 2.3 (Deprecated in L) diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java index 31719ff07..0b6fa2d5f 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java +++ b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java @@ -153,8 +153,7 @@ public final class SpdyConnection implements Closeable { if (protocol == Protocol.HTTP_2) { variant = new Http20Draft14(); // Like newSingleThreadExecutor, except lazy creates the thread. - pushExecutor = new ThreadPoolExecutor(0, 1, - 0L, TimeUnit.MILLISECONDS, + pushExecutor = new ThreadPoolExecutor(0, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), Util.threadFactory(String.format("OkHttp %s Push Observer", hostName), true)); // 1 less than SPDY http://tools.ietf.org/html/draft-ietf-httpbis-http2-14#section-6.9.2
['okhttp/src/main/java/com/squareup/okhttp/Connection.java', 'okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java']
{'.java': 2}
2
2
0
0
2
736,645
166,586
21,524
114
297
93
5
2
475
53
105
6
1
0
1970-01-01T00:23:33
44,252
Kotlin
{'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995}
Apache License 2.0
161
square/okhttp/1106/938
square
okhttp
https://github.com/square/okhttp/issues/938
https://github.com/square/okhttp/pull/1106
https://github.com/square/okhttp/pull/1106
1
closes
SpdyConnection synchronization problem in goAway
We call SpdyStream.receiveRstStream (synchronizes on the stream) while holding the lock on SpdyConnection.this. We should release the SpdyConnection lock before acquiring the SpdyStream lock.
125df557fbeb9c77eb17872acac2eb156428d2ed
8f1bc30cd1e821b8b3745502a0f442f54cdebce8
https://github.com/square/okhttp/compare/125df557fbeb9c77eb17872acac2eb156428d2ed...8f1bc30cd1e821b8b3745502a0f442f54cdebce8
diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java index 0b6fa2d5f..d3ebee2e3 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java +++ b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java @@ -24,7 +24,6 @@ import java.io.InterruptedIOException; import java.net.InetSocketAddress; import java.net.Socket; import java.util.HashMap; -import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; @@ -734,18 +733,19 @@ public final class SpdyConnection implements Closeable { @Override public void goAway(int lastGoodStreamId, ErrorCode errorCode, ByteString debugData) { if (debugData.size() > 0) { // TODO: log the debugData } + + // Copy the streams first. We don't want to hold a lock when we call receiveRstStream(). + SpdyStream[] streamsCopy; synchronized (SpdyConnection.this) { + streamsCopy = streams.values().toArray(new SpdyStream[streams.size()]); shutdown = true; + } - // Fail all streams created after the last good stream ID. - for (Iterator<Map.Entry<Integer, SpdyStream>> i = streams.entrySet().iterator(); - i.hasNext(); ) { - Map.Entry<Integer, SpdyStream> entry = i.next(); - int streamId = entry.getKey(); - if (streamId > lastGoodStreamId && entry.getValue().isLocallyInitiated()) { - entry.getValue().receiveRstStream(ErrorCode.REFUSED_STREAM); - i.remove(); - } + // Fail all streams created after the last good stream ID. + for (SpdyStream spdyStream : streamsCopy) { + if (spdyStream.getId() > lastGoodStreamId && spdyStream.isLocallyInitiated()) { + spdyStream.receiveRstStream(ErrorCode.REFUSED_STREAM); + removeStream(spdyStream.getId()); } } }
['okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java']
{'.java': 1}
1
1
0
0
1
755,423
170,699
21,981
117
1,054
232
20
1
192
24
43
2
0
0
1970-01-01T00:23:34
44,252
Kotlin
{'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995}
Apache License 2.0
170
square/okhttp/518/184
square
okhttp
https://github.com/square/okhttp/issues/184
https://github.com/square/okhttp/pull/518
https://github.com/square/okhttp/pull/518
1
closes
OkHttp changes the global SSL context, breaks other HTTP clients
We're enabling SPDY for the shared SSL context, and other HTTP clients like HttpURLConnection don't anticipate this, causing them to freak out and crash the app. @skyisle's original report... Here is backtrace. DEBUG I backtrace: DEBUG I #00 pc 00022430 /system/lib/libssl.so (SSL_select_next_proto+25) DEBUG I #01 pc 000222ef /system/lib/libjavacore.so DEBUG I #02 pc 0002905f /system/lib/libssl.so (ssl_parse_serverhello_tlsext+458) DEBUG I #03 pc 00015957 /system/lib/libssl.so (ssl3_get_server_hello+894) DEBUG I #04 pc 00018193 /system/lib/libssl.so (ssl3_connect+618) DEBUG I #05 pc 000235d7 /system/lib/libssl.so (SSL_connect+18) DEBUG I #06 pc 0001126b /system/lib/libssl.so (ssl23_connect+1970) DEBUG I #07 pc 0002350f /system/lib/libssl.so (SSL_do_handshake+66) DEBUG I #08 pc 00024bc5 /system/lib/libjavacore.so DEBUG I #09 pc 0001e490 /system/lib/libdvm.so (dvmPlatformInvoke+112) DEBUG I #10 pc 0004d2b1 /system/lib/libdvm.so (dvmCallJNIMethod(unsigned int const_, JValue_, Method const_, Thread_)+396) DEBUG I #11 pc 000278a0 /system/lib/libdvm.so DEBUG I #12 pc 0002b77c /system/lib/libdvm.so (dvmInterpret(Thread_, Method const_, JValue_)+176) DEBUG I #13 pc 0005fae5 /system/lib/libdvm.so (dvmCallMethodV(Thread_, Method const_, Object_, bool, JValue_, std::__va_list)+272) DEBUG I #14 pc 0005fb0f /system/lib/libdvm.so (dvmCallMethod(Thread_, Method const_, Object_, JValue*, ...)+20) DEBUG I #15 pc 0005466f /system/lib/libdvm.so DEBUG I #16 pc 0000e418 /system/lib/libc.so (__thread_entry+72) DEBUG I #17 pc 0000db0c /system/lib/libc.so (pthread_create+168) DEBUG I #18 pc 00052f34 <unknown>
de6d505c03419a53e0387802a6cc2196572dd99e
5d7fdbaf30a411c56666462bd032d86e8eb4ddf7
https://github.com/square/okhttp/compare/de6d505c03419a53e0387802a6cc2196572dd99e...5d7fdbaf30a411c56666462bd032d86e8eb4ddf7
diff --git a/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java b/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java index 68e1cfadb..b76b5cd45 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java +++ b/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java @@ -15,8 +15,8 @@ */ package com.squareup.okhttp; -import com.squareup.okhttp.internal.bytes.ByteString; import com.squareup.okhttp.internal.Util; +import com.squareup.okhttp.internal.bytes.ByteString; import com.squareup.okhttp.internal.http.HttpAuthenticator; import com.squareup.okhttp.internal.http.HttpURLConnectionImpl; import com.squareup.okhttp.internal.http.HttpsURLConnectionImpl; @@ -31,11 +31,12 @@ import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; import java.net.URLStreamHandlerFactory; +import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; /** Configures and creates HTTP connections. */ @@ -202,8 +203,7 @@ public final class OkHttpClient implements URLStreamHandlerFactory, Cloneable { /** * Sets the socket factory used to secure HTTPS connections. * - * <p>If unset, the {@link HttpsURLConnection#getDefaultSSLSocketFactory() - * system-wide default} SSL socket factory will be used. + * <p>If unset, a lazily created SSL socket factory will be used. */ public OkHttpClient setSslSocketFactory(SSLSocketFactory sslSocketFactory) { this.sslSocketFactory = sslSocketFactory; @@ -218,7 +218,8 @@ public final class OkHttpClient implements URLStreamHandlerFactory, Cloneable { * Sets the verifier used to confirm that response certificates apply to * requested hostnames for HTTPS connections. * - * <p>If unset, the {@link HttpsURLConnection#getDefaultHostnameVerifier() + * <p>If unset, the + * {@link javax.net.ssl.HttpsURLConnection#getDefaultHostnameVerifier() * system-wide default} hostname verifier will be used. */ public OkHttpClient setHostnameVerifier(HostnameVerifier hostnameVerifier) { @@ -422,7 +423,7 @@ public final class OkHttpClient implements URLStreamHandlerFactory, Cloneable { result.responseCache = toOkResponseCacheOrNull(ResponseCache.getDefault()); } if (result.sslSocketFactory == null) { - result.sslSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory(); + result.sslSocketFactory = getDefaultSSLSocketFactory(); } if (result.hostnameVerifier == null) { result.hostnameVerifier = OkHostnameVerifier.INSTANCE; @@ -439,6 +440,30 @@ public final class OkHttpClient implements URLStreamHandlerFactory, Cloneable { return result; } + /** + * Java and Android programs default to using a single global SSL context, + * accessible to HTTP clients as {@link SSLSocketFactory#getDefault()}. If we + * used the shared SSL context, when OkHttp enables NPN for its SPDY-related + * stuff, it would also enable NPN for other usages, which might crash them + * because NPN is enabled when it isn't expected to be. + * <p> + * This code avoids that by defaulting to an OkHttp created SSL context. The + * significant drawback of this approach is that apps that customize the + * global SSL context will lose these customizations. + */ + private synchronized SSLSocketFactory getDefaultSSLSocketFactory() { + if (sslSocketFactory == null) { + try { + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, null, null); + sslSocketFactory = sslContext.getSocketFactory(); + } catch (GeneralSecurityException e) { + throw new AssertionError(); // The system has no TLS. Just give up. + } + } + return sslSocketFactory; + } + /** Returns a shallow copy of this OkHttpClient. */ @Override public OkHttpClient clone() { try {
['okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java']
{'.java': 1}
1
1
0
0
1
688,744
159,125
20,229
100
1,840
403
37
1
1,769
183
605
27
0
0
1970-01-01T00:23:11
44,252
Kotlin
{'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995}
Apache License 2.0
169
square/okhttp/628/627
square
okhttp
https://github.com/square/okhttp/issues/627
https://github.com/square/okhttp/pull/628
https://github.com/square/okhttp/pull/628
1
fix
SpdyConnection clears the old settings without merging with the new server settings causing the window size always set as -1
When debugging an issue with client requests hanging on SpdyStream.waitUntilWritable(), we found that the window size is set as -1 in SpdyStream.java at line: this.bytesLeftInWriteWindow = connection.peerSettings.getInitialWindowSize(); After tracing down the issue, the problem turned out to be line 662 of https://github.com/square/okhttp/blob/master/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java, where peerSettings is cleared without merging with the new settings. This has caused any later SpdyStream always uses an –1 as the initial window size, and the bug has also caused the new window size settings not get propagated to existing SpdySteam(s).
945619c3f451bba092f772adbd62cd0a6fd7ec3b
12ba9103d825b776d6cf4f74704332f4118ec1be
https://github.com/square/okhttp/compare/945619c3f451bba092f772adbd62cd0a6fd7ec3b...12ba9103d825b776d6cf4f74704332f4118ec1be
diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SettingsTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SettingsTest.java index 44459b8c9..294684f1b 100644 --- a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SettingsTest.java +++ b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SettingsTest.java @@ -17,6 +17,7 @@ package com.squareup.okhttp.internal.spdy; import org.junit.Test; +import static com.squareup.okhttp.internal.spdy.Settings.DEFAULT_INITIAL_WINDOW_SIZE; import static com.squareup.okhttp.internal.spdy.Settings.DOWNLOAD_BANDWIDTH; import static com.squareup.okhttp.internal.spdy.Settings.DOWNLOAD_RETRANS_RATE; import static com.squareup.okhttp.internal.spdy.Settings.MAX_CONCURRENT_STREAMS; @@ -68,9 +69,10 @@ public final class SettingsTest { settings.set(DOWNLOAD_RETRANS_RATE, 0, 97); assertEquals(97, settings.getDownloadRetransRate(-3)); - assertEquals(-1, settings.getInitialWindowSize()); + assertEquals(DEFAULT_INITIAL_WINDOW_SIZE, + settings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE)); settings.set(Settings.INITIAL_WINDOW_SIZE, 0, 108); - assertEquals(108, settings.getInitialWindowSize()); + assertEquals(108, settings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE)); assertEquals(-3, settings.getClientCertificateVectorSize(-3)); settings.set(Settings.CLIENT_CERTIFICATE_VECTOR_SIZE, 0, 117); diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SpdyConnectionTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SpdyConnectionTest.java index 64b81ced1..2ef127e99 100644 --- a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SpdyConnectionTest.java +++ b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SpdyConnectionTest.java @@ -39,6 +39,7 @@ import static com.squareup.okhttp.internal.spdy.ErrorCode.INVALID_STREAM; import static com.squareup.okhttp.internal.spdy.ErrorCode.PROTOCOL_ERROR; import static com.squareup.okhttp.internal.spdy.ErrorCode.REFUSED_STREAM; import static com.squareup.okhttp.internal.spdy.ErrorCode.STREAM_IN_USE; +import static com.squareup.okhttp.internal.spdy.Settings.DEFAULT_INITIAL_WINDOW_SIZE; import static com.squareup.okhttp.internal.spdy.Settings.PERSIST_VALUE; import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_DATA; import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_GOAWAY; @@ -47,7 +48,6 @@ import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_PING; import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_RST_STREAM; import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_SETTINGS; import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_WINDOW_UPDATE; -import static com.squareup.okhttp.internal.spdy.SpdyConnection.INITIAL_WINDOW_SIZE; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -301,7 +301,7 @@ public final class SpdyConnectionTest { // This stream was created *after* the connection settings were adjusted. SpdyStream stream = connection.newStream(headerEntries("a", "android"), false, true); - assertEquals(3368, connection.peerSettings.getInitialWindowSize()); + assertEquals(3368, connection.peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE)); assertEquals(1684, connection.bytesLeftInWriteWindow); // initial wasn't affected. // New Stream is has the most recent initial window size. assertEquals(3368, stream.bytesLeftInWriteWindow); @@ -405,6 +405,35 @@ public final class SpdyConnectionTest { } } + @Test public void clearSettingsBeforeMerge() throws Exception { + // write the mocking script + Settings settings1 = new Settings(); + settings1.set(Settings.UPLOAD_BANDWIDTH, PERSIST_VALUE, 100); + settings1.set(Settings.DOWNLOAD_BANDWIDTH, PERSIST_VALUE, 200); + settings1.set(Settings.DOWNLOAD_RETRANS_RATE, 0, 300); + peer.sendFrame().settings(settings1); + peer.sendFrame().ping(false, 2, 0); + peer.acceptFrame(); + peer.play(); + + // play it back + SpdyConnection connection = connection(peer, SPDY3); + + peer.takeFrame(); // Guarantees that the Settings frame has been processed. + + // fake a settings frame with clear flag set. + Settings settings2 = new Settings(); + settings2.set(Settings.MAX_CONCURRENT_STREAMS, PERSIST_VALUE, 600); + connection.readerRunnable.settings(true, settings2); + + synchronized (connection) { + assertEquals(-1, connection.peerSettings.getUploadBandwidth(-1)); + assertEquals(-1, connection.peerSettings.getDownloadBandwidth(-1)); + assertEquals(-1, connection.peerSettings.getDownloadRetransRate(-1)); + assertEquals(600, connection.peerSettings.getMaxConcurrentStreams(-1)); + } + } + @Test public void bogusDataFrameDoesNotDisruptConnection() throws Exception { // write the mocking script peer.sendFrame().data(true, 41, new OkBuffer().writeUtf8("bogus")); @@ -1042,7 +1071,7 @@ public final class SpdyConnectionTest { throws IOException, InterruptedException { peer.setVariantAndClient(variant, false); - int windowUpdateThreshold = INITIAL_WINDOW_SIZE / 2; + int windowUpdateThreshold = DEFAULT_INITIAL_WINDOW_SIZE / 2; // Write the mocking script. peer.acceptFrame(); // SYN_STREAM @@ -1152,7 +1181,7 @@ public final class SpdyConnectionTest { } @Test public void writeAwaitsWindowUpdate() throws Exception { - int framesThatFillWindow = roundUp(INITIAL_WINDOW_SIZE, HTTP_20_DRAFT_09.maxFrameSize()); + int framesThatFillWindow = roundUp(DEFAULT_INITIAL_WINDOW_SIZE, HTTP_20_DRAFT_09.maxFrameSize()); // Write the mocking script. This accepts more data frames than necessary! peer.acceptFrame(); // SYN_STREAM @@ -1166,7 +1195,7 @@ public final class SpdyConnectionTest { SpdyConnection connection = connection(peer, SPDY3); SpdyStream stream = connection.newStream(headerEntries("b", "banana"), true, true); BufferedSink out = Okio.buffer(stream.getSink()); - out.write(new byte[INITIAL_WINDOW_SIZE]); + out.write(new byte[DEFAULT_INITIAL_WINDOW_SIZE]); out.flush(); // Check that we've filled the window for both the stream and also the connection. @@ -1194,7 +1223,7 @@ public final class SpdyConnectionTest { } @Test public void initialSettingsWithWindowSizeAdjustsConnection() throws Exception { - int framesThatFillWindow = roundUp(INITIAL_WINDOW_SIZE, HTTP_20_DRAFT_09.maxFrameSize()); + int framesThatFillWindow = roundUp(DEFAULT_INITIAL_WINDOW_SIZE, HTTP_20_DRAFT_09.maxFrameSize()); // Write the mocking script. This accepts more data frames than necessary! peer.acceptFrame(); // SYN_STREAM @@ -1208,7 +1237,7 @@ public final class SpdyConnectionTest { SpdyConnection connection = connection(peer, SPDY3); SpdyStream stream = connection.newStream(headerEntries("a", "apple"), true, true); BufferedSink out = Okio.buffer(stream.getSink()); - out.write(new byte[INITIAL_WINDOW_SIZE]); + out.write(new byte[DEFAULT_INITIAL_WINDOW_SIZE]); out.flush(); // write 1 more than the window size @@ -1221,7 +1250,7 @@ public final class SpdyConnectionTest { // Receiving a Settings with a larger window size will unblock the streams. Settings initial = new Settings(); - initial.set(Settings.INITIAL_WINDOW_SIZE, PERSIST_VALUE, INITIAL_WINDOW_SIZE + 1); + initial.set(Settings.INITIAL_WINDOW_SIZE, PERSIST_VALUE, DEFAULT_INITIAL_WINDOW_SIZE + 1); connection.readerRunnable.settings(false, initial); assertEquals(1, connection.bytesLeftInWriteWindow); @@ -1235,7 +1264,7 @@ public final class SpdyConnectionTest { // Settings after the initial do not affect the connection window size. Settings next = new Settings(); - next.set(Settings.INITIAL_WINDOW_SIZE, PERSIST_VALUE, INITIAL_WINDOW_SIZE + 2); + next.set(Settings.INITIAL_WINDOW_SIZE, PERSIST_VALUE, DEFAULT_INITIAL_WINDOW_SIZE + 2); connection.readerRunnable.settings(false, next); assertEquals(0, connection.bytesLeftInWriteWindow); // connection wasn't affected. @@ -1263,7 +1292,7 @@ public final class SpdyConnectionTest { } @Test public void blockedStreamDoesntStarveNewStream() throws Exception { - int framesThatFillWindow = roundUp(INITIAL_WINDOW_SIZE, SPDY3.maxFrameSize()); + int framesThatFillWindow = roundUp(DEFAULT_INITIAL_WINDOW_SIZE, SPDY3.maxFrameSize()); // Write the mocking script. This accepts more data frames than necessary! peer.acceptFrame(); // SYN_STREAM on stream 1 @@ -1278,7 +1307,7 @@ public final class SpdyConnectionTest { SpdyConnection connection = connection(peer, SPDY3); SpdyStream stream1 = connection.newStream(headerEntries("a", "apple"), true, true); BufferedSink out1 = Okio.buffer(stream1.getSink()); - out1.write(new byte[INITIAL_WINDOW_SIZE]); + out1.write(new byte[DEFAULT_INITIAL_WINDOW_SIZE]); out1.flush(); // Check that we've filled the window for both the stream and also the connection. @@ -1299,7 +1328,7 @@ public final class SpdyConnectionTest { assertEquals(0, connection.bytesLeftInWriteWindow); assertEquals(0, connection.getStream(1).bytesLeftInWriteWindow); - assertEquals(INITIAL_WINDOW_SIZE - 3, connection.getStream(3).bytesLeftInWriteWindow); + assertEquals(DEFAULT_INITIAL_WINDOW_SIZE - 3, connection.getStream(3).bytesLeftInWriteWindow); } @Test public void maxFrameSizeHonored() throws Exception { diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/Settings.java b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/Settings.java index c05d6b174..bf430882e 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/Settings.java +++ b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/Settings.java @@ -22,6 +22,12 @@ import java.util.Arrays; * Settings are {@link com.squareup.okhttp.internal.spdy.SpdyConnection connection} scoped. */ final class Settings { + /** + * From the SPDY/3 and HTTP/2 specs, the default initial window size for all + * streams is 64 KiB. (Chrome 25 uses 10 MiB). + */ + static final int DEFAULT_INITIAL_WINDOW_SIZE = 64 * 1024; + /** Peer request to clear durable settings. */ static final int FLAG_CLEAR_PREVIOUSLY_PERSISTED_SETTINGS = 0x1; @@ -171,11 +177,9 @@ final class Settings { return (bit & set) != 0 ? values[DOWNLOAD_RETRANS_RATE] : defaultValue; } - // TODO: honor this setting in http/2. - /** Returns -1 if unset. */ - int getInitialWindowSize() { + int getInitialWindowSize(int defaultValue) { int bit = 1 << INITIAL_WINDOW_SIZE; - return (bit & set) != 0 ? values[INITIAL_WINDOW_SIZE] : -1; + return (bit & set) != 0 ? values[INITIAL_WINDOW_SIZE] : defaultValue; } /** spdy/3 only. */ diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java index fab8698a2..4cd8d32c8 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java +++ b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java @@ -38,6 +38,8 @@ import okio.ByteString; import okio.OkBuffer; import okio.Okio; +import static com.squareup.okhttp.internal.spdy.Settings.DEFAULT_INITIAL_WINDOW_SIZE; + /** * A socket connection to a remote peer. A connection hosts streams which can * send and receive data. @@ -89,8 +91,6 @@ public final class SpdyConnection implements Closeable { private final PushObserver pushObserver; private int nextPingId; - static final int INITIAL_WINDOW_SIZE = 65535; - /** * The total number of bytes consumed by the application, but not yet * acknowledged by sending a {@code WINDOW_UPDATE} frame on this connection. @@ -107,15 +107,12 @@ public final class SpdyConnection implements Closeable { /** Settings we communicate to the peer. */ // TODO: Do we want to dynamically adjust settings, or KISS and only set once? - final Settings okHttpSettings = new Settings() - .set(Settings.INITIAL_WINDOW_SIZE, 0, INITIAL_WINDOW_SIZE); - // TODO: implement stream limit + final Settings okHttpSettings = new Settings(); // okHttpSettings.set(Settings.MAX_CONCURRENT_STREAMS, 0, max); /** Settings we receive from the peer. */ // TODO: MWS will need to guard on this setting before attempting to push. - final Settings peerSettings = new Settings() - .set(Settings.INITIAL_WINDOW_SIZE, 0, INITIAL_WINDOW_SIZE); + final Settings peerSettings = new Settings(); private boolean receivedInitialPeerSettings = false; final FrameReader frameReader; @@ -151,7 +148,7 @@ public final class SpdyConnection implements Closeable { } else { throw new AssertionError(protocol); } - bytesLeftInWriteWindow = peerSettings.getInitialWindowSize(); + bytesLeftInWriteWindow = peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE); frameReader = variant.newReader(builder.source, client); frameWriter = variant.newWriter(builder.sink, client); maxFrameSize = variant.maxFrameSize(); @@ -657,16 +654,13 @@ public final class SpdyConnection implements Closeable { long delta = 0; SpdyStream[] streamsToNotify = null; synchronized (SpdyConnection.this) { - int priorWriteWindowSize = peerSettings.getInitialWindowSize(); - if (clearPrevious) { - peerSettings.clear(); - } else { - peerSettings.merge(newSettings); - } + int priorWriteWindowSize = peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE); + if (clearPrevious) peerSettings.clear(); + peerSettings.merge(newSettings); if (getProtocol() == Protocol.HTTP_2) { ackSettingsLater(); } - int peerInitialWindowSize = peerSettings.getInitialWindowSize(); + int peerInitialWindowSize = peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE); if (peerInitialWindowSize != -1 && peerInitialWindowSize != priorWriteWindowSize) { delta = peerInitialWindowSize - priorWriteWindowSize; if (!receivedInitialPeerSettings) { diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java index 4fea5e8d3..0fcde2dbb 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java +++ b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java @@ -28,6 +28,8 @@ import okio.OkBuffer; import okio.Sink; import okio.Source; +import static com.squareup.okhttp.internal.spdy.Settings.DEFAULT_INITIAL_WINDOW_SIZE; + /** A logical bidirectional stream. */ public final class SpdyStream { // Internal state is guarded by this. No long-running or potentially @@ -76,8 +78,10 @@ public final class SpdyStream { if (requestHeaders == null) throw new NullPointerException("requestHeaders == null"); this.id = id; this.connection = connection; - this.bytesLeftInWriteWindow = connection.peerSettings.getInitialWindowSize(); - this.source = new SpdyDataSource(connection.okHttpSettings.getInitialWindowSize()); + this.bytesLeftInWriteWindow = + connection.peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE); + this.source = new SpdyDataSource( + connection.okHttpSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE)); this.sink = new SpdyDataSink(); this.source.finished = inFinished; this.sink.finished = outFinished; @@ -370,7 +374,8 @@ public final class SpdyStream { // Flow control: notify the peer that we're ready for more data! unacknowledgedBytesRead += read; - if (unacknowledgedBytesRead >= connection.peerSettings.getInitialWindowSize() / 2) { + if (unacknowledgedBytesRead + >= connection.peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE) / 2) { connection.writeWindowUpdateLater(id, unacknowledgedBytesRead); unacknowledgedBytesRead = 0; } @@ -380,7 +385,7 @@ public final class SpdyStream { synchronized (connection) { // Multiple application threads may hit this section. connection.unacknowledgedBytesRead += read; if (connection.unacknowledgedBytesRead - >= connection.peerSettings.getInitialWindowSize() / 2) { + >= connection.peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE) / 2) { connection.writeWindowUpdateLater(0, connection.unacknowledgedBytesRead); connection.unacknowledgedBytesRead = 0; }
['okhttp/src/main/java/com/squareup/okhttp/internal/spdy/Settings.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SettingsTest.java', 'okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SpdyConnectionTest.java', 'okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java']
{'.java': 5}
5
5
0
0
5
735,611
170,055
21,803
106
2,646
547
49
3
687
84
152
6
1
0
1970-01-01T00:23:14
44,252
Kotlin
{'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995}
Apache License 2.0
168
square/okhttp/631/627
square
okhttp
https://github.com/square/okhttp/issues/627
https://github.com/square/okhttp/pull/631
https://github.com/square/okhttp/pull/631
1
fix
SpdyConnection clears the old settings without merging with the new server settings causing the window size always set as -1
When debugging an issue with client requests hanging on SpdyStream.waitUntilWritable(), we found that the window size is set as -1 in SpdyStream.java at line: this.bytesLeftInWriteWindow = connection.peerSettings.getInitialWindowSize(); After tracing down the issue, the problem turned out to be line 662 of https://github.com/square/okhttp/blob/master/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java, where peerSettings is cleared without merging with the new settings. This has caused any later SpdyStream always uses an –1 as the initial window size, and the bug has also caused the new window size settings not get propagated to existing SpdySteam(s).
0d774185b616c7d471822f22f57f947412ef593d
83156632582465e93f462f311c0e6b340393c896
https://github.com/square/okhttp/compare/0d774185b616c7d471822f22f57f947412ef593d...83156632582465e93f462f311c0e6b340393c896
diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SettingsTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SettingsTest.java index 44459b8c9..294684f1b 100644 --- a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SettingsTest.java +++ b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SettingsTest.java @@ -17,6 +17,7 @@ package com.squareup.okhttp.internal.spdy; import org.junit.Test; +import static com.squareup.okhttp.internal.spdy.Settings.DEFAULT_INITIAL_WINDOW_SIZE; import static com.squareup.okhttp.internal.spdy.Settings.DOWNLOAD_BANDWIDTH; import static com.squareup.okhttp.internal.spdy.Settings.DOWNLOAD_RETRANS_RATE; import static com.squareup.okhttp.internal.spdy.Settings.MAX_CONCURRENT_STREAMS; @@ -68,9 +69,10 @@ public final class SettingsTest { settings.set(DOWNLOAD_RETRANS_RATE, 0, 97); assertEquals(97, settings.getDownloadRetransRate(-3)); - assertEquals(-1, settings.getInitialWindowSize()); + assertEquals(DEFAULT_INITIAL_WINDOW_SIZE, + settings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE)); settings.set(Settings.INITIAL_WINDOW_SIZE, 0, 108); - assertEquals(108, settings.getInitialWindowSize()); + assertEquals(108, settings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE)); assertEquals(-3, settings.getClientCertificateVectorSize(-3)); settings.set(Settings.CLIENT_CERTIFICATE_VECTOR_SIZE, 0, 117); diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SpdyConnectionTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SpdyConnectionTest.java index 8b934fa16..b73d6f930 100644 --- a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SpdyConnectionTest.java +++ b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SpdyConnectionTest.java @@ -39,6 +39,7 @@ import static com.squareup.okhttp.internal.spdy.ErrorCode.INVALID_STREAM; import static com.squareup.okhttp.internal.spdy.ErrorCode.PROTOCOL_ERROR; import static com.squareup.okhttp.internal.spdy.ErrorCode.REFUSED_STREAM; import static com.squareup.okhttp.internal.spdy.ErrorCode.STREAM_IN_USE; +import static com.squareup.okhttp.internal.spdy.Settings.DEFAULT_INITIAL_WINDOW_SIZE; import static com.squareup.okhttp.internal.spdy.Settings.PERSIST_VALUE; import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_DATA; import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_GOAWAY; @@ -47,7 +48,6 @@ import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_PING; import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_RST_STREAM; import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_SETTINGS; import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_WINDOW_UPDATE; -import static com.squareup.okhttp.internal.spdy.SpdyConnection.INITIAL_WINDOW_SIZE; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -301,7 +301,7 @@ public final class SpdyConnectionTest { // This stream was created *after* the connection settings were adjusted. SpdyStream stream = connection.newStream(headerEntries("a", "android"), false, true); - assertEquals(3368, connection.peerSettings.getInitialWindowSize()); + assertEquals(3368, connection.peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE)); assertEquals(1684, connection.bytesLeftInWriteWindow); // initial wasn't affected. // New Stream is has the most recent initial window size. assertEquals(3368, stream.bytesLeftInWriteWindow); @@ -405,6 +405,35 @@ public final class SpdyConnectionTest { } } + @Test public void clearSettingsBeforeMerge() throws Exception { + // write the mocking script + Settings settings1 = new Settings(); + settings1.set(Settings.UPLOAD_BANDWIDTH, PERSIST_VALUE, 100); + settings1.set(Settings.DOWNLOAD_BANDWIDTH, PERSIST_VALUE, 200); + settings1.set(Settings.DOWNLOAD_RETRANS_RATE, 0, 300); + peer.sendFrame().settings(settings1); + peer.sendFrame().ping(false, 2, 0); + peer.acceptFrame(); + peer.play(); + + // play it back + SpdyConnection connection = connection(peer, SPDY3); + + peer.takeFrame(); // Guarantees that the Settings frame has been processed. + + // fake a settings frame with clear flag set. + Settings settings2 = new Settings(); + settings2.set(Settings.MAX_CONCURRENT_STREAMS, PERSIST_VALUE, 600); + connection.readerRunnable.settings(true, settings2); + + synchronized (connection) { + assertEquals(-1, connection.peerSettings.getUploadBandwidth(-1)); + assertEquals(-1, connection.peerSettings.getDownloadBandwidth(-1)); + assertEquals(-1, connection.peerSettings.getDownloadRetransRate(-1)); + assertEquals(600, connection.peerSettings.getMaxConcurrentStreams(-1)); + } + } + @Test public void bogusDataFrameDoesNotDisruptConnection() throws Exception { // write the mocking script peer.sendFrame().data(true, 41, new OkBuffer().writeUtf8("bogus")); @@ -1042,7 +1071,7 @@ public final class SpdyConnectionTest { throws IOException, InterruptedException { peer.setVariantAndClient(variant, false); - int windowUpdateThreshold = INITIAL_WINDOW_SIZE / 2; + int windowUpdateThreshold = DEFAULT_INITIAL_WINDOW_SIZE / 2; // Write the mocking script. peer.acceptFrame(); // SYN_STREAM @@ -1152,7 +1181,7 @@ public final class SpdyConnectionTest { } @Test public void writeAwaitsWindowUpdate() throws Exception { - int framesThatFillWindow = roundUp(INITIAL_WINDOW_SIZE, HTTP_20_DRAFT_09.maxFrameSize()); + int framesThatFillWindow = roundUp(DEFAULT_INITIAL_WINDOW_SIZE, HTTP_20_DRAFT_09.maxFrameSize()); // Write the mocking script. This accepts more data frames than necessary! peer.acceptFrame(); // SYN_STREAM @@ -1166,7 +1195,7 @@ public final class SpdyConnectionTest { SpdyConnection connection = connection(peer, SPDY3); SpdyStream stream = connection.newStream(headerEntries("b", "banana"), true, true); BufferedSink out = Okio.buffer(stream.getSink()); - out.write(new byte[INITIAL_WINDOW_SIZE]); + out.write(new byte[DEFAULT_INITIAL_WINDOW_SIZE]); out.flush(); // Check that we've filled the window for both the stream and also the connection. @@ -1194,7 +1223,7 @@ public final class SpdyConnectionTest { } @Test public void initialSettingsWithWindowSizeAdjustsConnection() throws Exception { - int framesThatFillWindow = roundUp(INITIAL_WINDOW_SIZE, HTTP_20_DRAFT_09.maxFrameSize()); + int framesThatFillWindow = roundUp(DEFAULT_INITIAL_WINDOW_SIZE, HTTP_20_DRAFT_09.maxFrameSize()); // Write the mocking script. This accepts more data frames than necessary! peer.acceptFrame(); // SYN_STREAM @@ -1208,7 +1237,7 @@ public final class SpdyConnectionTest { SpdyConnection connection = connection(peer, SPDY3); SpdyStream stream = connection.newStream(headerEntries("a", "apple"), true, true); BufferedSink out = Okio.buffer(stream.getSink()); - out.write(new byte[INITIAL_WINDOW_SIZE]); + out.write(new byte[DEFAULT_INITIAL_WINDOW_SIZE]); out.flush(); // write 1 more than the window size @@ -1221,7 +1250,7 @@ public final class SpdyConnectionTest { // Receiving a Settings with a larger window size will unblock the streams. Settings initial = new Settings(); - initial.set(Settings.INITIAL_WINDOW_SIZE, PERSIST_VALUE, INITIAL_WINDOW_SIZE + 1); + initial.set(Settings.INITIAL_WINDOW_SIZE, PERSIST_VALUE, DEFAULT_INITIAL_WINDOW_SIZE + 1); connection.readerRunnable.settings(false, initial); assertEquals(1, connection.bytesLeftInWriteWindow); @@ -1235,7 +1264,7 @@ public final class SpdyConnectionTest { // Settings after the initial do not affect the connection window size. Settings next = new Settings(); - next.set(Settings.INITIAL_WINDOW_SIZE, PERSIST_VALUE, INITIAL_WINDOW_SIZE + 2); + next.set(Settings.INITIAL_WINDOW_SIZE, PERSIST_VALUE, DEFAULT_INITIAL_WINDOW_SIZE + 2); connection.readerRunnable.settings(false, next); assertEquals(0, connection.bytesLeftInWriteWindow); // connection wasn't affected. @@ -1263,7 +1292,7 @@ public final class SpdyConnectionTest { } @Test public void blockedStreamDoesntStarveNewStream() throws Exception { - int framesThatFillWindow = roundUp(INITIAL_WINDOW_SIZE, SPDY3.maxFrameSize()); + int framesThatFillWindow = roundUp(DEFAULT_INITIAL_WINDOW_SIZE, SPDY3.maxFrameSize()); // Write the mocking script. This accepts more data frames than necessary! peer.acceptFrame(); // SYN_STREAM on stream 1 @@ -1278,7 +1307,7 @@ public final class SpdyConnectionTest { SpdyConnection connection = connection(peer, SPDY3); SpdyStream stream1 = connection.newStream(headerEntries("a", "apple"), true, true); BufferedSink out1 = Okio.buffer(stream1.getSink()); - out1.write(new byte[INITIAL_WINDOW_SIZE]); + out1.write(new byte[DEFAULT_INITIAL_WINDOW_SIZE]); out1.flush(); // Check that we've filled the window for both the stream and also the connection. @@ -1299,7 +1328,7 @@ public final class SpdyConnectionTest { assertEquals(0, connection.bytesLeftInWriteWindow); assertEquals(0, connection.getStream(1).bytesLeftInWriteWindow); - assertEquals(INITIAL_WINDOW_SIZE - 3, connection.getStream(3).bytesLeftInWriteWindow); + assertEquals(DEFAULT_INITIAL_WINDOW_SIZE - 3, connection.getStream(3).bytesLeftInWriteWindow); } @Test public void maxFrameSizeHonored() throws Exception { diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/Settings.java b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/Settings.java index c05d6b174..bf430882e 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/Settings.java +++ b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/Settings.java @@ -22,6 +22,12 @@ import java.util.Arrays; * Settings are {@link com.squareup.okhttp.internal.spdy.SpdyConnection connection} scoped. */ final class Settings { + /** + * From the SPDY/3 and HTTP/2 specs, the default initial window size for all + * streams is 64 KiB. (Chrome 25 uses 10 MiB). + */ + static final int DEFAULT_INITIAL_WINDOW_SIZE = 64 * 1024; + /** Peer request to clear durable settings. */ static final int FLAG_CLEAR_PREVIOUSLY_PERSISTED_SETTINGS = 0x1; @@ -171,11 +177,9 @@ final class Settings { return (bit & set) != 0 ? values[DOWNLOAD_RETRANS_RATE] : defaultValue; } - // TODO: honor this setting in http/2. - /** Returns -1 if unset. */ - int getInitialWindowSize() { + int getInitialWindowSize(int defaultValue) { int bit = 1 << INITIAL_WINDOW_SIZE; - return (bit & set) != 0 ? values[INITIAL_WINDOW_SIZE] : -1; + return (bit & set) != 0 ? values[INITIAL_WINDOW_SIZE] : defaultValue; } /** spdy/3 only. */ diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java index 1ab4ab531..5c10db157 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java +++ b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java @@ -38,6 +38,8 @@ import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import static com.squareup.okhttp.internal.spdy.Settings.DEFAULT_INITIAL_WINDOW_SIZE; + /** * A socket connection to a remote peer. A connection hosts streams which can * send and receive data. @@ -89,8 +91,6 @@ public final class SpdyConnection implements Closeable { private final PushObserver pushObserver; private int nextPingId; - static final int INITIAL_WINDOW_SIZE = 65535; - /** * The total number of bytes consumed by the application, but not yet * acknowledged by sending a {@code WINDOW_UPDATE} frame on this connection. @@ -107,15 +107,12 @@ public final class SpdyConnection implements Closeable { /** Settings we communicate to the peer. */ // TODO: Do we want to dynamically adjust settings, or KISS and only set once? - final Settings okHttpSettings = new Settings() - .set(Settings.INITIAL_WINDOW_SIZE, 0, INITIAL_WINDOW_SIZE); - // TODO: implement stream limit + final Settings okHttpSettings = new Settings(); // okHttpSettings.set(Settings.MAX_CONCURRENT_STREAMS, 0, max); /** Settings we receive from the peer. */ // TODO: MWS will need to guard on this setting before attempting to push. - final Settings peerSettings = new Settings() - .set(Settings.INITIAL_WINDOW_SIZE, 0, INITIAL_WINDOW_SIZE); + final Settings peerSettings = new Settings(); private boolean receivedInitialPeerSettings = false; final FrameReader frameReader; @@ -151,7 +148,7 @@ public final class SpdyConnection implements Closeable { } else { throw new AssertionError(protocol); } - bytesLeftInWriteWindow = peerSettings.getInitialWindowSize(); + bytesLeftInWriteWindow = peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE); frameReader = variant.newReader(builder.source, client); frameWriter = variant.newWriter(builder.sink, client); maxFrameSize = variant.maxFrameSize(); @@ -657,16 +654,13 @@ public final class SpdyConnection implements Closeable { long delta = 0; SpdyStream[] streamsToNotify = null; synchronized (SpdyConnection.this) { - int priorWriteWindowSize = peerSettings.getInitialWindowSize(); - if (clearPrevious) { - peerSettings.clear(); - } else { - peerSettings.merge(newSettings); - } + int priorWriteWindowSize = peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE); + if (clearPrevious) peerSettings.clear(); + peerSettings.merge(newSettings); if (getProtocol() == Protocol.HTTP_2) { ackSettingsLater(); } - int peerInitialWindowSize = peerSettings.getInitialWindowSize(); + int peerInitialWindowSize = peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE); if (peerInitialWindowSize != -1 && peerInitialWindowSize != priorWriteWindowSize) { delta = peerInitialWindowSize - priorWriteWindowSize; if (!receivedInitialPeerSettings) { diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java index d0d2972aa..58d116fec 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java +++ b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java @@ -28,6 +28,8 @@ import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.List; +import static com.squareup.okhttp.internal.spdy.Settings.DEFAULT_INITIAL_WINDOW_SIZE; + /** A logical bidirectional stream. */ public final class SpdyStream { // Internal state is guarded by this. No long-running or potentially @@ -76,8 +78,10 @@ public final class SpdyStream { if (requestHeaders == null) throw new NullPointerException("requestHeaders == null"); this.id = id; this.connection = connection; - this.bytesLeftInWriteWindow = connection.peerSettings.getInitialWindowSize(); - this.source = new SpdyDataSource(connection.okHttpSettings.getInitialWindowSize()); + this.bytesLeftInWriteWindow = + connection.peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE); + this.source = new SpdyDataSource( + connection.okHttpSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE)); this.sink = new SpdyDataSink(); this.source.finished = inFinished; this.sink.finished = outFinished; @@ -370,7 +374,8 @@ public final class SpdyStream { // Flow control: notify the peer that we're ready for more data! unacknowledgedBytesRead += read; - if (unacknowledgedBytesRead >= connection.peerSettings.getInitialWindowSize() / 2) { + if (unacknowledgedBytesRead + >= connection.peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE) / 2) { connection.writeWindowUpdateLater(id, unacknowledgedBytesRead); unacknowledgedBytesRead = 0; } @@ -380,7 +385,7 @@ public final class SpdyStream { synchronized (connection) { // Multiple application threads may hit this section. connection.unacknowledgedBytesRead += read; if (connection.unacknowledgedBytesRead - >= connection.peerSettings.getInitialWindowSize() / 2) { + >= connection.peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE) / 2) { connection.writeWindowUpdateLater(0, connection.unacknowledgedBytesRead); connection.unacknowledgedBytesRead = 0; }
['okhttp/src/main/java/com/squareup/okhttp/internal/spdy/Settings.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SettingsTest.java', 'okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SpdyConnectionTest.java', 'okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java']
{'.java': 5}
5
5
0
0
5
707,538
163,749
20,895
102
2,646
547
49
3
687
84
152
6
1
0
1970-01-01T00:23:14
44,252
Kotlin
{'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995}
Apache License 2.0
167
square/okhttp/737/215
square
okhttp
https://github.com/square/okhttp/issues/215
https://github.com/square/okhttp/pull/737
https://github.com/square/okhttp/pull/737
1
closes
Creating HttpResponseCache causes StrictMode violation
When cache is created I'm having this violation: 06-18 11:19:42.607: E/StrictMode(4300): A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks. 06-18 11:19:42.607: E/StrictMode(4300): java.lang.Throwable: Explicit termination method 'close' not called 06-18 11:19:42.607: E/StrictMode(4300): at dalvik.system.CloseGuard.open(CloseGuard.java:184) 06-18 11:19:42.607: E/StrictMode(4300): at java.io.FileOutputStream.<init>(FileOutputStream.java:90) 06-18 11:19:42.607: E/StrictMode(4300): at com.squareup.okhttp.internal.DiskLruCache.open(DiskLruCache.java:226) 06-18 11:19:42.607: E/StrictMode(4300): at com.squareup.okhttp.HttpResponseCache.<init>(HttpResponseCache.java:171)
6486179b9d9c888a818c85384eed88fa0a8768a6
c51382a430a2adb8a29cb59976af76b2cb48e386
https://github.com/square/okhttp/compare/6486179b9d9c888a818c85384eed88fa0a8768a6...c51382a430a2adb8a29cb59976af76b2cb48e386
diff --git a/okhttp/src/main/java/com/squareup/okhttp/HttpResponseCache.java b/okhttp/src/main/java/com/squareup/okhttp/HttpResponseCache.java index e299d5721..2b701c335 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/HttpResponseCache.java +++ b/okhttp/src/main/java/com/squareup/okhttp/HttpResponseCache.java @@ -169,12 +169,18 @@ public final class HttpResponseCache extends ResponseCache implements OkResponse if (snapshot == null) { return null; } - entry = new Entry(snapshot.getInputStream(ENTRY_METADATA)); } catch (IOException e) { // Give up because the cache cannot be read. return null; } + try { + entry = new Entry(snapshot.getInputStream(ENTRY_METADATA)); + } catch (IOException e) { + Util.closeQuietly(snapshot); + return null; + } + Response response = entry.response(request, snapshot); if (!entry.matches(request, response)) {
['okhttp/src/main/java/com/squareup/okhttp/HttpResponseCache.java']
{'.java': 1}
1
1
0
0
1
663,416
150,136
19,555
92
240
46
8
1
772
60
237
9
0
0
1970-01-01T00:23:17
44,252
Kotlin
{'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995}
Apache License 2.0
166
square/okhttp/769/745
square
okhttp
https://github.com/square/okhttp/issues/745
https://github.com/square/okhttp/pull/769
https://github.com/square/okhttp/pull/769
1
fixes
Can't execute DELETE without body.
I'm trying to create Request just as: ``` Request.Builder builder = new Request.Builder().url("URL"); builder.method("DELETE", null); ``` (because there are no `.delete()` method) When I'm trying to execute such request it crashes, with error message: `java.lang.IllegalStateException: Cannot stream a request body without chunked encoding or a known content length!` As I get it, it happens because DELETE can "has request body" (`hasRequestBody` returns `true` for DELETE) and when we are trying to create request body it blows up, because neither `contentLength` info provided nor `Transfer-Encoding` is set to `chunked` because no body provided. So, there is workaround: just add `Content-Length: 0` header. Looks like it is somekind related to #605.
04aee71eb5007c87d857c4c2690689e89722f092
520d9fc2bc6b251a998b58794070f8bebee9d682
https://github.com/square/okhttp/compare/04aee71eb5007c87d857c4c2690689e89722f092...520d9fc2bc6b251a998b58794070f8bebee9d682
diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java index d5851488f..c44f386b8 100644 --- a/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java +++ b/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java @@ -65,6 +65,148 @@ public final class CallTest { cache.delete(); } + @Test public void get() throws Exception { + server.enqueue(new MockResponse().setBody("abc").addHeader("Content-Type: text/plain")); + server.play(); + + Request request = new Request.Builder() + .url(server.getUrl("/")) + .header("User-Agent", "SyncApiTest") + .build(); + + executeSynchronously(request) + .assertCode(200) + .assertContainsHeaders("Content-Type: text/plain") + .assertBody("abc"); + + RecordedRequest recordedRequest = server.takeRequest(); + assertEquals("GET", recordedRequest.getMethod()); + assertEquals("SyncApiTest", recordedRequest.getHeader("User-Agent")); + assertEquals(0, recordedRequest.getBody().length); + assertNull(recordedRequest.getHeader("Content-Length")); + } + + @Test public void head() throws Exception { + server.enqueue(new MockResponse().addHeader("Content-Type: text/plain")); + server.play(); + + Request request = new Request.Builder() + .url(server.getUrl("/")) + .head() + .header("User-Agent", "SyncApiTest") + .build(); + + executeSynchronously(request) + .assertCode(200) + .assertContainsHeaders("Content-Type: text/plain"); + + RecordedRequest recordedRequest = server.takeRequest(); + assertEquals("HEAD", recordedRequest.getMethod()); + assertEquals("SyncApiTest", recordedRequest.getHeader("User-Agent")); + assertEquals(0, recordedRequest.getBody().length); + assertNull(recordedRequest.getHeader("Content-Length")); + } + + @Test public void post() throws Exception { + server.enqueue(new MockResponse().setBody("abc")); + server.play(); + + Request request = new Request.Builder() + .url(server.getUrl("/")) + .post(Request.Body.create(MediaType.parse("text/plain"), "def")) + .build(); + + executeSynchronously(request) + .assertCode(200) + .assertBody("abc"); + + RecordedRequest recordedRequest = server.takeRequest(); + assertEquals("POST", recordedRequest.getMethod()); + assertEquals("def", recordedRequest.getUtf8Body()); + assertEquals("3", recordedRequest.getHeader("Content-Length")); + assertEquals("text/plain; charset=utf-8", recordedRequest.getHeader("Content-Type")); + } + + @Test public void postZeroLength() throws Exception { + server.enqueue(new MockResponse().setBody("abc")); + server.play(); + + Request request = new Request.Builder() + .url(server.getUrl("/")) + .method("POST", null) + .build(); + + executeSynchronously(request) + .assertCode(200) + .assertBody("abc"); + + RecordedRequest recordedRequest = server.takeRequest(); + assertEquals("POST", recordedRequest.getMethod()); + assertEquals(0, recordedRequest.getBody().length); + assertEquals("0", recordedRequest.getHeader("Content-Length")); + assertEquals(null, recordedRequest.getHeader("Content-Type")); + } + + @Test public void delete() throws Exception { + server.enqueue(new MockResponse().setBody("abc")); + server.play(); + + Request request = new Request.Builder() + .url(server.getUrl("/")) + .delete() + .build(); + + executeSynchronously(request) + .assertCode(200) + .assertBody("abc"); + + RecordedRequest recordedRequest = server.takeRequest(); + assertEquals("DELETE", recordedRequest.getMethod()); + assertEquals(0, recordedRequest.getBody().length); + assertEquals("0", recordedRequest.getHeader("Content-Length")); + assertEquals(null, recordedRequest.getHeader("Content-Type")); + } + + @Test public void put() throws Exception { + server.enqueue(new MockResponse().setBody("abc")); + server.play(); + + Request request = new Request.Builder() + .url(server.getUrl("/")) + .put(Request.Body.create(MediaType.parse("text/plain"), "def")) + .build(); + + executeSynchronously(request) + .assertCode(200) + .assertBody("abc"); + + RecordedRequest recordedRequest = server.takeRequest(); + assertEquals("PUT", recordedRequest.getMethod()); + assertEquals("def", recordedRequest.getUtf8Body()); + assertEquals("3", recordedRequest.getHeader("Content-Length")); + assertEquals("text/plain; charset=utf-8", recordedRequest.getHeader("Content-Type")); + } + + @Test public void patch() throws Exception { + server.enqueue(new MockResponse().setBody("abc")); + server.play(); + + Request request = new Request.Builder() + .url(server.getUrl("/")) + .patch(Request.Body.create(MediaType.parse("text/plain"), "def")) + .build(); + + executeSynchronously(request) + .assertCode(200) + .assertBody("abc"); + + RecordedRequest recordedRequest = server.takeRequest(); + assertEquals("PATCH", recordedRequest.getMethod()); + assertEquals("def", recordedRequest.getUtf8Body()); + assertEquals("3", recordedRequest.getHeader("Content-Length")); + assertEquals("text/plain; charset=utf-8", recordedRequest.getHeader("Content-Type")); + } + @Test public void illegalToExecuteTwice() throws Exception { server.enqueue(new MockResponse() .setBody("abc") @@ -127,25 +269,6 @@ public final class CallTest { assertTrue(server.takeRequest().getHeaders().contains("User-Agent: SyncApiTest")); } - @Test public void get() throws Exception { - server.enqueue(new MockResponse() - .setBody("abc") - .addHeader("Content-Type: text/plain")); - server.play(); - - Request request = new Request.Builder() - .url(server.getUrl("/")) - .header("User-Agent", "SyncApiTest") - .build(); - - executeSynchronously(request) - .assertCode(200) - .assertContainsHeaders("Content-Type: text/plain") - .assertBody("abc"); - - assertTrue(server.takeRequest().getHeaders().contains("User-Agent: SyncApiTest")); - } - @Test public void get_Async() throws Exception { server.enqueue(new MockResponse() .setBody("abc") @@ -340,25 +463,6 @@ public final class CallTest { assertEquals(301, response.code()); } - @Test public void post() throws Exception { - server.enqueue(new MockResponse().setBody("abc")); - server.play(); - - Request request = new Request.Builder() - .url(server.getUrl("/")) - .post(Request.Body.create(MediaType.parse("text/plain"), "def")) - .build(); - - executeSynchronously(request) - .assertCode(200) - .assertBody("abc"); - - RecordedRequest recordedRequest = server.takeRequest(); - assertEquals("def", recordedRequest.getUtf8Body()); - assertEquals("3", recordedRequest.getHeader("Content-Length")); - assertEquals("text/plain; charset=utf-8", recordedRequest.getHeader("Content-Type")); - } - @Test public void post_Async() throws Exception { server.enqueue(new MockResponse().setBody("abc")); server.play(); diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/RequestTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/RequestTest.java index fcb26b1fa..1878da5cf 100644 --- a/okhttp-tests/src/test/java/com/squareup/okhttp/RequestTest.java +++ b/okhttp-tests/src/test/java/com/squareup/okhttp/RequestTest.java @@ -23,6 +23,7 @@ import okio.Buffer; import org.junit.Test; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; public final class RequestTest { @Test public void string() throws Exception { @@ -73,6 +74,36 @@ public final class RequestTest { assertEquals("Retransmit body", "616263", bodyToHex(body)); } + /** Common verbs used for apis such as GitHub, AWS, and Google Cloud. */ + @Test public void crudVerbs() { + MediaType contentType = MediaType.parse("application/json"); + Request.Body body = Request.Body.create(contentType, "{}"); + + Request get = new Request.Builder().url("http://localhost/api").get().build(); + assertEquals("GET", get.method()); + assertNull(get.body()); + + Request head = new Request.Builder().url("http://localhost/api").head().build(); + assertEquals("HEAD", head.method()); + assertNull(head.body()); + + Request delete = new Request.Builder().url("http://localhost/api").delete().build(); + assertEquals("DELETE", delete.method()); + assertNull(delete.body()); + + Request post = new Request.Builder().url("http://localhost/api").post(body).build(); + assertEquals("POST", post.method()); + assertEquals(body, post.body()); + + Request put = new Request.Builder().url("http://localhost/api").put(body).build(); + assertEquals("PUT", put.method()); + assertEquals(body, put.body()); + + Request patch = new Request.Builder().url("http://localhost/api").patch(body).build(); + assertEquals("PATCH", patch.method()); + assertEquals(body, patch.body()); + } + private String bodyToHex(Request.Body body) throws IOException { Buffer buffer = new Buffer(); body.writeTo(buffer); diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/huc/JavaApiConverterTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/huc/JavaApiConverterTest.java index ac9b48fa8..060b11a95 100644 --- a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/huc/JavaApiConverterTest.java +++ b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/huc/JavaApiConverterTest.java @@ -209,7 +209,7 @@ public class JavaApiConverterTest { @Test public void createOkResponse_fromCacheResponse() throws Exception { final String statusLine = "HTTP/1.1 200 Fantastic"; URI uri = new URI("http://foo/bar"); - Request request = new Request.Builder().url(uri.toURL()).method("GET", null).build(); + Request request = new Request.Builder().url(uri.toURL()).build(); CacheResponse cacheResponse = new CacheResponse() { @Override public Map<String, List<String>> getHeaders() throws IOException { @@ -244,7 +244,7 @@ public class JavaApiConverterTest { final Principal serverPrincipal = SERVER_CERT.getSubjectX500Principal(); final List<Certificate> serverCertificates = Arrays.<Certificate>asList(SERVER_CERT); URI uri = new URI("https://foo/bar"); - Request request = new Request.Builder().url(uri.toURL()).method("GET", null).build(); + Request request = new Request.Builder().url(uri.toURL()).build(); SecureCacheResponse cacheResponse = new SecureCacheResponse() { @Override public Map<String, List<String>> getHeaders() throws IOException { @@ -517,7 +517,7 @@ public class JavaApiConverterTest { @Test public void createJavaUrlConnection_accessibleRequestInfo_GET() throws Exception { Request okRequest = createArbitraryOkRequest().newBuilder() - .method("GET", null) + .get() .build(); Response okResponse = createArbitraryOkResponse(okRequest); HttpURLConnection httpUrlConnection = JavaApiConverter.createJavaUrlConnection(okResponse); @@ -529,7 +529,7 @@ public class JavaApiConverterTest { @Test public void createJavaUrlConnection_accessibleRequestInfo_POST() throws Exception { Request okRequest = createArbitraryOkRequest().newBuilder() - .method("POST", createRequestBody("PostBody")) + .post(createRequestBody("PostBody")) .build(); Response okResponse = createArbitraryOkResponse(okRequest); HttpURLConnection httpUrlConnection = JavaApiConverter.createJavaUrlConnection(okResponse); @@ -541,7 +541,7 @@ public class JavaApiConverterTest { @Test public void createJavaUrlConnection_https_extraHttpsMethods() throws Exception { Request okRequest = createArbitraryOkRequest().newBuilder() - .method("GET", null) + .get() .url("https://secure/request") .build(); Handshake handshake = Handshake.get("SecureCipher", Arrays.<Certificate>asList(SERVER_CERT), @@ -584,7 +584,7 @@ public class JavaApiConverterTest { Request okRequest = createArbitraryOkRequest().newBuilder() .url("http://insecure/request") - .method("GET", null) + .get() .build(); Response okResponse = createArbitraryOkResponse(okRequest).newBuilder() .protocol(Protocol.HTTP_1_1) @@ -607,7 +607,7 @@ public class JavaApiConverterTest { Request okRequest = createArbitraryOkRequest().newBuilder() .url("http://insecure/request") - .method("POST", createRequestBody("RequestBody")) + .post(createRequestBody("RequestBody")) .build(); Response.Body responseBody = createResponseBody("ResponseBody"); Response okResponse = createArbitraryOkResponse(okRequest).newBuilder() @@ -631,7 +631,7 @@ public class JavaApiConverterTest { Request okRequest = createArbitraryOkRequest().newBuilder() .url("https://secure/request") - .method("POST", createRequestBody("RequestBody") ) + .post(createRequestBody("RequestBody") ) .build(); Response.Body responseBody = createResponseBody("ResponseBody"); Handshake handshake = Handshake.get("SecureCipher", Arrays.<Certificate>asList(SERVER_CERT), @@ -754,10 +754,7 @@ public class JavaApiConverterTest { } private static Request createArbitraryOkRequest() { - return new Request.Builder() - .url("http://arbitrary/url") - .method("GET", null) - .build(); + return new Request.Builder().url("http://arbitrary/url").build(); } private static Response createArbitraryOkResponse(Request request) { diff --git a/okhttp/src/main/java/com/squareup/okhttp/Call.java b/okhttp/src/main/java/com/squareup/okhttp/Call.java index 069a04440..3eba08ff1 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/Call.java +++ b/okhttp/src/main/java/com/squareup/okhttp/Call.java @@ -16,8 +16,11 @@ package com.squareup.okhttp; import com.squareup.okhttp.internal.NamedRunnable; +import com.squareup.okhttp.internal.Util; import com.squareup.okhttp.internal.http.HttpEngine; +import com.squareup.okhttp.internal.http.HttpMethod; import com.squareup.okhttp.internal.http.OkHeaders; +import com.squareup.okhttp.internal.http.RetryableSink; import java.io.IOException; import java.net.ProtocolException; import okio.BufferedSink; @@ -170,6 +173,7 @@ public final class Call { // Copy body metadata to the appropriate request headers. Request.Body body = request.body(); + RetryableSink requestBodyOut = null; if (body != null) { MediaType contentType = body.contentType(); if (contentType == null) throw new IllegalStateException("contentType == null"); @@ -187,10 +191,12 @@ public final class Call { } request = requestBuilder.build(); + } else if (HttpMethod.hasRequestBody(request.method())) { + requestBodyOut = Util.emptySink(); } // Create the initial HTTP engine. Retries and redirects need new engine for each attempt. - engine = new HttpEngine(client, request, false, null, null, null); + engine = new HttpEngine(client, request, false, null, null, requestBodyOut); while (true) { if (canceled) return null; diff --git a/okhttp/src/main/java/com/squareup/okhttp/Request.java b/okhttp/src/main/java/com/squareup/okhttp/Request.java index 937f3e39b..a6108e18f 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/Request.java +++ b/okhttp/src/main/java/com/squareup/okhttp/Request.java @@ -276,10 +276,18 @@ public final class Request { return method("POST", body); } + public Builder delete() { + return method("DELETE", null); + } + public Builder put(Body body) { return method("PUT", body); } + public Builder patch(Body body) { + return method("PATCH", body); + } + public Builder method(String method, Body body) { if (method == null || method.length() == 0) { throw new IllegalArgumentException("method == null || method.length() == 0"); diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/Util.java b/okhttp/src/main/java/com/squareup/okhttp/internal/Util.java index c481ee274..1b86147d1 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/internal/Util.java +++ b/okhttp/src/main/java/com/squareup/okhttp/internal/Util.java @@ -16,6 +16,7 @@ package com.squareup.okhttp.internal; +import com.squareup.okhttp.internal.http.RetryableSink; import com.squareup.okhttp.internal.spdy.Header; import java.io.Closeable; import java.io.File; @@ -222,4 +223,10 @@ public final class Util { } return result; } + + public static RetryableSink emptySink() { + return EMPTY_SINK; + } + + private static final RetryableSink EMPTY_SINK = new RetryableSink(0); } diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java b/okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java index 5647f0b73..f5579b3dc 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java +++ b/okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java @@ -28,6 +28,7 @@ import com.squareup.okhttp.Response; import com.squareup.okhttp.ResponseSource; import com.squareup.okhttp.Route; import com.squareup.okhttp.internal.Dns; +import com.squareup.okhttp.internal.Util; import java.io.IOException; import java.io.InputStream; import java.net.CacheRequest; @@ -283,7 +284,7 @@ public final class HttpEngine { } boolean hasRequestBody() { - return HttpMethod.hasRequestBody(request.method()); + return HttpMethod.hasRequestBody(request.method()) && !Util.emptySink().equals(requestBodyOut); } /** Returns the request body or null if this request doesn't have a body. */ diff --git a/samples/guide/src/main/java/com/squareup/okhttp/guide/PostExample.java b/samples/guide/src/main/java/com/squareup/okhttp/guide/PostExample.java index 68ac4e043..313e82744 100644 --- a/samples/guide/src/main/java/com/squareup/okhttp/guide/PostExample.java +++ b/samples/guide/src/main/java/com/squareup/okhttp/guide/PostExample.java @@ -12,10 +12,7 @@ public class PostExample { void run() throws IOException { String json = bowlingJson("Jesse", "Jake"); Request.Body body = Request.Body.create(MediaType.parse("application/json"), json); - Request request = new Request.Builder() - .url("http://www.roundsapp.com/post") - .method("POST", body) - .build(); + Request request = new Request.Builder().url("http://www.roundsapp.com/post").post(body).build(); Response response = client.newCall(request).execute(); System.out.println(response.body().string());
['okhttp-tests/src/test/java/com/squareup/okhttp/internal/huc/JavaApiConverterTest.java', 'okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java', 'okhttp/src/main/java/com/squareup/okhttp/Call.java', 'okhttp/src/main/java/com/squareup/okhttp/Request.java', 'okhttp/src/main/java/com/squareup/okhttp/internal/Util.java', 'samples/guide/src/main/java/com/squareup/okhttp/guide/PostExample.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/RequestTest.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java']
{'.java': 8}
8
8
0
0
8
665,782
150,731
19,663
94
1,266
272
31
5
761
109
172
18
0
1
1970-01-01T00:23:18
44,252
Kotlin
{'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995}
Apache License 2.0
165
square/okhttp/939/933
square
okhttp
https://github.com/square/okhttp/issues/933
https://github.com/square/okhttp/pull/939
https://github.com/square/okhttp/pull/939
1
closes
Certain SPDY requests always timeout
This simple request to fetch a .mp3 always timeouts. Some requests to the same domain work though. Other clients (Browsers, curl, etc) have no problem. ``` java String url = "https://s.auspiel.de/sounds/effects/mischen-1.mp3"; OkHttpClient httpClient = new OkHttpClient(); httpClient.setReadTimeout(10, TimeUnit.SECONDS); Call call = httpClient.newCall(new Request.Builder(). url(url). tag(url). get().build()); call.enqueue(new com.squareup.okhttp.Callback() { @Override public void onFailure(Request request, Throwable throwable) { System.out.println("Failure"); } @Override public void onResponse(Response response) throws IOException { System.out.println("GOT RESPONSE"); byte[] responseData = response.body().bytes(); System.out.println("READ BODY"); // this is never reached } }); ``` Example repo: https://github.com/MSch/okhttp-spdy-timeout https://github.com/MSch/okhttp-spdy-timeout/blob/master/app/src/main/java/msch/okhttpbug/MyActivity.java#L25-L40 I also tried with OkHttp 2.0.0-RC2 and OkIo master. Same issue. e.g. https://s.auspiel.de/sounds/male/bayerisch/greeting/begruessung-1.mp3 works. Tested devices: Samsung Galaxy Nexus with Android 4.2.2 and Asus Nexus 7 with Android 4.4.2 ``` E/AndroidRuntime﹕ FATAL EXCEPTION: OkHttp Dispatcher java.lang.RuntimeException: java.io.InterruptedIOException: timeout at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:153) at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) at java.lang.Thread.run(Thread.java:856) Caused by: java.io.InterruptedIOException: timeout at com.squareup.okhttp.internal.spdy.SpdyStream$SpdyTimeout.exitAndThrowIfTimedOut(SpdyStream.java:573) at com.squareup.okhttp.internal.spdy.SpdyStream$SpdyDataSource.waitUntilReadable(SpdyStream.java:380) at com.squareup.okhttp.internal.spdy.SpdyStream$SpdyDataSource.read(SpdyStream.java:343) at com.squareup.okhttp.internal.http.SpdyTransport$SpdySource.read(SpdyTransport.java:273) at okio.Buffer.writeAll(Buffer.java:574) at okio.RealBufferedSource.readByteArray(RealBufferedSource.java:87) at com.squareup.okhttp.ResponseBody.bytes(ResponseBody.java:56) at msch.okhttpbug.MyActivity$1.onResponse(MyActivity.java:37) at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:150)             at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)             at java.lang.Thread.run(Thread.java:856) ```
7213e9b6b9e1508c349ccd6b13b894bd5d8bf96d
6171f554512ce314d5b7008fc660a1697887581c
https://github.com/square/okhttp/compare/7213e9b6b9e1508c349ccd6b13b894bd5d8bf96d...6171f554512ce314d5b7008fc660a1697887581c
diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Http2ConnectionTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Http2ConnectionTest.java index 5bcb09e38..e700dd6c6 100644 --- a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Http2ConnectionTest.java +++ b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Http2ConnectionTest.java @@ -211,17 +211,17 @@ public final class Http2ConnectionTest { @Test public void readSendsWindowUpdateHttp2() throws Exception { peer.setVariantAndClient(HTTP_2, false); - int windowUpdateThreshold = DEFAULT_INITIAL_WINDOW_SIZE / 2; + int windowSize = 100; + int windowUpdateThreshold = 50; // Write the mocking script. peer.acceptFrame(); // SYN_STREAM peer.sendFrame().synReply(false, 3, headerEntries("a", "android")); for (int i = 0; i < 3; i++) { - // Send frames summing to windowUpdateThreshold. - for (int sent = 0, count; sent < windowUpdateThreshold; sent += count) { - count = Math.min(HTTP_2.maxFrameSize(), windowUpdateThreshold - sent); - peer.sendFrame().data(false, 3, data(count)); - } + // Send frames of summing to size 50, which is windowUpdateThreshold. + peer.sendFrame().data(false, 3, data(24)); + peer.sendFrame().data(false, 3, data(25)); + peer.sendFrame().data(false, 3, data(1)); peer.acceptFrame(); // connection WINDOW UPDATE peer.acceptFrame(); // stream WINDOW UPDATE } @@ -230,15 +230,15 @@ public final class Http2ConnectionTest { // Play it back. SpdyConnection connection = connection(peer, HTTP_2); + connection.okHttpSettings.set(Settings.INITIAL_WINDOW_SIZE, 0, windowSize); SpdyStream stream = connection.newStream(headerEntries("b", "banana"), false, true); assertEquals(0, stream.unacknowledgedBytesRead); assertEquals(headerEntries("a", "android"), stream.getResponseHeaders()); Source in = stream.getSource(); Buffer buffer = new Buffer(); - while (in.read(buffer, 1024) != -1) { - if (buffer.size() == 3 * windowUpdateThreshold) break; - } + buffer.writeAll(in); assertEquals(-1, in.read(buffer, 1)); + assertEquals(150, buffer.size()); MockSpdyPeer.InFrame synStream = peer.takeFrame(); assertEquals(TYPE_HEADERS, synStream.type); diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Spdy3ConnectionTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Spdy3ConnectionTest.java index 862e2f34a..a6c970362 100644 --- a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Spdy3ConnectionTest.java +++ b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Spdy3ConnectionTest.java @@ -1013,17 +1013,17 @@ public final class Spdy3ConnectionTest { @Test public void readSendsWindowUpdate() throws Exception { peer.setVariantAndClient(SPDY3, false); - int windowUpdateThreshold = DEFAULT_INITIAL_WINDOW_SIZE / 2; + int windowSize = 100; + int windowUpdateThreshold = 50; // Write the mocking script. peer.acceptFrame(); // SYN_STREAM peer.sendFrame().synReply(false, 1, headerEntries("a", "android")); for (int i = 0; i < 3; i++) { - // Send frames summing to windowUpdateThreshold. - for (int sent = 0, count; sent < windowUpdateThreshold; sent += count) { - count = Math.min(SPDY3.maxFrameSize(), windowUpdateThreshold - sent); - peer.sendFrame().data(false, 1, data(count)); - } + // Send frames of summing to size 50, which is windowUpdateThreshold. + peer.sendFrame().data(false, 1, data(24)); + peer.sendFrame().data(false, 1, data(25)); + peer.sendFrame().data(false, 1, data(1)); peer.acceptFrame(); // connection WINDOW UPDATE peer.acceptFrame(); // stream WINDOW UPDATE } @@ -1032,15 +1032,15 @@ public final class Spdy3ConnectionTest { // Play it back. SpdyConnection connection = connection(peer, SPDY3); + connection.okHttpSettings.set(Settings.INITIAL_WINDOW_SIZE, 0, windowSize); SpdyStream stream = connection.newStream(headerEntries("b", "banana"), false, true); assertEquals(0, stream.unacknowledgedBytesRead); assertEquals(headerEntries("a", "android"), stream.getResponseHeaders()); Source in = stream.getSource(); Buffer buffer = new Buffer(); - while (in.read(buffer, 1024) != -1) { - if (buffer.size() == 3 * windowUpdateThreshold) break; - } + buffer.writeAll(in); assertEquals(-1, in.read(buffer, 1)); + assertEquals(150, buffer.size()); MockSpdyPeer.InFrame synStream = peer.takeFrame(); assertEquals(TYPE_HEADERS, synStream.type); diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java index bceb25784..8e22f702c 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java +++ b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java @@ -113,6 +113,7 @@ public final class SpdyConnection implements Closeable { // TODO: Do we want to dynamically adjust settings, or KISS and only set once? final Settings okHttpSettings = new Settings(); // okHttpSettings.set(Settings.MAX_CONCURRENT_STREAMS, 0, max); + private static final int OKHTTP_CLIENT_WINDOW_SIZE = 16 * 1024 * 1024; /** Settings we receive from the peer. */ // TODO: MWS will need to guard on this setting before attempting to push. @@ -145,7 +146,7 @@ public final class SpdyConnection implements Closeable { // thrashing window updates every 64KiB, yet small enough to avoid blowing // up the heap. if (builder.client) { - okHttpSettings.set(Settings.INITIAL_WINDOW_SIZE, 0, 16 * 1024 * 1024); + okHttpSettings.set(Settings.INITIAL_WINDOW_SIZE, 0, OKHTTP_CLIENT_WINDOW_SIZE); } hostName = builder.hostName; @@ -503,6 +504,10 @@ public final class SpdyConnection implements Closeable { public void sendConnectionPreface() throws IOException { frameWriter.connectionPreface(); frameWriter.settings(okHttpSettings); + int windowSize = okHttpSettings.getInitialWindowSize(Settings.DEFAULT_INITIAL_WINDOW_SIZE); + if (windowSize != Settings.DEFAULT_INITIAL_WINDOW_SIZE) { + frameWriter.windowUpdate(0, windowSize - Settings.DEFAULT_INITIAL_WINDOW_SIZE); + } } public static class Builder { diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java index 7eb78cbef..331536d37 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java +++ b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java @@ -350,7 +350,7 @@ public final class SpdyStream { // Flow control: notify the peer that we're ready for more data! unacknowledgedBytesRead += read; if (unacknowledgedBytesRead - >= connection.peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE) / 2) { + >= connection.okHttpSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE) / 2) { connection.writeWindowUpdateLater(id, unacknowledgedBytesRead); unacknowledgedBytesRead = 0; } @@ -360,7 +360,7 @@ public final class SpdyStream { synchronized (connection) { // Multiple application threads may hit this section. connection.unacknowledgedBytesRead += read; if (connection.unacknowledgedBytesRead - >= connection.peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE) / 2) { + >= connection.okHttpSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE) / 2) { connection.writeWindowUpdateLater(0, connection.unacknowledgedBytesRead); connection.unacknowledgedBytesRead = 0; }
['okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Http2ConnectionTest.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Spdy3ConnectionTest.java', 'okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java', 'okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java']
{'.java': 4}
4
4
0
0
4
723,492
163,303
21,251
113
883
192
11
2
2,973
166
700
55
4
2
1970-01-01T00:23:23
44,252
Kotlin
{'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995}
Apache License 2.0
164
square/okhttp/948/947
square
okhttp
https://github.com/square/okhttp/issues/947
https://github.com/square/okhttp/pull/948
https://github.com/square/okhttp/pull/948
1
closes
Caching broken by transparent gzip header mismatch
Following the technique described in the Cache javadoc (http://square.github.io/okhttp/javadoc/com/squareup/okhttp/Cache.html) we added the Cache-Control max-stale header to ensure we get a cached response when offline. We're doing this through Retrofit's RequestInterceptor, like so: ``` requestFacade.addHeader("Cache-Control", "max-stale=" + maxStale); ``` This works great in okhttp 1.6: we get a response when offline. However, it no longer works in 2.0RC2 (or master). After some debugging, it turns out there _is_ a cache Response, but it's not returned after this test in Cache.get(Request): ``` if (!entry.matches(request, response)) ``` which in turn is caused by OkHeaders.varyMatches(), which returns false for the Accept-Encoding field: cachedField [], actualField: [gzip]. This issue can be worked around by performing the gzip "by hand" by adding our own gzip header and decompressing the resulting response when necessary (this was not necessary in 1.6), as I described here, after an unrelated transparent gzip issue in an earlier version of okhttp: http://stackoverflow.com/questions/21585347/retrofit-okhttp-retrieve-gzipinputstream/22537697#22537697
eb40f47753ce1a7d45bb3fbcf7eb28ac6e7e2479
94f9a1719cc420be061b16e2da03258552c5060b
https://github.com/square/okhttp/compare/eb40f47753ce1a7d45bb3fbcf7eb28ac6e7e2479...94f9a1719cc420be061b16e2da03258552c5060b
diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java index 93163450b..b78a68e92 100644 --- a/okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java +++ b/okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java @@ -920,6 +920,19 @@ public final class CacheTest { assertEquals("DEFDEFDEF", readAscii(client.open(server.getUrl("/")))); } + /** https://github.com/square/okhttp/issues/947 */ + @Test public void gzipAndVaryOnAcceptEncoding() throws Exception { + server.enqueue(new MockResponse() + .setBody(gzip("ABCABCABC")) + .addHeader("Content-Encoding: gzip") + .addHeader("Vary: Accept-Encoding") + .addHeader("Cache-Control: max-age=60")); + server.enqueue(new MockResponse().setBody("FAIL")); + + assertEquals("ABCABCABC", readAscii(client.open(server.getUrl("/")))); + assertEquals("ABCABCABC", readAscii(client.open(server.getUrl("/")))); + } + @Test public void conditionalCacheHitIsNotDoublePooled() throws Exception { server.enqueue(new MockResponse().addHeader("ETag: v1").setBody("A")); server.enqueue(new MockResponse() diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/http/OkHeaders.java b/okhttp/src/main/java/com/squareup/okhttp/internal/http/OkHeaders.java index 6736801fe..b09801b48 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/internal/http/OkHeaders.java +++ b/okhttp/src/main/java/com/squareup/okhttp/internal/http/OkHeaders.java @@ -174,8 +174,12 @@ public final class OkHeaders { Set<String> varyFields = varyFields(response); if (varyFields.isEmpty()) return new Headers.Builder().build(); + // Use the request headers sent over the network, since that's what the + // response varies on. Otherwise OkHttp-supplied headers like + // "Accept-Encoding: gzip" may be lost. + Headers requestHeaders = response.networkResponse().request().headers(); + Headers.Builder result = new Headers.Builder(); - Headers requestHeaders = response.request().headers(); for (int i = 0; i < requestHeaders.size(); i++) { String fieldName = requestHeaders.name(i); if (varyFields.contains(fieldName)) {
['okhttp/src/main/java/com/squareup/okhttp/internal/http/OkHeaders.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java']
{'.java': 2}
2
2
0
0
2
724,213
163,458
21,264
113
328
66
6
1
1,178
150
280
16
2
2
1970-01-01T00:23:23
44,252
Kotlin
{'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995}
Apache License 2.0
155
square/okhttp/1065/1036
square
okhttp
https://github.com/square/okhttp/issues/1036
https://github.com/square/okhttp/pull/1065
https://github.com/square/okhttp/pull/1065#issuecomment-57098303
1
fixes
okhttp 2.0.0 OkHttpClient.cancel(tag) doesn't work
The Recipes [Canceling a Call](https://github.com/square/okhttp/wiki/Recipes#canceling-a-call) worked, but after I used `OkHttpClient.cancel(tag)` instead, it didn't work. My code: ``` java import java.io.IOException; import java.util.concurrent.*; import com.squareup.okhttp.*; public class Test { private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { Request request = new Request.Builder() .url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay. .tag("asdf") .build(); final long startNanos = System.nanoTime(); final Call call = client.newCall(request); // Schedule a job to cancel the call in 1 second. executor.schedule(new Runnable() { @Override public void run() { System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f); client.cancel("asdf"); System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f); } }, 1, TimeUnit.SECONDS); try { System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f); Response response = call.execute(); System.out.printf("%.2f Call was expected to fail, but completed: %s%n", (System.nanoTime() - startNanos) / 1e9f, response); } catch (IOException e) { System.out.printf("%.2f Call failed as expected: %s%n", (System.nanoTime() - startNanos) / 1e9f, e); } } public static void main(String[] args) throws Exception { new Test().run(); } } ``` Result: ``` 0.25 Executing call. 1.25 Canceling call. 1.25 Canceled call. 3.46 Call was expected to fail, but completed: Response{protocol=http/1.1, code=200, message=OK, url=http://httpbin.org/delay/2} ```
4cdf0a90b3643d198014a56bf619dd9587820fca
38d57953ee7a22a6f87d97ed15e69f17abb2c16f
https://github.com/square/okhttp/compare/4cdf0a90b3643d198014a56bf619dd9587820fca...38d57953ee7a22a6f87d97ed15e69f17abb2c16f
diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java index 40519c61d..cefb681be 100644 --- a/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java +++ b/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java @@ -1172,6 +1172,33 @@ public final class CallTest { assertEquals(1, server.getRequestCount()); } + @Test public void cancelInFlightBeforeResponseReadThrowsIOE() throws Exception { + server.setDispatcher(new Dispatcher() { + @Override public MockResponse dispatch(RecordedRequest request) { + client.cancel("request"); + return new MockResponse().setBody("A"); + } + }); + server.play(); + + Request request = new Request.Builder().url(server.getUrl("/a")).tag("request").build(); + try { + client.newCall(request).execute(); + fail(); + } catch (IOException e) { + } + } + + @Test public void cancelInFlightBeforeResponseReadThrowsIOE_HTTP_2() throws Exception { + enableProtocol(Protocol.HTTP_2); + cancelInFlightBeforeResponseReadThrowsIOE(); + } + + @Test public void cancelInFlightBeforeResponseReadThrowsIOE_SPDY_3() throws Exception { + enableProtocol(Protocol.SPDY_3); + cancelInFlightBeforeResponseReadThrowsIOE(); + } + /** * This test puts a request in front of one that is to be canceled, so that it is canceled before * I/O takes place. diff --git a/okhttp/src/main/java/com/squareup/okhttp/Call.java b/okhttp/src/main/java/com/squareup/okhttp/Call.java index db2cf6107..785a9db38 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/Call.java +++ b/okhttp/src/main/java/com/squareup/okhttp/Call.java @@ -77,10 +77,20 @@ public class Call { if (executed) throw new IllegalStateException("Already Executed"); executed = true; } - Response result = getResponse(); - engine.releaseConnection(); // Transfer ownership of the body to the caller. - if (result == null) throw new IOException("Canceled"); - return result; + try { + client.getDispatcher().executed(this); + Response result = getResponse(); + System.out.println("releasing"); + engine.releaseConnection(); // Transfer ownership of the body to the caller. + if (result == null) throw new IOException("Canceled"); + return result; + } finally { + client.getDispatcher().finished(this); + } + } + + Object tag() { + return request.tag(); } /** diff --git a/okhttp/src/main/java/com/squareup/okhttp/Dispatcher.java b/okhttp/src/main/java/com/squareup/okhttp/Dispatcher.java index 0e4644d5b..21f60254a 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/Dispatcher.java +++ b/okhttp/src/main/java/com/squareup/okhttp/Dispatcher.java @@ -46,6 +46,9 @@ public final class Dispatcher { /** Running calls. Includes canceled calls that haven't finished yet. */ private final Deque<AsyncCall> runningCalls = new ArrayDeque<>(); + /** In-flight synchronous calls. Includes canceled calls that haven't finished yet. */ + private final Deque<Call> executedCalls = new ArrayDeque<>(); + public Dispatcher(ExecutorService executorService) { this.executorService = executorService; } @@ -123,6 +126,12 @@ public final class Dispatcher { if (engine != null) engine.disconnect(); } } + + for (Call call : executedCalls) { + if (Util.equal(tag, call.tag())) { + call.cancel(); + } + } } /** Used by {@code AsyncCall#run} to signal completion. */ @@ -156,4 +165,14 @@ public final class Dispatcher { } return result; } + + /** Used by {@code Call#execute} to signal it is in-flight. */ + synchronized void executed(Call call) { + executedCalls.add(call); + } + + /** Used by {@code Call#execute} to signal completion. */ + synchronized void finished(Call call) { + if (!executedCalls.remove(call)) throw new AssertionError("Call wasn't in-flight!"); + } } diff --git a/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java b/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java index 916062617..69029dfa4 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java +++ b/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java @@ -467,8 +467,8 @@ public class OkHttpClient implements Cloneable { } /** - * Cancels all scheduled tasks tagged with {@code tag}. Requests that are already - * complete cannot be canceled. + * Cancels all scheduled or in-flight calls tagged with {@code tag}. Requests + * that are already complete cannot be canceled. */ public OkHttpClient cancel(Object tag) { getDispatcher().cancel(tag);
['okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java', 'okhttp/src/main/java/com/squareup/okhttp/Dispatcher.java', 'okhttp/src/main/java/com/squareup/okhttp/Call.java']
{'.java': 4}
4
4
0
0
4
725,400
163,726
21,246
114
1,504
317
41
3
2,017
201
485
57
3
2
1970-01-01T00:23:31
44,252
Kotlin
{'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995}
Apache License 2.0
156
square/okhttp/1259/1043
square
okhttp
https://github.com/square/okhttp/issues/1043
https://github.com/square/okhttp/pull/1259
https://github.com/square/okhttp/pull/1259
1
closes
Don't recover if a non-GET request fails
Currently it can silently retry requests, but now it's forbidden: http://tools.ietf.org/html/rfc7230 A user agent MUST NOT automatically retry a request with a non- idempotent method unless it has some means to know that the request semantics are actually idempotent, regardless of the method, or some means to detect that the original request was never applied. related to https://github.com/square/okhttp/issues/258
24750b59c4a06e77635cec6ce6999c3db86ff7e4
786e3b3048b84721c73a046b02a9edcbb6927686
https://github.com/square/okhttp/compare/24750b59c4a06e77635cec6ce6999c3db86ff7e4...786e3b3048b84721c73a046b02a9edcbb6927686
diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java index 25eb85f95..2255dd8f6 100644 --- a/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java +++ b/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java @@ -704,6 +704,34 @@ public final class CallTest { callback.await(request.url()).assertHandshake(); } + @Test public void recoverWhenRetryOnConnectionFailureIsTrue() throws Exception { + server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); + server.enqueue(new MockResponse().setBody("retry success")); + + Internal.instance.setNetwork(client, new DoubleInetAddressNetwork()); + assertTrue(client.getRetryOnConnectionFailure()); + + Request request = new Request.Builder().url(server.getUrl("/")).build(); + Response response = client.newCall(request).execute(); + assertEquals("retry success", response.body().string()); + } + + @Test public void noRecoverWhenRetryOnConnectionFailureIsFalse() throws Exception { + server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); + server.enqueue(new MockResponse().setBody("unreachable!")); + + Internal.instance.setNetwork(client, new DoubleInetAddressNetwork()); + client.setRetryOnConnectionFailure(false); + + Request request = new Request.Builder().url(server.getUrl("/")).build(); + try { + // If this succeeds, too many requests were made. + client.newCall(request).execute(); + fail(); + } catch (IOException expected) { + } + } + @Test public void recoverFromTlsHandshakeFailure() throws Exception { server.get().useHttps(sslContext.getSocketFactory(), false); server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE)); diff --git a/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java b/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java index 09716a78b..71e646097 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java +++ b/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java @@ -178,6 +178,7 @@ public class OkHttpClient implements Cloneable { private Network network; private boolean followSslRedirects = true; private boolean followRedirects = true; + private boolean retryOnConnectionFailure = true; private int connectTimeout; private int readTimeout; private int writeTimeout; @@ -208,6 +209,7 @@ public class OkHttpClient implements Cloneable { this.network = okHttpClient.network; this.followSslRedirects = okHttpClient.followSslRedirects; this.followRedirects = okHttpClient.followRedirects; + this.retryOnConnectionFailure = okHttpClient.retryOnConnectionFailure; this.connectTimeout = okHttpClient.connectTimeout; this.readTimeout = okHttpClient.readTimeout; this.writeTimeout = okHttpClient.writeTimeout; @@ -449,6 +451,32 @@ public class OkHttpClient implements Cloneable { return followRedirects; } + /** + * Configure this client to retry or not when a connectivity problem is encountered. By default, + * this client silently recovers from the following problems: + * + * <ul> + * <li><strong>Unreachable IP addresses.</strong> If the URL's host has multiple IP addresses, + * failure to reach any individual IP address doesn't fail the overall request. This can + * increase availability of multi-homed services. + * <li><strong>Stale pooled connections.</strong> The {@link ConnectionPool} reuses sockets + * to decrease request latency, but these connections will occasionally time out. + * <li><strong>Unreachable proxy servers.</strong> A {@link ProxySelector} can be used to + * attempt multiple proxy servers in sequence, eventually falling back to a direct + * connection. + * </ul> + * + * Set this to false to avoid retrying requests when doing so is destructive. In this case the + * calling application should do its own recovery of connectivity failures. + */ + public final void setRetryOnConnectionFailure(boolean retryOnConnectionFailure) { + this.retryOnConnectionFailure = retryOnConnectionFailure; + } + + public final boolean getRetryOnConnectionFailure() { + return retryOnConnectionFailure; + } + final RouteDatabase routeDatabase() { return routeDatabase; } diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java b/okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java index 461f066c8..d4d9b4cb1 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java +++ b/okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java @@ -391,6 +391,11 @@ public final class HttpEngine { } private boolean isRecoverable(IOException e) { + // If the application has opted-out of recovery, don't recover. + if (!client.getRetryOnConnectionFailure()) { + return false; + } + // If the problem was a CertificateException from the X509TrustManager, // do not retry, we didn't have an abrupt server-initiated exception. if (e instanceof SSLPeerUnverifiedException
['okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java', 'okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java']
{'.java': 3}
3
3
0
0
3
876,114
202,976
24,677
132
1,578
336
33
2
430
58
96
11
2
0
1970-01-01T00:23:39
44,252
Kotlin
{'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995}
Apache License 2.0
157
square/okhttp/1254/1158
square
okhttp
https://github.com/square/okhttp/issues/1158
https://github.com/square/okhttp/pull/1254
https://github.com/square/okhttp/pull/1254
1
closes
Should okhttp be caching HTTP 307 (or 302) responses according to the w3 document?
I am using retrofit and okhttp in my Android app to download documents, images and music files. The files are hosted on Amazon through a CDN so the URLs change often. My backend server will try to use redirects to decrease the need to have to constantly update my content on my mobile app every time the CDN url changes. The devices should also cache responses in the case that the device is offline. For this reason, I am using 301 redirects, which I don't know is the best idea. I was reading the description for 307 redirect at http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html --- 10.3.8 307 Temporary Redirect The requested resource resides temporarily under a different URI. Since the redirection MAY be altered on occasion, the client SHOULD continue to use the Request-URI for future requests. This response is only cacheable if indicated by a Cache-Control or Expires header field. --- At http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html, --- 13.4 - Response Cacheability A response received with a status code of 200, 203, 206, 300, 301 or 410 MAY be stored by a cache and used in reply to a subsequent request, subject to the expiration mechanism, unless a cache-control directive prohibits caching. However, a cache that does not support the Range and Content-Range headers MUST NOT cache 206 (Partial Content) responses. A response received with any other status code (e.g. status codes 302 and 307) MUST NOT be returned in a reply to a subsequent request unless there are cache-control directives or another header(s) that explicitly allow it. For example, these include the following: an Expires header (section 14.21); a "max-age", "s-maxage", "must- revalidate", "proxy-revalidate", "public" or "private" cache-control directive (section 14.9). --- It seems that the description states that caching is possible. I haven't tried this yet, but I did notice that in okhttp's CacheStrategy.java class, it has the following code: --- public static boolean isCacheable(Response response, Request request) { // Always go to network for uncacheable response codes (RFC 2616, 13.4), // This implementation doesn't support caching partial content. int responseCode = response.code(); if (responseCode != HttpURLConnection.HTTP_OK // 200 && responseCode != HttpURLConnection.HTTP_NOT_AUTHORITATIVE // 203 && responseCode != HttpURLConnection.HTTP_MULT_CHOICE // 300 && responseCode != HttpURLConnection.HTTP_MOVED_PERM / 301 && responseCode != HttpURLConnection.HTTP_GONE) { // 410 return false; } --- And to verify that caching isn't enabled for from 302-308, the unit tests from CacheTest.java states the following --- for (int i = 302; i <= 308; ++i) { assertCached(false, i); } --- So the okhttp code explicitly ignores caching for 307, and also 302. I just wanted clarification for this. Is the spec for 307 wrong? Or is something wrong with caching 307 that it was deliberately excluded? If I were to set my own cache headers for 307, it would seem to still be skipped. Just another background information. I know Amazon will support caching with proper cache headers. But since I have to redirect through my own backend, if I don't have caching ability, my offline access to my redirect URL will not respond that I have a cached version from CDN locally. Of course, if I didn't redirect from my backend and go straight to Amazon, then caching wouldn't be a problem through Amazon. Could you provide some advice in this scenario?
64f2af812bef505b6cbc1693aa8b504d9dbbb42e
1d6f0e75d599e2cb02f0fe182f7dbf966cd5cb2b
https://github.com/square/okhttp/compare/64f2af812bef505b6cbc1693aa8b504d9dbbb42e...1d6f0e75d599e2cb02f0fe182f7dbf966cd5cb2b
diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java index 9fba4601c..0fd174648 100644 --- a/okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java +++ b/okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java @@ -121,9 +121,12 @@ public final class CacheTest { assertCached(false, 207); assertCached(true, 300); assertCached(true, 301); - for (int i = 302; i <= 307; ++i) { - assertCached(false, i); - } + assertCached(true, 302); + assertCached(false, 303); + assertCached(false, 304); + assertCached(false, 305); + assertCached(false, 306); + assertCached(true, 307); assertCached(true, 308); for (int i = 400; i <= 406; ++i) { assertCached(false, i); @@ -394,6 +397,63 @@ public final class CacheTest { assertEquals(2, cache.getHitCount()); } + @Test public void foundCachedWithExpiresHeader() throws Exception { + temporaryRedirectCachedWithCachingHeader(302, "Expires", formatDate(1, TimeUnit.HOURS)); + } + + @Test public void foundCachedWithCacheControlHeader() throws Exception { + temporaryRedirectCachedWithCachingHeader(302, "Cache-Control", "max-age=60"); + } + + @Test public void temporaryRedirectCachedWithExpiresHeader() throws Exception { + temporaryRedirectCachedWithCachingHeader(307, "Expires", formatDate(1, TimeUnit.HOURS)); + } + + @Test public void temporaryRedirectCachedWithCacheControlHeader() throws Exception { + temporaryRedirectCachedWithCachingHeader(307, "Cache-Control", "max-age=60"); + } + + @Test public void foundNotCachedWithoutCacheHeader() throws Exception { + temporaryRedirectNotCachedWithoutCachingHeader(302); + } + + @Test public void temporaryRedirectNotCachedWithoutCacheHeader() throws Exception { + temporaryRedirectNotCachedWithoutCachingHeader(307); + } + + private void temporaryRedirectCachedWithCachingHeader( + int responseCode, String headerName, String headerValue) throws Exception { + server.enqueue(new MockResponse() + .setResponseCode(responseCode) + .addHeader(headerName, headerValue) + .addHeader("Location", "/a")); + server.enqueue(new MockResponse() + .addHeader(headerName, headerValue) + .setBody("a")); + server.enqueue(new MockResponse() + .setBody("b")); + server.enqueue(new MockResponse() + .setBody("c")); + + URL url = server.getUrl("/"); + assertEquals("a", get(url).body().string()); + assertEquals("a", get(url).body().string()); + } + + private void temporaryRedirectNotCachedWithoutCachingHeader(int responseCode) throws Exception { + server.enqueue(new MockResponse() + .setResponseCode(responseCode) + .addHeader("Location", "/a")); + server.enqueue(new MockResponse() + .setBody("a")); + server.enqueue(new MockResponse() + .setBody("b")); + + URL url = server.getUrl("/"); + assertEquals("a", get(url).body().string()); + assertEquals("b", get(url).body().string()); + } + @Test public void serverDisconnectsPrematurelyWithContentLengthHeader() throws IOException { testServerPrematureDisconnect(TransferKind.FIXED_LENGTH); } diff --git a/okhttp-urlconnection/src/test/java/com/squareup/okhttp/UrlConnectionCacheTest.java b/okhttp-urlconnection/src/test/java/com/squareup/okhttp/UrlConnectionCacheTest.java index 800124bdf..79d73f4ee 100644 --- a/okhttp-urlconnection/src/test/java/com/squareup/okhttp/UrlConnectionCacheTest.java +++ b/okhttp-urlconnection/src/test/java/com/squareup/okhttp/UrlConnectionCacheTest.java @@ -132,9 +132,12 @@ public final class UrlConnectionCacheTest { assertCached(false, 207); assertCached(true, 300); assertCached(true, 301); - for (int i = 302; i <= 307; ++i) { - assertCached(false, i); - } + assertCached(true, 302); + assertCached(false, 303); + assertCached(false, 304); + assertCached(false, 305); + assertCached(false, 306); + assertCached(true, 307); assertCached(true, 308); for (int i = 400; i <= 406; ++i) { assertCached(false, i); @@ -158,12 +161,12 @@ public final class UrlConnectionCacheTest { private void assertCached(boolean shouldPut, int responseCode) throws Exception { server = new MockWebServer(); - MockResponse response = - new MockResponse().addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) - .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) - .setResponseCode(responseCode) - .setBody("ABCDE") - .addHeader("WWW-Authenticate: challenge"); + MockResponse response = new MockResponse() + .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)) + .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)) + .setResponseCode(responseCode) + .setBody("ABCDE") + .addHeader("WWW-Authenticate: challenge"); if (responseCode == HttpURLConnection.HTTP_PROXY_AUTH) { response.addHeader("Proxy-Authenticate: Basic realm=\\"protected area\\""); } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) { diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/http/CacheStrategy.java b/okhttp/src/main/java/com/squareup/okhttp/internal/http/CacheStrategy.java index 93c6d7e6d..69db3947f 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/internal/http/CacheStrategy.java +++ b/okhttp/src/main/java/com/squareup/okhttp/internal/http/CacheStrategy.java @@ -7,8 +7,10 @@ import com.squareup.okhttp.Response; import java.util.Date; import static com.squareup.okhttp.internal.http.StatusLine.HTTP_PERM_REDIRECT; +import static com.squareup.okhttp.internal.http.StatusLine.HTTP_TEMP_REDIRECT; import static java.net.HttpURLConnection.HTTP_GONE; import static java.net.HttpURLConnection.HTTP_MOVED_PERM; +import static java.net.HttpURLConnection.HTTP_MOVED_TEMP; import static java.net.HttpURLConnection.HTTP_MULT_CHOICE; import static java.net.HttpURLConnection.HTTP_NOT_AUTHORITATIVE; import static java.net.HttpURLConnection.HTTP_OK; @@ -39,26 +41,36 @@ public final class CacheStrategy { * request. */ public static boolean isCacheable(Response response, Request request) { - // Always go to network for uncacheable response codes (RFC 2616, 13.4), + // Always go to network for uncacheable response codes (RFC 7231 section 6.1), // This implementation doesn't support caching partial content. - int responseCode = response.code(); - if (responseCode != HTTP_OK - && responseCode != HTTP_NOT_AUTHORITATIVE - && responseCode != HTTP_MULT_CHOICE - && responseCode != HTTP_MOVED_PERM - && responseCode != HTTP_GONE - && responseCode != HTTP_PERM_REDIRECT) { - return false; - } + switch (response.code()) { + case HTTP_OK: + case HTTP_NOT_AUTHORITATIVE: + case HTTP_MULT_CHOICE: + case HTTP_MOVED_PERM: + case HTTP_GONE: + case HTTP_PERM_REDIRECT: + // These codes can be cached unless headers forbid it. + break; + + case HTTP_MOVED_TEMP: + case HTTP_TEMP_REDIRECT: + // These codes can only be cached with the right response headers. + if (response.header("Expires") != null + || response.cacheControl().maxAgeSeconds() != -1 + || response.cacheControl().sMaxAgeSeconds() != -1 + || response.cacheControl().isPublic()) { + break; + } + // Fall-through. - // A 'no-store' directive on request or response prevents the response from being cached. - CacheControl responseCaching = response.cacheControl(); - CacheControl requestCaching = request.cacheControl(); - if (responseCaching.noStore() || requestCaching.noStore()) { - return false; + default: + // All other codes cannot be cached. + return false; } - return true; + // A 'no-store' directive on request or response prevents the response from being cached. + return !response.cacheControl().noStore() && !request.cacheControl().noStore(); } public static class Factory {
['okhttp/src/main/java/com/squareup/okhttp/internal/http/CacheStrategy.java', 'okhttp-urlconnection/src/test/java/com/squareup/okhttp/UrlConnectionCacheTest.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java']
{'.java': 3}
3
3
0
0
3
875,001
202,735
24,643
132
1,919
416
44
1
3,541
539
802
69
2
0
1970-01-01T00:23:39
44,252
Kotlin
{'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995}
Apache License 2.0
160
square/okhttp/1122/1119
square
okhttp
https://github.com/square/okhttp/issues/1119
https://github.com/square/okhttp/pull/1122
https://github.com/square/okhttp/pull/1122
1
fixes
ConcurrentModificationException
I wouldn't deem this high priority but it did crash a device. Android 4.4.2 OkHttp 2.0.0 ``` bash java.util.ConcurrentModificationException at java.util.HashMap$HashIterator.nextEntry(HashMap.java:806) at java.util.HashMap$ValueIterator.next(HashMap.java:838) at com.squareup.okhttp.internal.spdy.SpdyConnection$Reader.settings(SourceFile:698) at com.squareup.okhttp.internal.spdy.Spdy3$Reader.readSettings$5f833cfd(SourceFile:278) at com.squareup.okhttp.internal.spdy.Spdy3$Reader.nextFrame$64dcaf67(SourceFile:165) at com.squareup.okhttp.internal.spdy.SpdyConnection$Reader.execute(SourceFile:574) at com.squareup.okhttp.internal.NamedRunnable.run(SourceFile:33) at java.lang.Thread.run(Thread.java:841) ``` [Crashlytics Link](http://crashes.to/s/fef087d43fb)
912d09e7da8830b831ee8f3461e0c66161fc82c8
3820b5c3355a0d5e48691c43481c6201a033a62c
https://github.com/square/okhttp/compare/912d09e7da8830b831ee8f3461e0c66161fc82c8...3820b5c3355a0d5e48691c43481c6201a033a62c
diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java index d3ebee2e3..458fb6db2 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java +++ b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java @@ -695,7 +695,7 @@ public final class SpdyConnection implements Closeable { } } if (streamsToNotify != null && delta != 0) { - for (SpdyStream stream : streams.values()) { + for (SpdyStream stream : streamsToNotify) { synchronized (stream) { stream.addBytesToWriteWindow(delta); }
['okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java']
{'.java': 1}
1
1
0
0
1
756,101
170,838
21,993
117
106
25
2
1
821
38
212
19
1
1
1970-01-01T00:23:35
44,252
Kotlin
{'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995}
Apache License 2.0
159
square/okhttp/1235/1191
square
okhttp
https://github.com/square/okhttp/issues/1191
https://github.com/square/okhttp/pull/1235
https://github.com/square/okhttp/pull/1235
1
closes
Crash with Facebook SDK
When I set `URL.setURLStreamHandlerFactory(new OkUrlFactory(client));` accordingly to https://github.com/square/picasso/issues/749, my app crashes because of the Facebook SDK : ``` Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.squareup.okhttp.internal.spdy.SpdyStream.close(com.squareup.okhttp.internal.spdy.ErrorCode)' on a null object reference at com.squareup.okhttp.internal.http.SpdyTransport.disconnect(SpdyTransport.java:221) at com.squareup.okhttp.internal.http.HttpEngine.disconnect(HttpEngine.java:465) at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.disconnect(HttpURLConnectionImpl.java:113) at com.squareup.okhttp.internal.huc.DelegatingHttpsURLConnection.disconnect(DelegatingHttpsURLConnection.java:93) at com.squareup.okhttp.internal.huc.HttpsURLConnectionImpl.disconnect(HttpsURLConnectionImpl.java:25) at com.facebook.internal.Utility.disconnectQuietly(Utility.java:464) at com.facebook.Request.executeConnectionAndWait(Request.java:1563) at com.facebook.Request.executeBatchAndWait(Request.java:1460) at com.facebook.Request.executeBatchAndWait(Request.java:1429) at com.facebook.Request.executeBatchAndWait(Request.java:1411) at com.facebook.Request.executeAndWait(Request.java:1383) at com.facebook.Request.executeAndWait(Request.java:1269) at com.facebook.internal.Utility.getAppSettingsQueryResponse(Utility.java:708) at com.facebook.internal.Utility.access$000(Utility.java:57) at com.facebook.internal.Utility$1.doInBackground(Utility.java:630) at com.facebook.internal.Utility$1.doInBackground(Utility.java:627) at android.os.AsyncTask$2.call(AsyncTask.java:288) at java.util.concurrent.FutureTask.run(FutureTask.java:237)             at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)             at java.lang.Thread.run(Thread.java:818) ``` Doesn't happen 100% of the time. Reproduced on Nexus 5 with Android 5.0 (LRX21O)
e536bca6d7b2eb64054ee9845ca43dab19b020a7
0e199f608909793892b7883614c0d20a94c27916
https://github.com/square/okhttp/compare/e536bca6d7b2eb64054ee9845ca43dab19b020a7...0e199f608909793892b7883614c0d20a94c27916
diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HttpOverSpdyTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HttpOverSpdyTest.java index 2c275e028..670361c60 100644 --- a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HttpOverSpdyTest.java +++ b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HttpOverSpdyTest.java @@ -16,6 +16,7 @@ package com.squareup.okhttp.internal.http; import com.squareup.okhttp.Cache; +import com.squareup.okhttp.ConnectionPool; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.OkUrlFactory; import com.squareup.okhttp.Protocol; @@ -426,6 +427,26 @@ public abstract class HttpOverSpdyTest { assertContains(requestB.getHeaders(), "cookie: c=oreo"); } + /** https://github.com/square/okhttp/issues/1191 */ + @Test public void disconnectWithStreamNotEstablished() throws Exception { + ConnectionPool connectionPool = new ConnectionPool(5, 5000); + client.client().setConnectionPool(connectionPool); + + server.enqueue(new MockResponse().setBody("abc")); + server.play(); + + // Disconnect before the stream is created. A connection is still established! + HttpURLConnection connection1 = client.open(server.getUrl("/")); + connection1.connect(); + connection1.disconnect(); + + // That connection is pooled, and it works. + assertEquals(1, connectionPool.getSpdyConnectionCount()); + HttpURLConnection connection2 = client.open(server.getUrl("/")); + assertContent("abc", connection2, 3); + assertEquals(0, server.takeRequest().getSequenceNumber()); + } + <T> void assertContains(Collection<T> collection, T value) { assertTrue(collection.toString(), collection.contains(value)); } diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/http/SpdyTransport.java b/okhttp/src/main/java/com/squareup/okhttp/internal/http/SpdyTransport.java index 0561ac38e..61b661081 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/internal/http/SpdyTransport.java +++ b/okhttp/src/main/java/com/squareup/okhttp/internal/http/SpdyTransport.java @@ -212,7 +212,7 @@ public final class SpdyTransport implements Transport { } @Override public void disconnect(HttpEngine engine) throws IOException { - stream.close(ErrorCode.CANCEL); + if (stream != null) stream.close(ErrorCode.CANCEL); } @Override public boolean canReuseConnection() {
['okhttp/src/main/java/com/squareup/okhttp/internal/http/SpdyTransport.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HttpOverSpdyTest.java']
{'.java': 2}
2
2
0
0
2
869,272
201,747
24,498
132
93
22
2
1
2,325
92
485
30
1
1
1970-01-01T00:23:39
44,252
Kotlin
{'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995}
Apache License 2.0
158
square/okhttp/1249/1239
square
okhttp
https://github.com/square/okhttp/issues/1239
https://github.com/square/okhttp/pull/1249
https://github.com/square/okhttp/pull/1249
1
closes
ConnectionPool is broken with MAX_CONNECTIONS_TO_CLEANUP
After merging @nfuller's recent leak fix, I noticed we have a new problem. Previously we were pretty eager to trim the idle connections down to the promised limits. An application that quickly created 100 connections would just as quickly see 95 of those connections evicted! With the new fix, it looks like we won't evict more than once every 5 minutes, and we won't evict more than 2 connections per round. That means that we can exceed our promised limits. We can fix this by replacing `Thread.sleep()` with `wait()` and invoke `notify()` where we're currently calling `scheduleCleanupAsRequired`. That'll cause the cleanup thread to take immediate action.
f1a27df8f9a895f6ef7c1e718e09c65726161a26
98c74ace40b089f2769afb3e56c59a64eef327cb
https://github.com/square/okhttp/compare/f1a27df8f9a895f6ef7c1e718e09c65726161a26...98c74ace40b089f2769afb3e56c59a64eef327cb
diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/ConnectionPoolTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/ConnectionPoolTest.java index 075153ddf..0bdc9f58a 100644 --- a/okhttp-tests/src/test/java/com/squareup/okhttp/ConnectionPoolTest.java +++ b/okhttp-tests/src/test/java/com/squareup/okhttp/ConnectionPoolTest.java @@ -443,6 +443,9 @@ public final class ConnectionPoolTest { pool.recycle(httpB); pool.share(spdyA); + // Give the cleanup callable time to run and settle down. + Thread.sleep(100); + // Kill http A. Util.closeQuietly(httpA.getSocket()); @@ -465,6 +468,31 @@ public final class ConnectionPoolTest { assertEquals(0, pool.getConnectionCount()); } + @Test public void maxIdleConnectionsLimitEnforced() throws Exception { + ConnectionPool pool = new ConnectionPool(2, KEEP_ALIVE_DURATION_MS); + + // Hit the max idle connections limit of 2. + pool.recycle(httpA); + pool.recycle(httpB); + Thread.sleep(100); // Give the cleanup callable time to run. + assertPooled(pool, httpB, httpA); + + // Adding httpC bumps httpA. + pool.recycle(httpC); + Thread.sleep(100); // Give the cleanup callable time to run. + assertPooled(pool, httpC, httpB); + + // Adding httpD bumps httpB. + pool.recycle(httpD); + Thread.sleep(100); // Give the cleanup callable time to run. + assertPooled(pool, httpD, httpC); + + // Adding httpE bumps httpC. + pool.recycle(httpE); + Thread.sleep(100); // Give the cleanup callable time to run. + assertPooled(pool, httpE, httpD); + } + @Test public void evictAllConnections() throws Exception { resetWithPoolSize(10); pool.recycle(httpA); diff --git a/okhttp/src/main/java/com/squareup/okhttp/Connection.java b/okhttp/src/main/java/com/squareup/okhttp/Connection.java index 45fc5e933..8d8586ea0 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/Connection.java +++ b/okhttp/src/main/java/com/squareup/okhttp/Connection.java @@ -316,14 +316,6 @@ public final class Connection { return spdyConnection == null || spdyConnection.isIdle(); } - /** - * Returns true if this connection has been idle for longer than - * {@code keepAliveDurationNs}. - */ - boolean isExpired(long keepAliveDurationNs) { - return getIdleStartTimeNs() < System.nanoTime() - keepAliveDurationNs; - } - /** * Returns the time in ns when this connection became idle. Undefined if * this connection is not idle. diff --git a/okhttp/src/main/java/com/squareup/okhttp/ConnectionPool.java b/okhttp/src/main/java/com/squareup/okhttp/ConnectionPool.java index 0390917ad..16a6adbd1 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/ConnectionPool.java +++ b/okhttp/src/main/java/com/squareup/okhttp/ConnectionPool.java @@ -52,7 +52,6 @@ import java.util.concurrent.TimeUnit; * initialized lazily. */ public final class ConnectionPool { - private static final int MAX_CONNECTIONS_TO_CLEANUP = 2; private static final long DEFAULT_KEEP_ALIVE_DURATION_MS = 5 * 60 * 1000; // 5 min private static final ConnectionPool systemDefault; @@ -93,36 +92,9 @@ public final class ConnectionPool { 0 /* corePoolSize */, 1 /* maximumPoolSize */, 60L /* keepAliveTime */, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), Util.threadFactory("OkHttp ConnectionPool", true)); - /** {@code true} if the pool is actively draining, {@code false} if it is currently empty. */ - private boolean draining; - private final Runnable connectionsCleanupRunnable = new Runnable() { - // An executing connectionsCleanupRunnable keeps a reference to the enclosing ConnectionPool, - // preventing the ConnectionPool from being garbage collected before all held connections have - // been explicitly closed. If this was not the case any open connections in the pool would - // trigger StrictMode violations in Android when they were garbage collected. http://b/18369687 @Override public void run() { - while (true) { - performCleanup(); - - // See whether this runnable should continue executing. - synchronized (ConnectionPool.this) { - if (connections.size() == 0) { - draining = false; - return; - } - } - - // Pause to avoid checking the pool too regularly, which would drain the battery on mobile - // devices. - try { - // Use the keep alive duration as a rough indicator of a good check interval. - long keepAliveDurationMillis = keepAliveDurationNs / (1000 * 1000); - Thread.sleep(keepAliveDurationMillis); - } catch (InterruptedException e) { - // Ignored. - } - } + runCleanupUntilPoolIsEmpty(); } }; @@ -188,7 +160,6 @@ public final class ConnectionPool { if (foundConnection != null && foundConnection.isSpdy()) { connections.addFirst(foundConnection); // Add it back after iteration. - scheduleCleanupAsRequired(); } return foundConnection; @@ -224,10 +195,19 @@ public final class ConnectionPool { } synchronized (this) { - connections.addFirst(connection); + addConnection(connection); connection.incrementRecycleCount(); connection.resetIdleStartTime(); - scheduleCleanupAsRequired(); + } + } + + private void addConnection(Connection connection) { + boolean empty = connections.isEmpty(); + connections.addFirst(connection); + if (empty) { + executor.execute(connectionsCleanupRunnable); + } else { + notifyAll(); } } @@ -237,71 +217,104 @@ public final class ConnectionPool { */ void share(Connection connection) { if (!connection.isSpdy()) throw new IllegalArgumentException(); - if (connection.isAlive()) { - synchronized (this) { - connections.addFirst(connection); - scheduleCleanupAsRequired(); - } + if (!connection.isAlive()) return; + synchronized (this) { + addConnection(connection); } } /** Close and remove all connections in the pool. */ public void evictAll() { - List<Connection> connections; + List<Connection> toEvict; synchronized (this) { - connections = new ArrayList<>(this.connections); - this.connections.clear(); + toEvict = new ArrayList<>(connections); + connections.clear(); } - for (int i = 0, size = connections.size(); i < size; i++) { - Util.closeQuietly(connections.get(i).getSocket()); + for (int i = 0, size = toEvict.size(); i < size; i++) { + Util.closeQuietly(toEvict.get(i).getSocket()); } } - // Callers must synchronize on "this". - private void scheduleCleanupAsRequired() { - if (!draining) { - // A new connection has potentially been offered up to an empty / drained pool. - // Start the clean-up immediately. - draining = true; - executor.execute(connectionsCleanupRunnable); + private void runCleanupUntilPoolIsEmpty() { + while (true) { + if (!performCleanup()) return; // Halt cleanup. } } - /** Performs a single round of pool cleanup. */ + /** + * Attempts to make forward progress on connection eviction. There are three possible outcomes: + * + * <h3>The pool is empty.</h3> + * In this case, this method returns false and the eviction job should exit because there are no + * further cleanup tasks coming. (If additional connections are added to the pool, another cleanup + * job must be enqueued.) + * + * <h3>Connections were evicted.</h3> + * At least one connections was eligible for immediate eviction and was evicted. The method + * returns true and cleanup should continue. + * + * <h3>We waited to evict.</h3> + * None of the pooled connections were eligible for immediate eviction. Instead, we waited until + * either a connection became eligible for eviction, or the connections list changed. In either + * case, the method returns true and cleanup should continue. + */ // VisibleForTesting - void performCleanup() { - List<Connection> expiredConnections = new ArrayList<>(MAX_CONNECTIONS_TO_CLEANUP); - int idleConnectionCount = 0; + boolean performCleanup() { + List<Connection> evictableConnections; + synchronized (this) { + if (connections.isEmpty()) return false; // Halt cleanup. + + evictableConnections = new ArrayList<>(); + int idleConnectionCount = 0; + long now = System.nanoTime(); + long nanosUntilNextEviction = keepAliveDurationNs; + + // Collect connections eligible for immediate eviction. for (ListIterator<Connection> i = connections.listIterator(connections.size()); i.hasPrevious(); ) { Connection connection = i.previous(); - if (!connection.isAlive() || connection.isExpired(keepAliveDurationNs)) { + long nanosUntilEviction = connection.getIdleStartTimeNs() + keepAliveDurationNs - now; + if (nanosUntilEviction <= 0 || !connection.isAlive()) { i.remove(); - expiredConnections.add(connection); - if (expiredConnections.size() == MAX_CONNECTIONS_TO_CLEANUP) { - break; - } + evictableConnections.add(connection); } else if (connection.isIdle()) { idleConnectionCount++; + nanosUntilNextEviction = Math.min(nanosUntilNextEviction, nanosUntilEviction); } } + // If the pool has too many idle connections, gather more! Oldest to newest. for (ListIterator<Connection> i = connections.listIterator(connections.size()); i.hasPrevious() && idleConnectionCount > maxIdleConnections; ) { Connection connection = i.previous(); if (connection.isIdle()) { - expiredConnections.add(connection); + evictableConnections.add(connection); i.remove(); --idleConnectionCount; } } + + // If there's nothing to evict, wait. (This will be interrupted if connections are added.) + if (evictableConnections.isEmpty()) { + try { + long millisUntilNextEviction = nanosUntilNextEviction / (1000 * 1000); + long remainderNanos = nanosUntilNextEviction - millisUntilNextEviction * (1000 * 1000); + this.wait(millisUntilNextEviction, (int) remainderNanos); + return true; // Cleanup continues. + } catch (InterruptedException ignored) { + } + } } - for (Connection expiredConnection : expiredConnections) { + // Actually do the eviction. Note that we avoid synchronized() when closing sockets. + for (int i = 0, size = evictableConnections.size(); i < size; i++) { + Connection expiredConnection = evictableConnections.get(i); Util.closeQuietly(expiredConnection.getSocket()); } + + return true; // Cleanup continues. } /**
['okhttp-tests/src/test/java/com/squareup/okhttp/ConnectionPoolTest.java', 'okhttp/src/main/java/com/squareup/okhttp/Connection.java', 'okhttp/src/main/java/com/squareup/okhttp/ConnectionPool.java']
{'.java': 3}
3
3
0
0
3
869,670
201,598
24,507
132
6,200
1,313
141
2
662
106
142
6
0
0
1970-01-01T00:23:39
44,252
Kotlin
{'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995}
Apache License 2.0
163
square/okhttp/980/979
square
okhttp
https://github.com/square/okhttp/issues/979
https://github.com/square/okhttp/pull/980
https://github.com/square/okhttp/pull/980
1
fixes
SpdyTransport sets the wrong protocol
SpdyTransport sets the response protocol according to the status line. https://github.com/square/okhttp/blob/master/okhttp/src/main/java/com/squareup/okhttp/internal/http/StatusLine.java#L41 It seems to me that it should be clarified with the transport protocol, here, right? https://github.com/square/okhttp/blob/master/okhttp/src/main/java/com/squareup/okhttp/internal/http/SpdyTransport.java#L206
0766369844b26f64fc2e8d551ee8b5b00aa3fd87
9a35caf73356aa9a0142f5c5a0c50fde60d6ae02
https://github.com/square/okhttp/compare/0766369844b26f64fc2e8d551ee8b5b00aa3fd87...9a35caf73356aa9a0142f5c5a0c50fde60d6ae02
diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HeadersTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HeadersTest.java index 9947da037..144ec78f4 100644 --- a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HeadersTest.java +++ b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HeadersTest.java @@ -41,7 +41,7 @@ public final class HeadersTest { SpdyTransport.readNameValueBlock(headerBlock, Protocol.SPDY_3).request(request).build(); Headers headers = response.headers(); assertEquals(4, headers.size()); - assertEquals(Protocol.HTTP_1_1, response.protocol()); + assertEquals(Protocol.SPDY_3, response.protocol()); assertEquals(200, response.code()); assertEquals("OK", response.message()); assertEquals("no-cache, no-store", headers.get("cache-control")); diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/http/SpdyTransport.java b/okhttp/src/main/java/com/squareup/okhttp/internal/http/SpdyTransport.java index 38ad43817..14f317ba9 100644 --- a/okhttp/src/main/java/com/squareup/okhttp/internal/http/SpdyTransport.java +++ b/okhttp/src/main/java/com/squareup/okhttp/internal/http/SpdyTransport.java @@ -204,7 +204,7 @@ public final class SpdyTransport implements Transport { StatusLine statusLine = StatusLine.parse(version + " " + status); return new Response.Builder() - .protocol(statusLine.protocol) + .protocol(protocol) .code(statusLine.code) .message(statusLine.message) .headers(headersBuilder.build());
['okhttp/src/main/java/com/squareup/okhttp/internal/http/SpdyTransport.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HeadersTest.java']
{'.java': 2}
2
2
0
0
2
724,212
163,340
21,260
113
68
12
2
1
403
27
100
8
2
0
1970-01-01T00:23:24
44,252
Kotlin
{'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995}
Apache License 2.0
685
dbeaver/dbeaver/12953/12943
dbeaver
dbeaver
https://github.com/dbeaver/dbeaver/issues/12943
https://github.com/dbeaver/dbeaver/pull/12953
https://github.com/dbeaver/dbeaver/pull/12953
1
fix
Database Navigator "Show Connected Only", "Show All" toggle no longer works
#### System information: - Operating system (distribution) and version Windows 10 Enterprise version 1909 - DBeaver version Community 21.1.1.202106210824 - Java version - Additional extensions #### Connection specification: - Database name and version postgres 13.* - Driver name - Do you use tunnels or proxies (SSH, SOCKS, etc)? #### Describe the problem you're observing: [Database Navigator], top right side, button to toggle between showing all connections and showing connected only stopped working with yesterday's upgrade to Community 21.1.1.202106210824 #### Steps to reproduce, if exist: #### Include any warning/errors/backtraces from the logs <none> Functionality has not worked today and there are no errors in the logs from today.
7176cb483b61f6c3db2668dbb13df49876a4c1f0
cb54f75baa3c1c7c1b1ba18d41e97ca82313fe53
https://github.com/dbeaver/dbeaver/compare/7176cb483b61f6c3db2668dbb13df49876a4c1f0...cb54f75baa3c1c7c1b1ba18d41e97ca82313fe53
diff --git a/plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/navigator/database/DatabaseNavigatorTree.java b/plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/navigator/database/DatabaseNavigatorTree.java index 749c8113a7..a6c2863f9a 100644 --- a/plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/navigator/database/DatabaseNavigatorTree.java +++ b/plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/navigator/database/DatabaseNavigatorTree.java @@ -714,6 +714,8 @@ public class DatabaseNavigatorTree extends Composite implements INavigatorListen } pattern = "*" + pattern; this.matcher = new TextMatcherExt(pattern, true, false); + } else { + super.setPattern(null); } } @@ -725,13 +727,10 @@ public class DatabaseNavigatorTree extends Composite implements INavigatorListen if (matcher != null) { return matcher.match(text); } - return false; + return super.wordMatches(text); } public boolean isElementVisible(Viewer viewer, Object element){ - if (matcher == null) { - return true; - } if (filterShowConnected && element instanceof DBNDataSource && !((DBNDataSource) element).getDataSourceContainer().isConnected()) { return false; } diff --git a/plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/navigator/database/TextMatcherExt.java b/plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/navigator/database/TextMatcherExt.java index 7a5d7d0710..6b4a5dffe0 100644 --- a/plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/navigator/database/TextMatcherExt.java +++ b/plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/navigator/database/TextMatcherExt.java @@ -68,6 +68,7 @@ public class TextMatcherExt { if (s == null || s.isEmpty()) { continue; } + s = "*" + s; StringMatcher m = new StringMatcher(s, ignoreCase, ignoreWildCards); m.usePrefixMatch(); matchers.add(m);
['plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/navigator/database/TextMatcherExt.java', 'plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/navigator/database/DatabaseNavigatorTree.java']
{'.java': 2}
2
2
0
0
2
21,355,988
4,380,492
582,549
4,173
240
42
8
2
770
107
173
17
0
0
1970-01-01T00:27:04
33,177
Java
{'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202}
Apache License 2.0
686
dbeaver/dbeaver/12939/12070
dbeaver
dbeaver
https://github.com/dbeaver/dbeaver/issues/12070
https://github.com/dbeaver/dbeaver/pull/12939
https://github.com/dbeaver/dbeaver/pull/12939
1
fix
[mysql] incorrect handling of stored procedure and function with the same name
- Operating system (distribution) and version: Debian 10 - DBeaver version: 21.0.2 - Database name and version: mysql 8.0.23 - Driver name: MySQL If there are one stored procedure and one function with the same name, you could loose function while editing the procedure. 1) create "test" PROCEDURE ``` DELIMITER $$ $$ CREATE PROCEDURE testdb.test() BEGIN END$$ DELIMITER ; ``` 2) create "test" FUNCTION ``` DELIMITER $$ $$ CREATE FUNCTION testdb.test() RETURNS INT DETERMINISTIC BEGIN RETURN 0; END$$ DELIMITER ; ``` 3) open the procedure, edit and save. CTRL+S generates the correct code: ``` DROP PROCEDURE IF EXISTS testdb.test; DELIMITER $$ $$ CREATE DEFINER=`root`@`localhost` PROCEDURE `testdb`.`test`() BEGIN # test END$$ DELIMITER ; ``` 4) edit the procedure again and press CTRL+S.... boom: DROP **FUNCTION** IF EXISTS testdb.test; DELIMITER $$ $$ CREATE DEFINER=`root`@`localhost` PROCEDURE `testdb`.`test`() BEGIN # test 1 END$$ DELIMITER ; As you can see the second time you save, there is a DROP FUNCTION and CREATE PROCEDURE, so "test" function is deleted.
9825b1f323d73718b7e685dea501fdbd7387410d
9c46c6f8bd6d6b5a5db4aea769a63663699c912f
https://github.com/dbeaver/dbeaver/compare/9825b1f323d73718b7e685dea501fdbd7387410d...9c46c6f8bd6d6b5a5db4aea769a63663699c912f
diff --git a/plugins/org.jkiss.dbeaver.ext.mysql/src/org/jkiss/dbeaver/ext/mysql/model/MySQLCatalog.java b/plugins/org.jkiss.dbeaver.ext.mysql/src/org/jkiss/dbeaver/ext/mysql/model/MySQLCatalog.java index 3b2caa3e88..c6ad2fa070 100644 --- a/plugins/org.jkiss.dbeaver.ext.mysql/src/org/jkiss/dbeaver/ext/mysql/model/MySQLCatalog.java +++ b/plugins/org.jkiss.dbeaver.ext.mysql/src/org/jkiss/dbeaver/ext/mysql/model/MySQLCatalog.java @@ -923,12 +923,15 @@ public class MySQLCatalog implements "SELECT * FROM " + MySQLConstants.META_TABLE_ROUTINES + "\\nWHERE " + MySQLConstants.COL_ROUTINE_SCHEMA + "=?" + (object == null && objectName == null ? "" : " AND " + MySQLConstants.COL_ROUTINE_NAME + "=?") + - "\\nAND ROUTINE_TYPE IN ('PROCEDURE','FUNCTION')" + + " AND ROUTINE_TYPE" + (object == null ? " IN ('PROCEDURE','FUNCTION')" : "=?") + "\\nORDER BY " + MySQLConstants.COL_ROUTINE_NAME ); dbStat.setString(1, owner.getName()); if (object != null || objectName != null) { dbStat.setString(2, object != null ? object.getName() : objectName); + if (object != null) { + dbStat.setString(3, String.valueOf(object.getProcedureType())); + } } return dbStat; } diff --git a/plugins/org.jkiss.dbeaver.ext.mysql/src/org/jkiss/dbeaver/ext/mysql/model/MySQLProcedure.java b/plugins/org.jkiss.dbeaver.ext.mysql/src/org/jkiss/dbeaver/ext/mysql/model/MySQLProcedure.java index bf1cf13f76..4b98d7f7e3 100644 --- a/plugins/org.jkiss.dbeaver.ext.mysql/src/org/jkiss/dbeaver/ext/mysql/model/MySQLProcedure.java +++ b/plugins/org.jkiss.dbeaver.ext.mysql/src/org/jkiss/dbeaver/ext/mysql/model/MySQLProcedure.java @@ -20,10 +20,7 @@ import org.jkiss.code.NotNull; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.ext.mysql.MySQLConstants; -import org.jkiss.dbeaver.model.DBPDataKind; -import org.jkiss.dbeaver.model.DBPEvaluationContext; -import org.jkiss.dbeaver.model.DBPRefreshableObject; -import org.jkiss.dbeaver.model.DBUtils; +import org.jkiss.dbeaver.model.*; import org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement; import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet; import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession; @@ -44,7 +41,7 @@ import java.util.Map; /** * MySQLProcedure */ -public class MySQLProcedure extends AbstractProcedure<MySQLDataSource, MySQLCatalog> implements MySQLSourceObject, DBPRefreshableObject +public class MySQLProcedure extends AbstractProcedure<MySQLDataSource, MySQLCatalog> implements MySQLSourceObject, DBPRefreshableObject, DBPUniqueObject { private static final Log log = Log.getLog(MySQLProcedure.class); @@ -263,6 +260,15 @@ public class MySQLProcedure extends AbstractProcedure<MySQLDataSource, MySQLCata return getContainer().proceduresCache.refreshObject(monitor, getContainer(), this); } + @NotNull + @Override + public String getUniqueName() { + if (getProcedureType() == DBSProcedureType.PROCEDURE) { + return getName() + ' ' + getResultType(); + } + return getName(); + } + @Override public String toString() { return procedureType.name() + " " + getName();
['plugins/org.jkiss.dbeaver.ext.mysql/src/org/jkiss/dbeaver/ext/mysql/model/MySQLCatalog.java', 'plugins/org.jkiss.dbeaver.ext.mysql/src/org/jkiss/dbeaver/ext/mysql/model/MySQLProcedure.java']
{'.java': 2}
2
2
0
0
2
21,350,073
4,379,299
582,409
4,172
1,068
234
21
2
1,144
163
306
59
0
3
1970-01-01T00:27:04
33,177
Java
{'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202}
Apache License 2.0
688
dbeaver/dbeaver/12766/12765
dbeaver
dbeaver
https://github.com/dbeaver/dbeaver/issues/12765
https://github.com/dbeaver/dbeaver/pull/12766
https://github.com/dbeaver/dbeaver/pull/12766
1
fix
SqlServer FK between two schemas doesn't show on UI
<!-- Thank you for reporting an issue. *IMPORTANT* - *before* creating a new issue please look around: - DBeaver documentation: https://github.com/dbeaver/dbeaver/wiki and - open issues in Github tracker: https://github.com/dbeaver/dbeaver/issues If you cannot find a similar problem, then create a new issue. Short tips about new issues can be found here: https://github.com/dbeaver/dbeaver/wiki/Posting-issues Please, do not create issue duplicates. If you find the same or similar issue, just add a comment or vote for this feature. It helps us to track the most popular requests and fix them faster. Please fill in as much of the template as possible. --> #### System information: - Operating system: **Windows 10 Version 21H1 Build 19043.1023** - DBeaver version **21.1.0.202105300349** Community - Additional extensions DBeaver Git support 1.0.46.202106012023 org.jkiss.dbeaver.git.feature.feature.group DBeaver Corp DevStyle (includes Darkest Dark Theme) 1.11.0.202105260439 com.genuitec.eclipse.theming.core.feature.feature.group Genuitec, LLC #### Connection specification: - Database name and version: **SqlServer Express Microsoft SQL Server 2017 (RTM-GDR) (KB4583456) - 14.0.2037.2 (X64) Nov 2 2020 19:19:59 Copyright (C) 2017 Microsoft Corporation Express Edition (64-bit) on Windows 10 Pro 10.0 <X64> (Build 19043: ) (Hypervisor)** - Driver name **SQL Server** - Do you use tunnels or proxies (SSH, SOCKS, etc)? **No** #### Describe the problem you're observing: Creating foreign keys between two tables on two different schemas via UI or SQL Script does not show it on Foreign Keys Tab/SubGroup neither on the DDL source tab. #### Steps to reproduce, if exist: 1. Create a SQL Server database 2. Create two schemas 3. Create TableOne on schema1 4. Create TableTwo on schema2 5. Create FK from TableTwo to TableOne 6. If you create FK with UI from the Foreign Keys tab when click persist the FK disappear (but is still present on DB) 7. Execute the query `select * from sys.objects` to verify that the object is successfully created
63aee4269a199deb69359f4913055615619a7666
0e820df3b91ff92f3c37db90335d30703afde0fd
https://github.com/dbeaver/dbeaver/compare/63aee4269a199deb69359f4913055615619a7666...0e820df3b91ff92f3c37db90335d30703afde0fd
diff --git a/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerSchema.java b/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerSchema.java index dac1924bb9..e41e19e4ef 100644 --- a/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerSchema.java +++ b/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerSchema.java @@ -216,10 +216,22 @@ public class SQLServerSchema implements DBSSchema, DBPSaveableObject, DBPQualifi return tableCache.getTypedObjects(monitor, this, SQLServerTable.class); } + @Nullable public SQLServerTableBase getTable(DBRProgressMonitor monitor, String name) throws DBException { return tableCache.getObject(monitor, this, name); } + @Nullable + public SQLServerTable getTable(DBRProgressMonitor monitor, long tableId) throws DBException { + for (SQLServerTableBase table : tableCache.getAllObjects(monitor, this)) { + if (table.getObjectId() == tableId && table instanceof SQLServerTable) { + return (SQLServerTable) table; + } + } + log.debug("Table '" + tableId + "' not found in schema " + getName()); + return null; + } + @Association public Collection<SQLServerView> getViews(DBRProgressMonitor monitor) throws DBException { return tableCache.getTypedObjects(monitor, this, SQLServerView.class); @@ -659,7 +671,7 @@ public class SQLServerSchema implements DBSSchema, DBPSaveableObject, DBPQualifi return null; } long refTableId = JDBCUtils.safeGetLong(dbResult, "referenced_object_id"); - SQLServerTable refTable = getTable(monitor, refTableId); + SQLServerTable refTable = refSchema.getTable(monitor, refTableId); if (refTable == null) { log.debug("Ref table " + refTableId + " not found in schema " + refSchema.getName()); return null; @@ -684,17 +696,6 @@ public class SQLServerSchema implements DBSSchema, DBPSaveableObject, DBPQualifi return new SQLServerTableForeignKey(parent, fkName, null, refConstraint, deleteRule, updateRule, true); } - @Nullable - private SQLServerTable getTable(DBRProgressMonitor monitor, long tableId) throws DBException { - for (SQLServerTableBase table: tableCache.getAllObjects(monitor, SQLServerSchema.this)) { - if (table.getObjectId() == tableId && table instanceof SQLServerTable) { - return (SQLServerTable) table; - } - } - log.debug("Table '" + tableId + "' not found in schema " + getName()); - return null; - } - @Nullable @Override protected SQLServerTableForeignKeyColumn[] fetchObjectRow(
['plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerSchema.java']
{'.java': 1}
1
1
0
0
1
21,252,088
4,358,670
579,957
4,152
1,158
240
25
1
2,113
299
550
39
3
0
1970-01-01T00:27:03
33,177
Java
{'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202}
Apache License 2.0
689
dbeaver/dbeaver/12577/12576
dbeaver
dbeaver
https://github.com/dbeaver/dbeaver/issues/12576
https://github.com/dbeaver/dbeaver/pull/12577
https://github.com/dbeaver/dbeaver/pull/12577
1
fix
Inconsistent behavior of some checkboxes on the PostgreSQL connection configuration page
On the aforementioned page, we have 3 checkboxes: a) Show all databases; b) Show template databases; c) Show databases not available for connection. If the first one is not set, the latter two are not applicable. However, if we check one of them, e.g. the second one, and then we uncheck the first one, checkbox b is still set (but grayed). We also have the same checkboxes in the global preferences, and there we can even apply checkboxes b and c without checking button a.
a4afc250c8dc2566f43c7352e4aba539db7b8e23
4ae933837845b1c564859b676464fe7c83b18f9a
https://github.com/dbeaver/dbeaver/compare/a4afc250c8dc2566f43c7352e4aba539db7b8e23...4ae933837845b1c564859b676464fe7c83b18f9a
diff --git a/plugins/org.jkiss.dbeaver.ext.postgresql.ui/src/org/jkiss/dbeaver/ext/postgresql/ui/PostgreConnectionPageAdvanced.java b/plugins/org.jkiss.dbeaver.ext.postgresql.ui/src/org/jkiss/dbeaver/ext/postgresql/ui/PostgreConnectionPageAdvanced.java index 3d86556b1b..4529685533 100644 --- a/plugins/org.jkiss.dbeaver.ext.postgresql.ui/src/org/jkiss/dbeaver/ext/postgresql/ui/PostgreConnectionPageAdvanced.java +++ b/plugins/org.jkiss.dbeaver.ext.postgresql.ui/src/org/jkiss/dbeaver/ext/postgresql/ui/PostgreConnectionPageAdvanced.java @@ -84,8 +84,7 @@ public class PostgreConnectionPageAdvanced extends ConnectionPageAbstract showNonDefault.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - showTemplates.setEnabled(showNonDefault.getSelection()); - showUnavailable.setEnabled(showNonDefault.getSelection()); + setCheckboxesState(); } }); showTemplates = UIUtils.createCheckbox(secureGroup, PostgreMessages.dialog_setting_connection_show_templates, PostgreMessages.dialog_setting_connection_show_templates_tip, false, 2); @@ -125,6 +124,16 @@ public class PostgreConnectionPageAdvanced extends ConnectionPageAbstract loadSettings(); } + private void setCheckboxesState() { + boolean enable = showNonDefault.getSelection(); + if (!enable) { + showUnavailable.setSelection(false); + showTemplates.setSelection(false); + } + showUnavailable.setEnabled(enable); + showTemplates.setEnabled(enable); + } + @Override public boolean isComplete() { @@ -145,11 +154,10 @@ public class PostgreConnectionPageAdvanced extends ConnectionPageAbstract showTemplates.setSelection( CommonUtils.getBoolean(connectionInfo.getProviderProperty(PostgreConstants.PROP_SHOW_TEMPLATES_DB), globalPrefs.getBoolean(PostgreConstants.PROP_SHOW_TEMPLATES_DB))); - showTemplates.setEnabled(showNonDefault.getSelection()); showUnavailable.setSelection( CommonUtils.getBoolean(connectionInfo.getProviderProperty(PostgreConstants.PROP_SHOW_UNAVAILABLE_DB), globalPrefs.getBoolean(PostgreConstants.PROP_SHOW_UNAVAILABLE_DB))); - showUnavailable.setEnabled(showNonDefault.getSelection()); + setCheckboxesState(); showDatabaseStatistics.setSelection( CommonUtils.getBoolean(connectionInfo.getProviderProperty(PostgreConstants.PROP_SHOW_DATABASE_STATISTICS), globalPrefs.getBoolean(PostgreConstants.PROP_SHOW_DATABASE_STATISTICS))); diff --git a/plugins/org.jkiss.dbeaver.ext.postgresql.ui/src/org/jkiss/dbeaver/ext/postgresql/ui/PrefPagePostgreSQL.java b/plugins/org.jkiss.dbeaver.ext.postgresql.ui/src/org/jkiss/dbeaver/ext/postgresql/ui/PrefPagePostgreSQL.java index 9eb6ff68de..cfb96b1b4c 100644 --- a/plugins/org.jkiss.dbeaver.ext.postgresql.ui/src/org/jkiss/dbeaver/ext/postgresql/ui/PrefPagePostgreSQL.java +++ b/plugins/org.jkiss.dbeaver.ext.postgresql.ui/src/org/jkiss/dbeaver/ext/postgresql/ui/PrefPagePostgreSQL.java @@ -79,8 +79,7 @@ public class PrefPagePostgreSQL extends AbstractPrefPage implements IWorkbenchPr showNonDefault.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - showTemplates.setEnabled(showNonDefault.getSelection()); - showUnavailable.setEnabled(showNonDefault.getSelection()); + setCheckboxesState(); } }); showTemplates = UIUtils.createCheckbox(secureGroup, @@ -95,6 +94,7 @@ public class PrefPagePostgreSQL extends AbstractPrefPage implements IWorkbenchPr globalPrefs.getBoolean(PostgreConstants.PROP_SHOW_UNAVAILABLE_DB), 2 ); + setCheckboxesState(); showDatabaseStatistics = UIUtils.createCheckbox( secureGroup, PostgreMessages.dialog_setting_connection_database_statistics, @@ -129,6 +129,16 @@ public class PrefPagePostgreSQL extends AbstractPrefPage implements IWorkbenchPr return cfgGroup; } + private void setCheckboxesState() { + boolean enable = showNonDefault.getSelection(); + if (!enable) { + showUnavailable.setSelection(false); + showTemplates.setSelection(false); + } + showUnavailable.setEnabled(enable); + showTemplates.setEnabled(enable); + } + @Override public boolean performOk() { DBPPreferenceStore preferenceStore = DBWorkbench.getPlatform().getPreferenceStore();
['plugins/org.jkiss.dbeaver.ext.postgresql.ui/src/org/jkiss/dbeaver/ext/postgresql/ui/PostgreConnectionPageAdvanced.java', 'plugins/org.jkiss.dbeaver.ext.postgresql.ui/src/org/jkiss/dbeaver/ext/postgresql/ui/PrefPagePostgreSQL.java']
{'.java': 2}
2
2
0
0
2
21,216,761
4,351,606
579,212
4,150
1,256
182
30
2
474
85
108
1
0
0
1970-01-01T00:27:01
33,177
Java
{'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202}
Apache License 2.0
690
dbeaver/dbeaver/12571/12569
dbeaver
dbeaver
https://github.com/dbeaver/dbeaver/issues/12569
https://github.com/dbeaver/dbeaver/pull/12571
https://github.com/dbeaver/dbeaver/pull/12571
1
fix
Probable regression, Postgresql sequence DDL uses Cache 0 and this is not a valid value
#### System information: - Ubuntu 18.04 - DBeaver CE 21.0.5 - Additional extensions: Non AFAIK #### Connection specification: - Database name and version: PostgreSQL 9.6 - Driver name: PostgreSQL JDBC Driver - Do you use tunnels or proxies (SSH, SOCKS, etc)? No #### Describe the problem you're observing: The DDL suggested for a sequence sets optional attribute CACHE to 0 which is not valid in PostgreSQL. This was reported and supposedly fixed a couple of years ago in #5156 . #### Steps to reproduce, if exist: Create a sequence in a PostgreSQL DB and check the DDL that DBeaver shows. #### Include any warning/errors/backtraces from the logs <!-- Please, find the short guide how to find logs here: https://github.com/dbeaver/dbeaver/wiki/Log-files -->
67d9e76022d6a32ac090e12f2e25d82ec1726fe3
c170fae1c16ce0ef9287d3419de48541385eb1f1
https://github.com/dbeaver/dbeaver/compare/67d9e76022d6a32ac090e12f2e25d82ec1726fe3...c170fae1c16ce0ef9287d3419de48541385eb1f1
diff --git a/plugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/model/PostgreSequence.java b/plugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/model/PostgreSequence.java index dd58352562..57c44bda18 100644 --- a/plugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/model/PostgreSequence.java +++ b/plugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/model/PostgreSequence.java @@ -253,13 +253,29 @@ public class PostgreSequence extends PostgreTableBase implements DBSSequence, DB AdditionalInfo info = getAdditionalInfo(monitor); StringBuilder sql = new StringBuilder() .append("-- DROP SEQUENCE ").append(getFullyQualifiedName(DBPEvaluationContext.DDL)).append(";\\n\\n") - .append("CREATE SEQUENCE ").append(getFullyQualifiedName(DBPEvaluationContext.DDL)) - .append("\\n\\tINCREMENT BY ").append(info.getIncrementBy()) - .append("\\n\\tMINVALUE ").append(info.getMinValue()) - .append("\\n\\tMAXVALUE ").append(info.getMaxValue()) - .append("\\n\\tSTART ").append(info.getStartValue()) - .append("\\n\\tCACHE ").append(info.getCacheValue()) - .append("\\n\\t").append(info.isCycled ? "" : "NO ").append("CYCLE;"); + .append("CREATE SEQUENCE ").append(getFullyQualifiedName(DBPEvaluationContext.DDL)); + + if (info.getIncrementBy() > 0) { + sql.append("\\n\\tINCREMENT BY ").append(info.getIncrementBy()); + } + if (info.getMinValue() > 0) { + sql.append("\\n\\tMINVALUE ").append(info.getMinValue()); + } else { + sql.append("\\n\\tNO MINVALUE"); + } + if (info.getMaxValue() > 0) { + sql.append("\\n\\tMAXVALUE ").append(info.getMaxValue()); + } else { + sql.append("\\n\\tNO MAXVALUE"); + } + if (info.getStartValue() > 0) { + sql.append("\\n\\tSTART ").append(info.getStartValue()); + } + if (info.getCacheValue() > 0) { + sql.append("\\n\\tCACHE ").append(info.getCacheValue()); + sql.append("\\n\\t").append(info.isCycled ? "" : "NO ").append("CYCLE"); + } + sql.append(';'); if (!CommonUtils.isEmpty(getDescription())) { sql.append("\\nCOMMENT ON SEQUENCE ").append(DBUtils.getQuotedIdentifier(this)).append(" IS ")
['plugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/model/PostgreSequence.java']
{'.java': 1}
1
1
0
0
1
21,193,424
4,346,619
578,586
4,146
1,449
331
30
1
782
120
186
20
1
0
1970-01-01T00:27:01
33,177
Java
{'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202}
Apache License 2.0
684
dbeaver/dbeaver/13321/11973
dbeaver
dbeaver
https://github.com/dbeaver/dbeaver/issues/11973
https://github.com/dbeaver/dbeaver/pull/13321
https://github.com/dbeaver/dbeaver/pull/13321
1
fix
Filters don't work for enum types
PostgreSQL 12, DBeaver EE 21.0.0, macOS 11.2.3. Suppose we have a enum type and a table: ```sql CREATE TYPE "mood" AS ENUM ( 'sad', 'ok', 'happy' ); CREATE TABLE mood_data ( id int4 NOT NULL GENERATED ALWAYS AS IDENTITY, "time" timestamp NULL, "mood" "mood" NULL, CONSTRAINT mood_data_pkey PRIMARY KEY (id) ); ``` Fill the table with data. Open the data editor and try to apply a filter on the `mood` column. Possible values for filtering will be duplicated, the data editor will be closed with an error when applying the filter.
86adfaeec2af0cf11b43114cfb25f316830489fd
01ddb8e9c02c212e4179295aa37381a9944d6621
https://github.com/dbeaver/dbeaver/compare/86adfaeec2af0cf11b43114cfb25f316830489fd...01ddb8e9c02c212e4179295aa37381a9944d6621
diff --git a/plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/valuefilter/GenericFilterValueEdit.java b/plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/valuefilter/GenericFilterValueEdit.java index 9fede8aa6a..3558b73b3c 100644 --- a/plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/valuefilter/GenericFilterValueEdit.java +++ b/plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/valuefilter/GenericFilterValueEdit.java @@ -496,6 +496,12 @@ class GenericFilterValueEdit { } private DBDLabelValuePair findValue(Map<Object, DBDLabelValuePair> rowData, Object cellValue) { + final DBDLabelValuePair value = rowData.get(cellValue); + if (value != null) { + // If we managed to found something at this point - return right away + return value; + } + // Otherwise try to match values manually if (cellValue instanceof Number) { for (Map.Entry<Object, DBDLabelValuePair> pair : rowData.entrySet()) { if (pair.getKey() instanceof Number && CommonUtils.compareNumbers((Number) pair.getKey(), (Number) cellValue) == 0) { @@ -503,7 +509,14 @@ class GenericFilterValueEdit { } } } - return rowData.get(cellValue); + if (cellValue instanceof String) { + for (Map.Entry<Object, DBDLabelValuePair> pair : rowData.entrySet()) { + if (!DBUtils.isNullValue(pair.getKey()) && CommonUtils.toString(pair.getKey()).equals(cellValue)) { + return pair.getValue(); + } + } + } + return null; } @Nullable
['plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/valuefilter/GenericFilterValueEdit.java']
{'.java': 1}
1
1
0
0
1
21,570,516
4,422,651
587,715
4,199
663
123
15
1
582
91
157
20
0
1
1970-01-01T00:27:07
33,177
Java
{'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202}
Apache License 2.0
683
dbeaver/dbeaver/14078/10955
dbeaver
dbeaver
https://github.com/dbeaver/dbeaver/issues/10955
https://github.com/dbeaver/dbeaver/pull/14078
https://github.com/dbeaver/dbeaver/pull/14078
1
fix
Auto-complete offers objects from the current schema only
#### System information: - Operating system (distribution) and version Win10 - DBeaver version 7.3.3 EA #### Steps to reproduce, if exist: 1. Open SQL Editor for MySQL sakila 2. Type `select * from a` **Actual result**: the list for auto-complete appears with objects from the current schema only **Expected**: the objects are offered from the whole database if they are suitable for auto-complete in the current statement. _Note_: enabled **Use global search** option doesn't solve the issue
19a37d839f97bb022c19ddc6fff588b230f92786
e5219c457984fa0ef078968c11b7c835a3526142
https://github.com/dbeaver/dbeaver/compare/19a37d839f97bb022c19ddc6fff588b230f92786...e5219c457984fa0ef078968c11b7c835a3526142
diff --git a/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerStructureAssistant.java b/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerStructureAssistant.java index 68edb2d22e..9be288abeb 100644 --- a/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerStructureAssistant.java +++ b/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerStructureAssistant.java @@ -128,7 +128,7 @@ public class SQLServerStructureAssistant implements DBSStructureAssistant<SQLSer Collection<SQLServerDatabase> databases; SQLServerSchema schema = null; - if (parentObject instanceof DBPDataSourceContainer) { + if (parentObject instanceof DBPDataSourceContainer || parentObject instanceof SQLServerDataSource) { if (globalSearch) { databases = executionContext.getDataSource().getDatabases(monitor); } else {
['plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerStructureAssistant.java']
{'.java': 1}
1
1
0
0
1
22,041,779
4,518,554
599,248
4,274
172
31
2
1
508
77
114
12
0
0
1970-01-01T00:27:13
33,177
Java
{'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202}
Apache License 2.0
682
dbeaver/dbeaver/14732/12335
dbeaver
dbeaver
https://github.com/dbeaver/dbeaver/issues/12335
https://github.com/dbeaver/dbeaver/pull/14732
https://github.com/dbeaver/dbeaver/pull/14732
1
fix
Autocompletion doesn't work in some JOIN cases.
#### System information: - Windows 10 Pro x64 - DBeaver 21.0.4 - No additional extensions #### Connection specification: - PostgreSQL 9.5 - Default PostgreSQL driver - No tunnels or proxies #### Describe the problem you're observing: Column autocompletion doesn't work when table in from clause doesn't have alias #### Steps to reproduce, if exist: https://user-images.githubusercontent.com/22142845/116897332-cdc2a480-ac3d-11eb-8f1b-5f8d6e5ebee0.mp4
aa2e00bbde05b2fb5e993b05298ad4e4d2fc2ca1
661dc850cef16f395a746f811fab55de36107ee8
https://github.com/dbeaver/dbeaver/compare/aa2e00bbde05b2fb5e993b05298ad4e4d2fc2ca1...661dc850cef16f395a746f811fab55de36107ee8
diff --git a/plugins/org.jkiss.dbeaver.model.sql/src/org/jkiss/dbeaver/model/sql/completion/SQLCompletionAnalyzer.java b/plugins/org.jkiss.dbeaver.model.sql/src/org/jkiss/dbeaver/model/sql/completion/SQLCompletionAnalyzer.java index 33ecaf1292..15bb14763d 100644 --- a/plugins/org.jkiss.dbeaver.model.sql/src/org/jkiss/dbeaver/model/sql/completion/SQLCompletionAnalyzer.java +++ b/plugins/org.jkiss.dbeaver.model.sql/src/org/jkiss/dbeaver/model/sql/completion/SQLCompletionAnalyzer.java @@ -932,8 +932,16 @@ public class SQLCompletionAnalyzer implements DBRRunnableParametrized<DBRProgres continue; } if (state == InlineState.TABLE_DOT) { - if (CommonUtils.isEmpty(tableAlias)) { + if (CommonUtils.isEmpty(tableAlias) && !isTableQueryToken(tok, value)) { state = InlineState.MATCHED; + } else if (isTableQueryToken(tok, value)) { + /* + Sometimes we can have table without alias, it will reset state to table_name because there is no alias to check + See #12335 + */ + matchedTableName = null; + state = InlineState.TABLE_NAME; + continue; } else { state = InlineState.ALIAS_AS; } diff --git a/test/org.jkiss.dbeaver.test.platform/src/org/jkiss/dbeaver/model/sql/analyzer/SQLCompletionAnalyzerTest.java b/test/org.jkiss.dbeaver.test.platform/src/org/jkiss/dbeaver/model/sql/analyzer/SQLCompletionAnalyzerTest.java index 7a03a6a672..26a363327b 100644 --- a/test/org.jkiss.dbeaver.test.platform/src/org/jkiss/dbeaver/model/sql/analyzer/SQLCompletionAnalyzerTest.java +++ b/test/org.jkiss.dbeaver.test.platform/src/org/jkiss/dbeaver/model/sql/analyzer/SQLCompletionAnalyzerTest.java @@ -147,6 +147,30 @@ public class SQLCompletionAnalyzerTest { } } + @Test + public void testColumnWithNonExistingAliases() throws DBException { + final RequestResult request = RequestBuilder.tables(s-> { + s.table("Table1", t -> { + t.attribute("Col1"); + t.attribute("Col2"); + }); + s.table("Table2", t -> { + t.attribute("Col4"); + t.attribute("Col5"); + }); + }).prepare(); + { + final List<SQLCompletionProposalBase> proposals = request.request("SELECT * FROM Table1 join Table2 t on t.|", false); + Assert.assertEquals("Col4", proposals.get(0).getReplacementString()); + Assert.assertEquals("Col5", proposals.get(1).getReplacementString()); + } + { + final List<SQLCompletionProposalBase> proposals = request.request("SELECT * FROM Table1 b join Table2 on b.|", false); + Assert.assertEquals("Col1", proposals.get(0).getReplacementString()); + Assert.assertEquals("Col2", proposals.get(1).getReplacementString()); + } + } + @Test public void testColumnNamesExpandCompletion() throws DBException { final RequestResult request = RequestBuilder
['plugins/org.jkiss.dbeaver.model.sql/src/org/jkiss/dbeaver/model/sql/completion/SQLCompletionAnalyzer.java', 'test/org.jkiss.dbeaver.test.platform/src/org/jkiss/dbeaver/model/sql/analyzer/SQLCompletionAnalyzerTest.java']
{'.java': 2}
2
2
0
0
2
22,438,727
4,600,353
608,724
4,320
598
96
10
1
474
55
128
18
1
0
1970-01-01T00:27:18
33,177
Java
{'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202}
Apache License 2.0
681
dbeaver/dbeaver/14902/14010
dbeaver
dbeaver
https://github.com/dbeaver/dbeaver/issues/14010
https://github.com/dbeaver/dbeaver/pull/14902
https://github.com/dbeaver/dbeaver/pull/14902
1
fix
Support JSONExtractKeysAndValuesRaw feature in Clickhouse
Hello! I use DBeaver 21.1.3.202107181810 with ClickHouse. And I have a problem with JSONExtractKeysAndValuesRaw feature: `SELECT JSONExtractKeysAndValuesRaw('{"id":67}')` Error: ``` org.jkiss.dbeaver.model.exec.DBCException: Can't extract array data from JDBC array at org.jkiss.dbeaver.model.impl.jdbc.data.JDBCCollection.makeCollectionFromArray(JDBCCollection.java:267) at org.jkiss.dbeaver.model.impl.jdbc.data.handlers.JDBCArrayValueHandler.getValueFromObject(JDBCArrayValueHandler.java:64) at org.jkiss.dbeaver.model.impl.jdbc.data.handlers.JDBCArrayValueHandler.getValueFromObject(JDBCArrayValueHandler.java:1) at org.jkiss.dbeaver.model.impl.jdbc.data.handlers.JDBCComplexValueHandler.fetchColumnValue(JDBCComplexValueHandler.java:50) at org.jkiss.dbeaver.model.impl.jdbc.data.handlers.JDBCAbstractValueHandler.fetchValueObject(JDBCAbstractValueHandler.java:49) at org.jkiss.dbeaver.ui.controls.resultset.ResultSetDataReceiver.fetchRow(ResultSetDataReceiver.java:125) at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.fetchQueryData(SQLQueryJob.java:721) at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.executeStatement(SQLQueryJob.java:544) at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.lambda$0(SQLQueryJob.java:444) at org.jkiss.dbeaver.model.exec.DBExecUtils.tryExecuteRecover(DBExecUtils.java:171) at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.executeSingleQuery(SQLQueryJob.java:431) at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.extractData(SQLQueryJob.java:816) at org.jkiss.dbeaver.ui.editors.sql.SQLEditor$QueryResultsContainer.readData(SQLEditor.java:3435) at org.jkiss.dbeaver.ui.controls.resultset.ResultSetJobDataRead.lambda$0(ResultSetJobDataRead.java:118) at org.jkiss.dbeaver.model.exec.DBExecUtils.tryExecuteRecover(DBExecUtils.java:171) at org.jkiss.dbeaver.ui.controls.resultset.ResultSetJobDataRead.run(ResultSetJobDataRead.java:116) at org.jkiss.dbeaver.ui.controls.resultset.ResultSetViewer$ResultSetDataPumpJob.run(ResultSetViewer.java:4686) at org.jkiss.dbeaver.model.runtime.AbstractJob.run(AbstractJob.java:105) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63) Caused by: org.jkiss.dbeaver.model.exec.DBCException: SQL Error at org.jkiss.dbeaver.model.impl.jdbc.data.JDBCCollection.makeCollectionFromArray(JDBCCollection.java:251) ... 18 more Caused by: java.sql.SQLFeatureNotSupportedException at ru.yandex.clickhouse.ClickHouseArray.getResultSet(ClickHouseArray.java:65) at org.jkiss.dbeaver.model.impl.jdbc.data.JDBCCollection.makeCollectionFromResultSet(JDBCCollection.java:367) at org.jkiss.dbeaver.model.impl.jdbc.data.JDBCCollection.makeCollectionFromArray(JDBCCollection.java:249) ... 18 more ``` Are there any plans to add support of this feature? It would be very useful. Thank you
a7980337756790411f2354e08b3286290669493c
0bb461d52d3c6228e8b3124f96689ea7c92183cf
https://github.com/dbeaver/dbeaver/compare/a7980337756790411f2354e08b3286290669493c...0bb461d52d3c6228e8b3124f96689ea7c92183cf
diff --git a/plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/impl/jdbc/data/JDBCCollection.java b/plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/impl/jdbc/data/JDBCCollection.java index d2104bf043..b947bbd148 100644 --- a/plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/impl/jdbc/data/JDBCCollection.java +++ b/plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/impl/jdbc/data/JDBCCollection.java @@ -237,30 +237,32 @@ public class JDBCCollection extends AbstractDatabaseList implements DBDValueClon } try { - if (elementType == null) { - if (array == null) { - // Null array of unknown type. Just make NULL read-only array - String defDataTypeName = dataSource.getDefaultDataTypeName(DBPDataKind.OBJECT); - DBSDataType defDataType = dataSource.getLocalDataType(defDataTypeName); - DBDValueHandler defValueHandler = session.getDefaultValueHandler(); - return new JDBCCollection(defDataType, defValueHandler, null); - } + if (elementType == null && array == null) { + // Null array of unknown type. Just make NULL read-only array + String defDataTypeName = dataSource.getDefaultDataTypeName(DBPDataKind.OBJECT); + DBSDataType defDataType = dataSource.getLocalDataType(defDataTypeName); + DBDValueHandler defValueHandler = session.getDefaultValueHandler(); + return new JDBCCollection(defDataType, defValueHandler, null); + } + + if (elementType != null) { try { - return makeCollectionFromResultSet(session, array, null); + return makeCollectionFromArray(session, array, elementType); } catch (SQLException e) { - throw new DBCException(e, session.getExecutionContext()); + if (array == null) { + throw new DBCException(e, session.getExecutionContext()); + } } } + try { - return makeCollectionFromArray(session, array, elementType); + return makeCollectionFromResultSet(session, array, null); } catch (SQLException e) { - if (array == null) { - throw new DBCException(e, session.getExecutionContext()); - } try { - return makeCollectionFromResultSet(session, array, elementType); - } catch (SQLException e1) { - throw new DBCException(e1, session.getExecutionContext()); + // Array of unknown type. + return makeCollectionFromJavaArray(session, array.getArray()); + } catch (SQLException ex) { + throw new DBCException(ex, session.getExecutionContext()); } } } catch (DBException e) { @@ -269,7 +271,7 @@ public class JDBCCollection extends AbstractDatabaseList implements DBDValueClon } @NotNull - public static JDBCCollection makeCollectionFromJavaArray(@NotNull JDBCSession session, @NotNull DBSTypedObject column, Object array) throws DBCException { + public static JDBCCollection makeCollectionFromJavaArray(@NotNull JDBCSession session, Object array) throws DBCException { DBSDataType elementType; DBPDataKind dataKind; DBPDataTypeProvider dataTypeProvider = session.getDataSource(); diff --git a/plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/impl/jdbc/data/handlers/JDBCArrayValueHandler.java b/plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/impl/jdbc/data/handlers/JDBCArrayValueHandler.java index 6d1b96a928..7f51dbb2a1 100644 --- a/plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/impl/jdbc/data/handlers/JDBCArrayValueHandler.java +++ b/plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/impl/jdbc/data/handlers/JDBCArrayValueHandler.java @@ -65,7 +65,7 @@ public class JDBCArrayValueHandler extends JDBCComplexValueHandler { } else if (object instanceof String) { return JDBCCollection.makeCollectionFromString((JDBCSession) session, (String)object); } else if (object.getClass().isArray()) { - return JDBCCollection.makeCollectionFromJavaArray((JDBCSession) session, type, object); + return JDBCCollection.makeCollectionFromJavaArray((JDBCSession) session, object); } else if (object instanceof Collection) { return JDBCCollection.makeCollectionFromJavaCollection((JDBCSession) session, type, (Collection) object); } else {
['plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/impl/jdbc/data/handlers/JDBCArrayValueHandler.java', 'plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/impl/jdbc/data/JDBCCollection.java']
{'.java': 2}
2
2
0
0
2
22,575,202
4,628,235
612,652
4,342
2,721
471
40
2
2,846
105
741
38
0
1
1970-01-01T00:27:19
33,177
Java
{'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202}
Apache License 2.0
680
dbeaver/dbeaver/14936/14187
dbeaver
dbeaver
https://github.com/dbeaver/dbeaver/issues/14187
https://github.com/dbeaver/dbeaver/pull/14936
https://github.com/dbeaver/dbeaver/pull/14936
1
fix
SQL script editor bug when delete
#### System information: - Win 10 - 21.2.2.202110030714 - Additional extensions - #### Connection specification: - Postgresql 13 - org.postgresql.Driver (42.2.20) #### Describe the problem you're observing: 1. E.g. "SELECT id, c1, c2, c3 FROM table;" from SQL script window. 2. select a row and mark it for delete. 3. browse over the row limit (e.g. 200) 4. press "save" 5. the row doesn't deleted
9b10a1e99e8f8c60a65cdcba8dff8db606afed63
ded93ff8197261905aeba24d75e6030bc601bf69
https://github.com/dbeaver/dbeaver/compare/9b10a1e99e8f8c60a65cdcba8dff8db606afed63...ded93ff8197261905aeba24d75e6030bc601bf69
diff --git a/plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/ResultSetViewer.java b/plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/ResultSetViewer.java index bf66efb8b4..115d734f38 100644 --- a/plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/ResultSetViewer.java +++ b/plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/ResultSetViewer.java @@ -221,7 +221,15 @@ public class ResultSetViewer extends Viewer // Theme listener private IPropertyChangeListener themeChangeListener; private long lastThemeUpdateTime; + private boolean isCancelled = false; + public boolean isCancelled() { + return isCancelled; + } + + public void setCancelled(boolean cancelled) { + isCancelled = cancelled; + } public ResultSetViewer(@NotNull Composite parent, @NotNull IWorkbenchPartSite site, @NotNull IResultSetContainer container) { @@ -2256,9 +2264,6 @@ public class ResultSetViewer extends Viewer } void appendData(List<Object[]> rows, boolean resetOldRows) { - if (!checkForChanges()) { - return; - } model.appendData(rows, resetOldRows); UIUtils.asyncExec(() -> { @@ -3540,6 +3545,9 @@ public class ResultSetViewer extends Viewer public boolean checkForChanges() { // Check if we are dirty if (isDirty()) { + if (isCancelled){ + return false; + } int checkResult = new UITask<Integer>() { @Override protected Integer runTask() { @@ -3548,6 +3556,7 @@ public class ResultSetViewer extends Viewer }.execute(); switch (checkResult) { case ISaveablePart2.CANCEL: + isCancelled = true; return false; case ISaveablePart2.YES: // Apply changes @@ -4809,6 +4818,10 @@ public class ResultSetViewer extends Viewer return Status.CANCEL_STATUS; } beforeDataRead(); + if (!checkForChanges()){ + return Status.CANCEL_STATUS; + } + isCancelled = false; try { IStatus status = super.run(monitor); afterDataRead();
['plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/ResultSetViewer.java']
{'.java': 1}
1
1
0
0
1
22,588,265
4,630,944
613,005
4,345
525
93
19
1
414
65
121
15
0
0
1970-01-01T00:27:19
33,177
Java
{'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202}
Apache License 2.0
679
dbeaver/dbeaver/15089/13436
dbeaver
dbeaver
https://github.com/dbeaver/dbeaver/issues/13436
https://github.com/dbeaver/dbeaver/pull/15089
https://github.com/dbeaver/dbeaver/pull/15089
1
fix
copy sql as source code for delphi and single quote
#### System information: - Windows 10 - DBeaver version 21.1.4.202108020335 - dark theme and office #### Describe the problem you're observing: when i use "copy sql as source code" and i don't select use string builder option the code generated have half cicle ")" in end of code. Delphi require string inside single quote at begin and end. Another problem is when i use single quote inside sql and generation of code. Single quote is in delphi a reserved charater for defining string . If i want use single quote in a string is necessary repeat single quote. #### Example code generate from dbaver 'SELECT COD_AGE_ID,STATO FROM mytable aa ' + 'where COD_AGE_ID = '00125' '); correct version in delphi 'SELECT COD_AGE_ID,STATO FROM mytable aa ' + 'where COD_AGE_ID = ''00125'' ';
3795b714f903eb25be17750d2f67ecf94186b6df
10f8607acbdccb6aed02df2a6f1f91caf8047994
https://github.com/dbeaver/dbeaver/compare/3795b714f903eb25be17750d2f67ecf94186b6df...10f8607acbdccb6aed02df2a6f1f91caf8047994
diff --git a/plugins/org.jkiss.dbeaver.ui.editors.sql/src/org/jkiss/dbeaver/ui/editors/sql/convert/impl/DelphiSQLConverter.java b/plugins/org.jkiss.dbeaver.ui.editors.sql/src/org/jkiss/dbeaver/ui/editors/sql/convert/impl/DelphiSQLConverter.java index bcbfb0a563..ecfa7173f5 100644 --- a/plugins/org.jkiss.dbeaver.ui.editors.sql/src/org/jkiss/dbeaver/ui/editors/sql/convert/impl/DelphiSQLConverter.java +++ b/plugins/org.jkiss.dbeaver.ui.editors.sql/src/org/jkiss/dbeaver/ui/editors/sql/convert/impl/DelphiSQLConverter.java @@ -40,6 +40,7 @@ public class DelphiSQLConverter extends SourceCodeSQLConverter { result.append("Query.Add("); } String line = sourceLines[i]; + line = line.replace("'", "''"); result.append('\\'').append(CommonUtils.escapeJavaString(line)); if (!trailingLineFeed) { result.append(lineDelimiter); @@ -48,9 +49,9 @@ public class DelphiSQLConverter extends SourceCodeSQLConverter { if (trailingLineFeed) { result.append(lineDelimiter); } - if ((i < sourceLines.length - 1) && (!useStringBuilder)) { + if (i < sourceLines.length - 1 && !useStringBuilder) { result.append(" + \\n"); - } else { + } else if (useStringBuilder){ result.append(");\\n"); } }
['plugins/org.jkiss.dbeaver.ui.editors.sql/src/org/jkiss/dbeaver/ui/editors/sql/convert/impl/DelphiSQLConverter.java']
{'.java': 1}
1
1
0
0
1
22,650,259
4,642,705
614,544
4,357
249
56
5
1
875
132
213
24
0
0
1970-01-01T00:27:20
33,177
Java
{'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202}
Apache License 2.0
678
dbeaver/dbeaver/15183/15158
dbeaver
dbeaver
https://github.com/dbeaver/dbeaver/issues/15158
https://github.com/dbeaver/dbeaver/pull/15183
https://github.com/dbeaver/dbeaver/pull/15183
1
fix
Advanced Copy as SQL doesn't copy table name as case sensitive
#### System information: - Operating system (distribution) and version: MacOS Monterey - DBeaver version: 21.3.2 Community #### Connection specification: - Database name and version: Postgres 12 - Driver name: PostgreSQL JDBC Driver - Do you use tunnels or proxies (SSH, SOCKS, etc)? No #### Describe the problem you're observing: When copying result row in order to get an insert SQL statement the table name is not copied with double quotes and proper (case sensitive) table name. Example table name "investmentRounds" is copied as "investmentrounds" and without quotes. This kind of statement doesn't work and the name of the table must be corrected. #### Steps to reproduce, if exist: 1. Select some data 2. Highlight a row in the results tab 3. Right click -> Advanced Copy -> Copy as SQL 4. Paste in editor and notice the table name to be all lower case
acac6596149745c7bc12f417d159563c9d9374a6
a8fc093bf529f51b005e7bc1f53fb620d3fadecf
https://github.com/dbeaver/dbeaver/compare/acac6596149745c7bc12f417d159563c9d9374a6...a8fc093bf529f51b005e7bc1f53fb620d3fadecf
diff --git a/plugins/org.jkiss.dbeaver.data.transfer/src/org/jkiss/dbeaver/tools/transfer/DTUtils.java b/plugins/org.jkiss.dbeaver.data.transfer/src/org/jkiss/dbeaver/tools/transfer/DTUtils.java index 1b0824c937..6c5acdcd86 100644 --- a/plugins/org.jkiss.dbeaver.data.transfer/src/org/jkiss/dbeaver/tools/transfer/DTUtils.java +++ b/plugins/org.jkiss.dbeaver.data.transfer/src/org/jkiss/dbeaver/tools/transfer/DTUtils.java @@ -103,7 +103,7 @@ public class DTUtils { public static String getTableNameFromQuery(DBPDataSource dataSource, SQLQueryContainer queryContainer, boolean shortName) { SQLScriptElement query = queryContainer.getQuery(); if (query instanceof SQLQuery) { - DBCEntityMetaData singleSource = ((SQLQuery) query).getSingleSource(); + DBCEntityMetaData singleSource = ((SQLQuery) query).getEntityMetadata(true); if (singleSource != null) { SQLDialect dialect = dataSource.getSQLDialect(); String entity = transformName(dialect, singleSource.getEntityName()); diff --git a/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/SQLServerUtils.java b/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/SQLServerUtils.java index dca19c4b62..0a916b991e 100644 --- a/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/SQLServerUtils.java +++ b/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/SQLServerUtils.java @@ -312,7 +312,7 @@ public class SQLServerUtils { } public static SQLServerTableBase getTableFromQuery(DBCSession session, SQLQuery sqlQuery, SQLServerDataSource dataSource) throws DBException, SQLException { - DBCEntityMetaData singleSource = sqlQuery.getSingleSource(); + DBCEntityMetaData singleSource = sqlQuery.getEntityMetadata(false); String catalogName = null; if (singleSource != null) { catalogName = singleSource.getCatalogName(); diff --git a/plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/exec/DBExecUtils.java b/plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/exec/DBExecUtils.java index bc75ed5d9d..d9e1ec995d 100644 --- a/plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/exec/DBExecUtils.java +++ b/plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/exec/DBExecUtils.java @@ -640,7 +640,7 @@ public class DBExecUtils { Object sourceDescriptor = executionSource.getSourceDescriptor(); if (sourceDescriptor instanceof SQLQuery) { sqlQuery = (SQLQuery) sourceDescriptor; - entityMeta = sqlQuery.getSingleSource(); + entityMeta = sqlQuery.getEntityMetadata(false); } if (entityMeta != null) { entity = DBUtils.getEntityFromMetaData(monitor, session.getExecutionContext(), entityMeta); diff --git a/plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/sql/SQLQuery.java b/plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/sql/SQLQuery.java index 202b585fe1..26300584f1 100644 --- a/plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/sql/SQLQuery.java +++ b/plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/sql/SQLQuery.java @@ -73,7 +73,7 @@ public class SQLQuery implements SQLScriptElement { @NotNull private SQLQueryType type; private Statement statement; - private SingleTableMeta singleTableMeta; + private SingleTableMeta singleTableMeta, rawSingleTableMetadata; private List<SQLSelectItem> selectItems; private String queryTitle; @@ -214,18 +214,27 @@ public class SQLQuery implements SQLScriptElement { } private void fillSingleSource(Table fromItem) { - singleTableMeta = createTableMetaData(fromItem); + rawSingleTableMetadata = createOriginalSourceTableMetaData(fromItem); + singleTableMeta = createUnquotedTableMetaData(rawSingleTableMetadata); } SingleTableMeta createTableMetaData(Table fromItem) { + return createUnquotedTableMetaData(createOriginalSourceTableMetaData(fromItem)); + } + + private SingleTableMeta createOriginalSourceTableMetaData(Table fromItem) { Database database = fromItem.getDatabase(); String catalogName = database == null ? null : database.getDatabaseName(); String schemaName = fromItem.getSchemaName(); String tableName = fromItem.getName(); + return new SingleTableMeta(catalogName, schemaName, tableName); + } + + private SingleTableMeta createUnquotedTableMetaData(SingleTableMeta tableMeta) { return new SingleTableMeta( - unquoteIdentifier(catalogName), - unquoteIdentifier(schemaName), - unquoteIdentifier(tableName)); + unquoteIdentifier(tableMeta.getCatalogName()), + unquoteIdentifier(tableMeta.getSchemaName()), + unquoteIdentifier(tableMeta.getEntityName())); } private String unquoteIdentifier(String name) { @@ -345,9 +354,9 @@ public class SQLQuery implements SQLScriptElement { return type; } - public DBCEntityMetaData getSingleSource() { + public DBCEntityMetaData getEntityMetadata(boolean raw) { parseQuery(); - return singleTableMeta; + return raw? rawSingleTableMetadata : singleTableMeta; } public void setParameters(List<SQLQueryParameter> parameters) { diff --git a/plugins/org.jkiss.dbeaver.ui.editors.sql/src/org/jkiss/dbeaver/ui/editors/sql/SQLEditor.java b/plugins/org.jkiss.dbeaver.ui.editors.sql/src/org/jkiss/dbeaver/ui/editors/sql/SQLEditor.java index d74ccca8ee..71d5be0d3a 100644 --- a/plugins/org.jkiss.dbeaver.ui.editors.sql/src/org/jkiss/dbeaver/ui/editors/sql/SQLEditor.java +++ b/plugins/org.jkiss.dbeaver.ui.editors.sql/src/org/jkiss/dbeaver/ui/editors/sql/SQLEditor.java @@ -2295,8 +2295,8 @@ public class SQLEditor extends SQLEditorBase implements SQLQuery query = (SQLQuery) queries.get(0); if (query.isDeleteUpdateDangerous()) { String targetName = "multiple tables"; - if (query.getSingleSource() != null) { - targetName = query.getSingleSource().getEntityName(); + if (query.getEntityMetadata(false) != null) { + targetName = query.getEntityMetadata(false).getEntityName(); } if (ConfirmationDialog.showConfirmDialogEx( ResourceBundle.getBundle(SQLEditorMessages.BUNDLE_NAME),
['plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/SQLServerUtils.java', 'plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/exec/DBExecUtils.java', 'plugins/org.jkiss.dbeaver.data.transfer/src/org/jkiss/dbeaver/tools/transfer/DTUtils.java', 'plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/sql/SQLQuery.java', 'plugins/org.jkiss.dbeaver.ui.editors.sql/src/org/jkiss/dbeaver/ui/editors/sql/SQLEditor.java']
{'.java': 5}
5
5
0
0
5
22,693,159
4,650,361
615,474
4,358
1,964
380
33
5
882
144
197
19
0
0
1970-01-01T00:27:22
33,177
Java
{'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202}
Apache License 2.0
677
dbeaver/dbeaver/15184/14296
dbeaver
dbeaver
https://github.com/dbeaver/dbeaver/issues/14296
https://github.com/dbeaver/dbeaver/pull/15184
https://github.com/dbeaver/dbeaver/pull/15184
1
fix
Oracle Alternative Quoting Mechanism Not Properly Ended
#### System information: - Windows 10 64-bit - DBeaver 21.2.3 - No additional extensions #### Connection specification: - Oracle Database 12c - Oracle JDBC driver 12.2.0.1 - No tunnels or proxies #### Describe the problem you're observing: Alternative quoting mechanism ("Q") for string literals is not working correctly when the alternative quoting character is repeated at the end of a string. #### Steps to reproduce: I execute this SQL statement: `SELECT q'!Test!!' FROM DUAL;` And get this error: > SQL Error [933] [42000]: ORA-00933: SQL command not properly ended If I first highlight the whole SQL statement or remove the semi-colon before executing it, it runs without errors and outputs: ``` Q'!TEST!!'| ----------+ Test! | ``` In both cases, the appearance is wrong with all of `' FROM DUAL;` being SQL string colour and `q'{{Test}}` not being so. Other scenarios: * If you add an odd number of quotes to the string (e.g. `q'!It's a test!!'`), it'll run fine but still appear wrong. * If the string has the alternative quoting character followed by a quote within it (e.g. `q'!Test!'!'`), it'll correctly throw an error. * If the character before the final alternative quoting character is anything else (e.g. `q'!Test! !'`), it'll both run and look fine. * If the string has an odd number of the alternative quoting characters (e.g. `q'!Test!!!'`), it'll both run and look fine. #### Include any warning/errors/backtraces from the logs ``` !ENTRY org.jkiss.dbeaver.model 4 0 2021-10-19 17:20:57.514 !MESSAGE SQL Error [933] [42000]: ORA-00933: SQL command not properly ended !SUBENTRY 1 org.jkiss.dbeaver.model 4 0 2021-10-19 17:20:57.515 !MESSAGE SQL Error [933] [42000]: ORA-00933: SQL command not properly ended !SUBENTRY 2 org.jkiss.dbeaver.model 4 0 2021-10-19 17:20:57.515 !MESSAGE Error : 933, Position : 27, Sql = SELECT q'!Test!!' FROM DUAL;, OriginalSql = SELECT q'!Test!!' FROM DUAL;, Error Msg = ORA-00933: SQL command not properly ended !STACK 0 Error : 933, Position : 27, Sql = SELECT q'!Test!!' FROM DUAL;, OriginalSql = SELECT q'!Test!!' FROM DUAL;, Error Msg = ORA-00933: SQL command not properly ended at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:498) at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:446) at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1054) at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:623) at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:252) at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:612) at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:213) at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:37) at oracle.jdbc.driver.T4CStatement.executeForDescribe(T4CStatement.java:733) at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:904) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1082) at oracle.jdbc.driver.OracleStatement.executeInternal(OracleStatement.java:1737) at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:1692) at oracle.jdbc.driver.OracleStatementWrapper.execute(OracleStatementWrapper.java:300) at org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCStatementImpl.execute(JDBCStatementImpl.java:330) at org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCStatementImpl.executeStatement(JDBCStatementImpl.java:130) at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.executeStatement(SQLQueryJob.java:513) at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.lambda$0(SQLQueryJob.java:444) at org.jkiss.dbeaver.model.exec.DBExecUtils.tryExecuteRecover(DBExecUtils.java:171) at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.executeSingleQuery(SQLQueryJob.java:431) at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.extractData(SQLQueryJob.java:816) at org.jkiss.dbeaver.ui.editors.sql.SQLEditor$QueryResultsContainer.readData(SQLEditor.java:3462) at org.jkiss.dbeaver.ui.controls.resultset.ResultSetJobDataRead.lambda$0(ResultSetJobDataRead.java:118) at org.jkiss.dbeaver.model.exec.DBExecUtils.tryExecuteRecover(DBExecUtils.java:171) at org.jkiss.dbeaver.ui.controls.resultset.ResultSetJobDataRead.run(ResultSetJobDataRead.java:116) at org.jkiss.dbeaver.ui.controls.resultset.ResultSetViewer$ResultSetDataPumpJob.run(ResultSetViewer.java:4718) at org.jkiss.dbeaver.model.runtime.AbstractJob.run(AbstractJob.java:105) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63) ```
7ed7fd29d5cd5793ede0313235bcf417bd72f461
e26f3c4e2fc1314e7f0a7792da974af726125700
https://github.com/dbeaver/dbeaver/compare/7ed7fd29d5cd5793ede0313235bcf417bd72f461...e26f3c4e2fc1314e7f0a7792da974af726125700
diff --git a/plugins/org.jkiss.dbeaver.ext.oracle/src/org/jkiss/dbeaver/ext/oracle/sql/OracleDialectRules.java b/plugins/org.jkiss.dbeaver.ext.oracle/src/org/jkiss/dbeaver/ext/oracle/sql/OracleDialectRules.java index 60e3991bb7..6d27c76a92 100644 --- a/plugins/org.jkiss.dbeaver.ext.oracle/src/org/jkiss/dbeaver/ext/oracle/sql/OracleDialectRules.java +++ b/plugins/org.jkiss.dbeaver.ext.oracle/src/org/jkiss/dbeaver/ext/oracle/sql/OracleDialectRules.java @@ -61,28 +61,9 @@ class OracleDialectRules implements TPRuleProvider { if (!Character.isLetterOrDigit(quoteStartChar)) { // Probably a Q-string char quoteEndChar = getQuoteEndChar(quoteStartChar); - int charsRead = 0; - boolean isQuote = true; - for (;;) { - c = scanner.read(); - charsRead++; - if (c == quoteEndChar) { - c = scanner.read(); - charsRead++; - if (c == '\\'') { - break; - } - } else if (c == TPCharacterScanner.EOF) { - isQuote = false; - break; - } - } - if (isQuote) { + + if (tryReadQString(scanner, quoteEndChar)) { return stringToken; - } else { - for (int i = 0; i < charsRead; i++) { - scanner.unread(); - } } } else { quoteStartChar = (char) -1; @@ -99,6 +80,26 @@ class OracleDialectRules implements TPRuleProvider { return TPTokenAbstract.UNDEFINED; } + private boolean tryReadQString(TPCharacterScanner scanner, char quoteEndChar) { + int charsRead = 0; + int prevChar = -1, currChar = -1; + boolean isEndOfLiteral, isEndOfText; + do { + prevChar = currChar; + currChar = scanner.read(); + charsRead++; + isEndOfLiteral = prevChar == quoteEndChar && currChar == '\\''; + isEndOfText = currChar == TPCharacterScanner.EOF; + } while (!isEndOfLiteral && !isEndOfText); + + if (isEndOfText) { + for (int i = 0; i < charsRead; i++) { + scanner.unread(); + } + } + return isEndOfLiteral; + } + private static char getQuoteEndChar(char startChar) { switch (startChar) { case '<': return '>';
['plugins/org.jkiss.dbeaver.ext.oracle/src/org/jkiss/dbeaver/ext/oracle/sql/OracleDialectRules.java']
{'.java': 1}
1
1
0
0
1
22,691,287
4,649,999
615,441
4,358
1,777
300
43
1
4,556
392
1,265
87
0
2
1970-01-01T00:27:22
33,177
Java
{'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202}
Apache License 2.0
676
dbeaver/dbeaver/16854/16705
dbeaver
dbeaver
https://github.com/dbeaver/dbeaver/issues/16705
https://github.com/dbeaver/dbeaver/pull/16854
https://github.com/dbeaver/dbeaver/pull/16854
1
closes
[Wayland] Data can't be edited inline after double click
#### System information: - Operating system (distribution) and version Ubuntu 22.04 - DBeaver version 22.1.0 #### Steps to reproduce, if exist: 1. Double-click on any cell in data editor 2. Input something **Expected:** Data in a cell is replaced with the input **Actual:** Nothing happens
cc530b2a5b86e4f0d38b03335d59c59865d0d12e
8fbd8d861a51a5cfb73530ea6fe7ddb7807a6f85
https://github.com/dbeaver/dbeaver/compare/cc530b2a5b86e4f0d38b03335d59c59865d0d12e...8fbd8d861a51a5cfb73530ea6fe7ddb7807a6f85
diff --git a/plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/lightgrid/LightGrid.java b/plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/lightgrid/LightGrid.java index 83f42eac12..8a3070d215 100644 --- a/plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/lightgrid/LightGrid.java +++ b/plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/lightgrid/LightGrid.java @@ -3130,7 +3130,13 @@ public abstract class LightGrid extends Canvas { // and therefore the grid has a child. The solution is to // forceFocus() if ((getStyle() & SWT.NO_FOCUS) != SWT.NO_FOCUS) { - forceFocus(); + GridPos cell = getCell(new Point(e.x, e.y)); + if (cell == null || !cell.equalsTo(getFocusPos())) { + // We don't want to call this event if the selected cell equals active one + // this is related to bug with wayland handling of force focus, which led to editors + // loosing focus on double click see #16705 + forceFocus(); + } } //if populated will be fired at end of method.
['plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/lightgrid/LightGrid.java']
{'.java': 1}
1
1
0
0
1
23,737,785
4,861,616
641,519
4,577
451
92
8
1
303
45
74
11
0
0
1970-01-01T00:27:35
33,177
Java
{'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202}
Apache License 2.0
675
dbeaver/dbeaver/17319/16368
dbeaver
dbeaver
https://github.com/dbeaver/dbeaver/issues/16368
https://github.com/dbeaver/dbeaver/pull/17319
https://github.com/dbeaver/dbeaver/pull/17319
1
fix
Azure Synapse Serverless: cannot read view definition
#### System information: - Windows 10 - DBeaver 22.0.3 #### Connection specification: - Database type: Azure Synapse "serverless" - Driver name: Azure SQL Server - No tunnels or proxies #### Describe the problem you're observing: Trying to get the DDL of a view produces a NullPointerException and the definition pane shows: ``` /* ERROR WHILE READING SOURCE: null */ ``` In version 22.0.0, view definitions could be obtained, see #15490. #### Steps to reproduce, if exist: - Open a view object in this type of database - Go to Properties -> Definition #### Include any warning/errors/backtraces from the logs Exception stack trace: java.lang.NullPointerException at org.jkiss.dbeaver.model.DBUtils.getQuotedIdentifier(DBUtils.java:78) at org.jkiss.dbeaver.ext.mssql.edit.SQLServerViewManager.createOrReplaceViewQuery(SQLServerViewManager.java:115) at org.jkiss.dbeaver.ext.mssql.edit.SQLServerViewManager.addObjectDeleteActions(SQLServerViewManager.java:91) at org.jkiss.dbeaver.model.impl.sql.edit.SQLObjectEditor$ObjectDeleteCommand.getPersistActions(SQLObjectEditor.java:401) at org.jkiss.dbeaver.model.impl.sql.edit.struct.SQLTableManager.getTableDDL(SQLTableManager.java:224) at org.jkiss.dbeaver.model.struct.DBStructUtils.generateTableDDL(DBStructUtils.java:89) at org.jkiss.dbeaver.model.struct.DBStructUtils.getTableDDL(DBStructUtils.java:116) at org.jkiss.dbeaver.model.struct.DBStructUtils.generateTableListDDL(DBStructUtils.java:176) at org.jkiss.dbeaver.ui.editors.sql.SQLSourceViewer.getSourceText(SQLSourceViewer.java:95) at org.jkiss.dbeaver.ui.editors.sql.SQLEditorNested$ObjectDocumentProvider$1.lambda$0(SQLEditorNested.java:279) at org.jkiss.dbeaver.model.exec.DBExecUtils.tryExecuteRecover(DBExecUtils.java:171) at org.jkiss.dbeaver.ui.editors.sql.SQLEditorNested$ObjectDocumentProvider$1.run(SQLEditorNested.java:277) at org.jkiss.dbeaver.model.runtime.AbstractJob.run(AbstractJob.java:105) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63) Session data: eclipse.buildId=unknown java.version=11.0.12 java.vendor=Eclipse Foundation BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en Command-line arguments: -os win32 -ws win32 -arch x86_64 Connection test shows: Server: Microsoft SQL Server 12.00.214 Microsoft SQL Azure (RTM) - 12.0.2000.8 Mar 31 2022 08:13:33 Driver: Microsoft JDBC Driver 9.2 for SQL Server 9.2.0.0 Output of `SELECT SERVERPROPERTY('EngineEdition')`: 11 `SELECT definition FROM sys.sql_modules WHERE object_id = (OBJECT_ID(N'your_shema_name.your_view_name'))` (adapted to existing schemas and views, obviously) gives no results.
2e150880eb8c50b521fce85aacfad7c1bf9ea29f
4c27fb0b16d838cf7bd1eeafc2082bc7136f7ba5
https://github.com/dbeaver/dbeaver/compare/2e150880eb8c50b521fce85aacfad7c1bf9ea29f...4c27fb0b16d838cf7bd1eeafc2082bc7136f7ba5
diff --git a/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/edit/SQLServerViewManager.java b/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/edit/SQLServerViewManager.java index 0a6428e52c..10b8537007 100644 --- a/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/edit/SQLServerViewManager.java +++ b/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/edit/SQLServerViewManager.java @@ -97,7 +97,8 @@ public class SQLServerViewManager extends SQLServerBaseTableManager<SQLServerVie { SQLServerDatabase procDatabase = view.getContainer().getDatabase(); SQLServerDatabase defaultDatabase = ((SQLServerExecutionContext)executionContext).getDefaultCatalog(); - if (defaultDatabase != procDatabase) { + boolean addUse = defaultDatabase != null && procDatabase != null && defaultDatabase != procDatabase; + if (addUse) { actions.add(new SQLDatabasePersistAction("Set current database", "USE " + DBUtils.getQuotedIdentifier(procDatabase), false)); //$NON-NLS-2$ } @@ -113,7 +114,7 @@ public class SQLServerViewManager extends SQLServerBaseTableManager<SQLServerVie break; } - if (defaultDatabase != procDatabase) { + if (addUse) { actions.add(new SQLDatabasePersistAction("Set current database ", "USE " + DBUtils.getQuotedIdentifier(defaultDatabase), false)); //$NON-NLS-2$ } }
['plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/edit/SQLServerViewManager.java']
{'.java': 1}
1
1
0
0
1
23,944,358
4,902,210
647,191
4,610
251
55
5
1
2,701
201
702
63
0
1
1970-01-01T00:27:40
33,177
Java
{'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202}
Apache License 2.0
674
dbeaver/dbeaver/18887/18885
dbeaver
dbeaver
https://github.com/dbeaver/dbeaver/issues/18885
https://github.com/dbeaver/dbeaver/pull/18887
https://github.com/dbeaver/dbeaver/pull/18887
1
fix
Get prompted every time a variable is referenced in a SQL script
### Description I upgraded DBeaver Community Edition to version 22.3.3.202301211053 a few days ago. After this upgrade the behavior of the variables in DBeaver has changed., I use @set statements to setup values for the variable and was able to use them throughout my SQL scripts. The same scripts now kept prompting for the value of the variables. Looks like it does not use the values that I set in the script. Even after I entered the value in the "Bind parameters" dialog, it popped up each time the variable is used. I have been searching to see if there is setting that I can control but to no avail... thinking of downgrading to 22.3.2, Thanks ### DBeaver Version Community Edition 22.3.3 ### Operating System Windows ### Database and driver Snowflake ### Steps to reproduce @set v_WorkFlow = Clone_Operations_Schema @echo ${v_WorkFlow}, ${V_WORKFLOW} select '${v_WorkFlow}'; ### Additional context _No response_
a7f2fd65626498d2ea3f2e1a5ded926434ab5d11
884553d44a3ccfc07c86ee00ec0861564e760f88
https://github.com/dbeaver/dbeaver/compare/a7f2fd65626498d2ea3f2e1a5ded926434ab5d11...884553d44a3ccfc07c86ee00ec0861564e760f88
diff --git a/plugins/org.jkiss.dbeaver.model.sql/src/org/jkiss/dbeaver/model/sql/parser/SQLScriptParser.java b/plugins/org.jkiss.dbeaver.model.sql/src/org/jkiss/dbeaver/model/sql/parser/SQLScriptParser.java index 1dc5f278e1..b712d7f7cb 100644 --- a/plugins/org.jkiss.dbeaver.model.sql/src/org/jkiss/dbeaver/model/sql/parser/SQLScriptParser.java +++ b/plugins/org.jkiss.dbeaver.model.sql/src/org/jkiss/dbeaver/model/sql/parser/SQLScriptParser.java @@ -781,7 +781,13 @@ public class SQLScriptParser { } if (param == null) { - param = new SQLQueryParameter(syntaxManager, orderPos, matcher.group(0), start, matcher.end() - matcher.start()); + param = new SQLQueryParameter( + syntaxManager, + orderPos, + matcher.group(SQLQueryParameter.VARIABLE_NAME_GROUP_NAME).toUpperCase(Locale.ENGLISH), + start, + matcher.end() - matcher.start() + ); if (parameters == null) { parameters = new ArrayList<>(); } diff --git a/plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/sql/SQLQueryParameter.java b/plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/sql/SQLQueryParameter.java index 5b12c7678b..dcab25dea1 100644 --- a/plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/sql/SQLQueryParameter.java +++ b/plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/sql/SQLQueryParameter.java @@ -25,9 +25,10 @@ import java.util.regex.Pattern; */ public class SQLQueryParameter { + public static final String VARIABLE_NAME_GROUP_NAME = "pn"; - private static final Pattern VARIABLE_PATTERN_SIMPLE = Pattern.compile("\\\\$\\\\{[a-z0-9_]+\\\\}", Pattern.CASE_INSENSITIVE); - private static final Pattern VARIABLE_PATTERN_FULL = Pattern.compile("\\\\$P?!?\\\\{[a-z0-9_]+\\\\}", Pattern.CASE_INSENSITIVE); + private static final Pattern VARIABLE_PATTERN_SIMPLE = Pattern.compile("\\\\$\\\\{(?<pn>[a-z0-9_]+)\\\\}", Pattern.CASE_INSENSITIVE); + private static final Pattern VARIABLE_PATTERN_FULL = Pattern.compile("\\\\$P?!?\\\\{(?<pn>[a-z0-9_]+)\\\\}", Pattern.CASE_INSENSITIVE); private final SQLSyntaxManager syntaxManager; diff --git a/test/org.jkiss.dbeaver.test.platform/src/org/jkiss/dbeaver/model/sql/parser/SQLScriptParserGenericsTest.java b/test/org.jkiss.dbeaver.test.platform/src/org/jkiss/dbeaver/model/sql/parser/SQLScriptParserGenericsTest.java index 7008710ba3..202f194b73 100644 --- a/test/org.jkiss.dbeaver.test.platform/src/org/jkiss/dbeaver/model/sql/parser/SQLScriptParserGenericsTest.java +++ b/test/org.jkiss.dbeaver.test.platform/src/org/jkiss/dbeaver/model/sql/parser/SQLScriptParserGenericsTest.java @@ -176,7 +176,7 @@ public class SQLScriptParserGenericsTest { } Assert.assertEquals(List.of("1", "SYs_B_1", "MyVar8", "ABC", "#d2"), actualParamNames); } - + @Test public void parseVariables() throws DBException { List<String> inputParamNames = List.of("aBc", "PrE#%&@T", "a@c="); @@ -191,6 +191,36 @@ public class SQLScriptParserGenericsTest { } Assert.assertEquals(List.of("ABC", "PRE#%&@T", "A@C="), actualParamNames); } + + @Test + public void parseVariablesInStrings() throws DBException { + List<String> inputParamNames = List.of("aBc", "PrET", "ac"); + StringJoiner joiner = new StringJoiner(", ", "select ", " from dual"); + inputParamNames.stream().forEach(p -> joiner.add("'${" + p + "}'")); + String query = joiner.toString(); + SQLParserContext context = createParserContext(setDialect("snowflake"), query); + List<SQLQueryParameter> params = SQLScriptParser.parseParametersAndVariables(context, 0, query.length()); + List<String> actualParamNames = new ArrayList<String>(); + for (SQLQueryParameter sqlQueryParameter : params) { + actualParamNames.add(sqlQueryParameter.getName()); + } + Assert.assertEquals(List.of("ABC", "PRET", "AC"), actualParamNames); + } + + @Test + public void parseVariablesInComment() throws DBException { + List<String> inputParamNames = List.of("aBc", "PrET", "ac"); + StringJoiner joiner = new StringJoiner(", ", "-- ", " "); + inputParamNames.stream().forEach(p -> joiner.add("${" + p + "}")); + String query = joiner.toString(); + SQLParserContext context = createParserContext(setDialect("snowflake"), query); + List<SQLQueryParameter> params = SQLScriptParser.parseParametersAndVariables(context, 0, query.length()); + List<String> actualParamNames = new ArrayList<String>(); + for (SQLQueryParameter sqlQueryParameter : params) { + actualParamNames.add(sqlQueryParameter.getName()); + } + Assert.assertEquals(List.of("ABC", "PRET", "AC"), actualParamNames); + } @Test public void parseParameterFromSetCommand() throws DBException {
['plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/sql/SQLQueryParameter.java', 'test/org.jkiss.dbeaver.test.platform/src/org/jkiss/dbeaver/model/sql/parser/SQLScriptParserGenericsTest.java', 'plugins/org.jkiss.dbeaver.model.sql/src/org/jkiss/dbeaver/model/sql/parser/SQLScriptParser.java']
{'.java': 3}
3
3
0
0
3
24,740,893
5,058,866
667,368
4,738
1,136
229
13
2
940
149
225
30
0
0
1970-01-01T00:27:54
33,177
Java
{'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202}
Apache License 2.0
673
dbeaver/dbeaver/20881/20529
dbeaver
dbeaver
https://github.com/dbeaver/dbeaver/issues/20529
https://github.com/dbeaver/dbeaver/pull/20881
https://github.com/dbeaver/dbeaver/pull/20881
1
closes
SSH connection defaults to OS login, if server login not saved in settings
### Description It's related to credential popup changes from #18017 - now if SSH is set to use encrypted certificates there will be a popup asking for certificate password, but there's no way to enter server login. If the login is stored in settings - it will work - but in case the login is left empty, the connection will default to OS login. ### DBeaver Version Community Edition 23.1.2 ### Operating System Windows 10 ### Database and driver _No response_ ### Steps to reproduce 1. Configure SSH with jump server (probably without the jump server will be the same) 2. Use encrypted certificate as auth, leave passphrases blank 3. Leave the "user name" blank 4. Try to connect The connection will ask for passphrase, but not for login and then it will default to using OS user name as SSH server login. ### Additional context _No response_
1ad21c12ab285733bdf877024ebb4d6d071617b1
41addd796eaf82905bfb7d587214542b8990c50d
https://github.com/dbeaver/dbeaver/compare/1ad21c12ab285733bdf877024ebb4d6d071617b1...41addd796eaf82905bfb7d587214542b8990c50d
diff --git a/plugins/org.jkiss.dbeaver.net.ssh.ui/src/org/jkiss/dbeaver/ui/net/ssh/SSHTunnelConfiguratorUI.java b/plugins/org.jkiss.dbeaver.net.ssh.ui/src/org/jkiss/dbeaver/ui/net/ssh/SSHTunnelConfiguratorUI.java index ffd49fbb4f..7f59eee123 100644 --- a/plugins/org.jkiss.dbeaver.net.ssh.ui/src/org/jkiss/dbeaver/ui/net/ssh/SSHTunnelConfiguratorUI.java +++ b/plugins/org.jkiss.dbeaver.net.ssh.ui/src/org/jkiss/dbeaver/ui/net/ssh/SSHTunnelConfiguratorUI.java @@ -256,7 +256,7 @@ public class SSHTunnelConfiguratorUI implements IObjectPropertyConfigurator<Obje ? SSHUIMessages.model_ssh_dialog_credentials_passphrase : SSHUIMessages.model_ssh_dialog_credentials_password, password, - type.equals(SSHConstants.AuthType.PUBLIC_KEY), + false, false ); } catch (Exception e) { @@ -298,9 +298,7 @@ public class SSHTunnelConfiguratorUI implements IObjectPropertyConfigurator<Obje DBPAuthInfo dbpAuthInfo = promptCredentialsDialog(authType, configuration.getUserName(), configuration.getPassword()); if (dbpAuthInfo != null) { - if (authType.equals(SSHConstants.AuthType.PASSWORD)) { - configuration.setUserName(dbpAuthInfo.getUserName()); - } + configuration.setUserName(dbpAuthInfo.getUserName()); configuration.setPassword(dbpAuthInfo.getUserPassword()); } checkJumpServerConfiguration(tunnel); @@ -337,19 +335,18 @@ public class SSHTunnelConfiguratorUI implements IObjectPropertyConfigurator<Obje ); if (tunnel.getRequiredCredentials(configuration, getJumpServerSettingsPrefix()) != DBWTunnel.AuthCredentials.NONE) { - DBPAuthInfo dbpAuthInfo = promptCredentialsDialog(authType, - configuration.getStringProperty(getJumpServerSettingsPrefix() - + DBConstants.PROP_ID_NAME), - configuration.getSecureProperty(getJumpServerSettingsPrefix() - + DBConstants.PROP_FEATURE_PASSWORD) + DBPAuthInfo dbpAuthInfo = promptCredentialsDialog( + authType, + configuration.getStringProperty(getJumpServerSettingsPrefix() + DBConstants.PROP_ID_NAME), + configuration.getSecureProperty( + getJumpServerSettingsPrefix() + DBConstants.PROP_FEATURE_PASSWORD) ); if (dbpAuthInfo != null) { - if (authType.equals(SSHConstants.AuthType.PASSWORD)) { - configuration.setProperty(getJumpServerSettingsPrefix() + DBConstants.PROP_ID_NAME, - dbpAuthInfo.getUserName() - ); - } - configuration.setSecureProperty(getJumpServerSettingsPrefix() + DBConstants.PROP_FEATURE_PASSWORD, + configuration.setProperty(getJumpServerSettingsPrefix() + DBConstants.PROP_ID_NAME, + dbpAuthInfo.getUserName() + ); + configuration.setSecureProperty( + getJumpServerSettingsPrefix() + DBConstants.PROP_FEATURE_PASSWORD, dbpAuthInfo.getUserPassword() ); } diff --git a/plugins/org.jkiss.dbeaver.registry/src/org/jkiss/dbeaver/registry/DataSourceDescriptor.java b/plugins/org.jkiss.dbeaver.registry/src/org/jkiss/dbeaver/registry/DataSourceDescriptor.java index 2aec12602b..0194debc58 100644 --- a/plugins/org.jkiss.dbeaver.registry/src/org/jkiss/dbeaver/registry/DataSourceDescriptor.java +++ b/plugins/org.jkiss.dbeaver.registry/src/org/jkiss/dbeaver/registry/DataSourceDescriptor.java @@ -1928,9 +1928,7 @@ public class DataSourceDescriptor } if (networkHandler != null) { - if (authType == DBWTunnel.AuthCredentials.CREDENTIALS) { - networkHandler.setUserName(authInfo.getUserName()); - } + networkHandler.setUserName(authInfo.getUserName()); networkHandler.setPassword(authInfo.getUserPassword()); networkHandler.setSavePassword(authInfo.isSavePassword()); actualConfig.updateHandler(networkHandler); @@ -1989,7 +1987,7 @@ public class DataSourceDescriptor authType == DBWTunnel.AuthCredentials.PASSWORD ? RegistryMessages.dialog_connection_auth_passphrase : RegistryMessages.dialog_connection_auth_password, password, - authType != DBWTunnel.AuthCredentials.CREDENTIALS, + false, canSavePassword ); return authInfo;
['plugins/org.jkiss.dbeaver.registry/src/org/jkiss/dbeaver/registry/DataSourceDescriptor.java', 'plugins/org.jkiss.dbeaver.net.ssh.ui/src/org/jkiss/dbeaver/ui/net/ssh/SSHTunnelConfiguratorUI.java']
{'.java': 2}
2
2
0
0
2
25,916,171
5,294,862
697,820
4,986
2,351
325
33
2
858
148
190
27
0
0
1970-01-01T00:28:12
33,177
Java
{'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202}
Apache License 2.0
687
dbeaver/dbeaver/12799/12796
dbeaver
dbeaver
https://github.com/dbeaver/dbeaver/issues/12796
https://github.com/dbeaver/dbeaver/pull/12799
https://github.com/dbeaver/dbeaver/pull/12799
1
fix
NPE with find/replace window
#### System information: - Operating system (distribution) and version Windows 10 - DBeaver version 21.1.0 - Additional extensions: n/a #### Connection specification: - Database name and version Oracle 12 - Driver name ojdbc 19 - Do you use tunnels or proxies (SSH, SOCKS, etc)? n/a #### Describe the problem you're observing: Sometimes the find/replace dialog, if left open while navigating different objects, throws a NullPointerException. When this happens, pressing the close button is useless. Instead, clicking on the X button successfully closes the dialog. An NPE is thrown every time you switch tab or click close. #### Steps to reproduce, if exist: I am not able to reliably reproduce this issue. #### Include any warning/errors/backtraces from the logs Exception when clicking "Close" ``` java.lang.NullPointerException at org.jkiss.dbeaver.ui.controls.lightgrid.LightGrid.selectCells(LightGrid.java:4178) at org.jkiss.dbeaver.ui.controls.resultset.spreadsheet.SpreadsheetFindReplaceTarget.endSession(SpreadsheetFindReplaceTarget.java:172) at org.jkiss.dbeaver.ui.DynamicFindReplaceTarget.endSession(DynamicFindReplaceTarget.java:105) at org.eclipse.ui.texteditor.FindReplaceDialog.handleDialogClose(FindReplaceDialog.java:1080) at org.eclipse.ui.texteditor.FindReplaceDialog.close(FindReplaceDialog.java:1055) at org.eclipse.ui.texteditor.FindReplaceDialog.buttonPressed(FindReplaceDialog.java:837) at org.eclipse.jface.dialogs.Dialog.lambda$0(Dialog.java:619) at org.eclipse.swt.events.SelectionListener$1.widgetSelected(SelectionListener.java:84) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:252) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:89) at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4209) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1043) ... ``` Exception when switching tabs (happens only after the first one was triggered ``` java.lang.NullPointerException at org.jkiss.dbeaver.ui.controls.lightgrid.LightGrid.selectCells(LightGrid.java:4178) at org.jkiss.dbeaver.ui.controls.resultset.spreadsheet.SpreadsheetFindReplaceTarget.endSession(SpreadsheetFindReplaceTarget.java:172) at org.jkiss.dbeaver.ui.DynamicFindReplaceTarget.endSession(DynamicFindReplaceTarget.java:105) at org.eclipse.ui.texteditor.FindReplaceDialog.updateTarget(FindReplaceDialog.java:1719) at org.eclipse.ui.texteditor.FindReplaceAction$FindReplaceDialogStub.partActivated(FindReplaceAction.java:130) at org.eclipse.ui.texteditor.FindReplaceAction$FindReplaceDialogStub.partActivated(FindReplaceAction.java:137) at org.eclipse.ui.internal.PartService$6.run(PartService.java:145) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:45) at org.eclipse.ui.internal.PartService.partActivated(PartService.java:142) at org.eclipse.ui.internal.WorkbenchPage$4.run(WorkbenchPage.java:4901) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:45) at org.eclipse.ui.internal.WorkbenchPage.firePartActivated(WorkbenchPage.java:4898) at org.eclipse.ui.internal.WorkbenchPage$E4PartListener.partActivated(WorkbenchPage.java:219) at org.eclipse.e4.ui.internal.workbench.PartServiceImpl$2.run(PartServiceImpl.java:249) ... ```
ad8a5859e3a946a7cd65f00ddb0e8c6a8e13276d
6ebeeb857461cf8963797e57c101b29eba863a57
https://github.com/dbeaver/dbeaver/compare/ad8a5859e3a946a7cd65f00ddb0e8c6a8e13276d...6ebeeb857461cf8963797e57c101b29eba863a57
diff --git a/plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/spreadsheet/SpreadsheetFindReplaceTarget.java b/plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/spreadsheet/SpreadsheetFindReplaceTarget.java index cb8862fc78..7f4a301895 100644 --- a/plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/spreadsheet/SpreadsheetFindReplaceTarget.java +++ b/plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/spreadsheet/SpreadsheetFindReplaceTarget.java @@ -61,7 +61,7 @@ class SpreadsheetFindReplaceTarget implements IFindReplaceTarget, IFindReplaceTa private Color scopeHighlightColor; private boolean replaceAll; private boolean sessionActive = false; - private List<GridPos> originalSelection = null; + private List<GridPos> originalSelection = new ArrayList<>(); public static synchronized SpreadsheetFindReplaceTarget getInstance() { if (instance == null) {
['plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/spreadsheet/SpreadsheetFindReplaceTarget.java']
{'.java': 1}
1
1
0
0
1
21,264,034
4,361,163
580,241
4,155
118
25
2
1
3,282
194
741
56
0
2
1970-01-01T00:27:03
33,177
Java
{'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202}
Apache License 2.0
783
alibaba/easyexcel/1923/1651
alibaba
easyexcel
https://github.com/alibaba/easyexcel/issues/1651
https://github.com/alibaba/easyexcel/pull/1923
https://github.com/alibaba/easyexcel/pull/1923
1
fix
使用模板填充导出的时候设置自动换行报错
**触发场景描述** 模板填充导出的时候设置自动换行报错 **触发Bug的代码** ```java InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/annualPlanning.xlsx"); //内容策略 WriteCellStyle contentWriteCellStyle = new WriteCellStyle(); //设置 自动换行 contentWriteCellStyle.setWrapped(true); HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(null, contentWriteCellStyle); ExcelWriter excelWriter = EasyExcel.write(outputStream) .withTemplate(resourceAsStream) .registerWriteHandler(new CustomCellWriteHandler()) .registerWriteHandler(horizontalCellStyleStrategy) .build(); WriteSheet writeSheet = EasyExcel.writerSheet().build(); FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build(); List<AnnualPlanningExcel> excelList; for (AnnualPlanningExcel planningExcel : annualPlanningExcelList) { excelList = new ArrayList<>(); excelList.add(planningExcel); excelWriter.fill(excelList, fillConfig, writeSheet); number++; } Map<String, Object> map = new HashMap<>(); map.put("name", tbAuditPlan.getPlanName()); excelWriter.fill(map, writeSheet); excelWriter.finish(); outputStream.flush(); outputStream.close(); ``` **java.lang.NullPointerException at com.alibaba.excel.write.style.HorizontalCellStyleStrategy.setContentCellStyle(HorizontalCellStyleStrategy.java:66) at com.alibaba.excel.write.style.AbstractCellStyleStrategy.afterCellDispose(AbstractCellStyleStrategy.java:60) at com.alibaba.excel.util.WriteHandlerUtils.afterCellDispose(WriteHandlerUtils.java:176) at com.alibaba.excel.util.WriteHandlerUtils.afterCellDispose(WriteHandlerUtils.java:164) at com.alibaba.excel.write.executor.ExcelWriteFillExecutor.doFill(ExcelWriteFillExecutor.java:201) at com.alibaba.excel.write.executor.ExcelWriteFillExecutor.fill(ExcelWriteFillExecutor.java:121) at com.alibaba.excel.write.ExcelBuilderImpl.fill(ExcelBuilderImpl.java:78) at com.alibaba.excel.ExcelWriter.fill(ExcelWriter.java:185) at com.alibaba.excel.ExcelWriter.fill(ExcelWriter.java:173) at org.dvt.modules.tb.service.impl.AnnualPlanningServiceImpl.download(AnnualPlanningServiceImpl.java:290) at org.dvt.modules.tb.controller.AnnualPlanningController.download(AnnualPlanningController.java:176) 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:190) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) at javax.servlet.http.HttpServlet.service(HttpServlet.java:645) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) at javax.servlet.http.HttpServlet.service(HttpServlet.java:750) 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:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449) at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365) at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90) at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83) at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383) at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362) at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125) 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.CorsFilter.doFilterInternal(CorsFilter.java:92) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92) at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271) 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:100) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) 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.FormContentFilter.doFilterInternal(FormContentFilter.java:93) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) 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:201) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) 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:202) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1639) 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)**
5a8d3f5bd452a4a6aa4f5156acd3c70c4620450a
fee773f04b3180621530494fad8590babf2040e7
https://github.com/alibaba/easyexcel/compare/5a8d3f5bd452a4a6aa4f5156acd3c70c4620450a...fee773f04b3180621530494fad8590babf2040e7
diff --git a/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java b/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java index 295cd556..504570fa 100644 --- a/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java +++ b/src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java @@ -60,9 +60,10 @@ public class HorizontalCellStyleStrategy extends AbstractCellStyleStrategy { @Override protected void setContentCellStyle(Cell cell, Head head, Integer relativeRowIndex) { - if (contentCellStyleList == null || contentCellStyleList.isEmpty()) { + if (contentCellStyleList == null || contentCellStyleList.isEmpty() || relativeRowIndex == null) { return; } + cell.setCellStyle(contentCellStyleList.get(relativeRowIndex % contentCellStyleList.size())); }
['src/main/java/com/alibaba/excel/write/style/HorizontalCellStyleStrategy.java']
{'.java': 1}
1
1
0
0
1
680,873
142,666
21,841
252
187
36
3
1
11,986
284
2,337
138
0
1
1970-01-01T00:27:00
28,637
Java
{'Java': 1416062}
Apache License 2.0
1,657
square/leakcanary/475/417
square
leakcanary
https://github.com/square/leakcanary/issues/417
https://github.com/square/leakcanary/pull/475
https://github.com/square/leakcanary/pull/475
1
fixes
java.lang.NullPointerException alyunOS
In com.sumxiang.noteapp:1.0:2. - FAILURE: java.lang.NullPointerException: java.lang.NullPointerException at com.squareup.leakcanary.HahaHelper.classInstanceValues(HahaHelper.java:143) at com.squareup.leakcanary.HahaHelper.asString(HahaHelper.java:73) at com.squareup.leakcanary.HahaHelper.threadName(HahaHelper.java:55) at com.squareup.leakcanary.ShortestPathFinder.enqueueGcRoots(ShortestPathFinder.java:133) at com.squareup.leakcanary.ShortestPathFinder.findPath(ShortestPathFinder.java:82) at com.squareup.leakcanary.HeapAnalyzer.findLeakTrace(HeapAnalyzer.java:112) at com.squareup.leakcanary.HeapAnalyzer.checkForLeak(HeapAnalyzer.java:87) at com.squareup.leakcanary.internal.HeapAnalyzerService.onHandleIntent(HeapAnalyzerService.java:58) at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.os.HandlerThread.run(HandlerThread.java:61) - Reference Key: 17ea16ba-cb43-4a23-bd9e-18c6ad09b2d2 - Device: Xiaomi Xiaomi HM 1SW armani - Android Version: 4.4.4 API: 19 LeakCanary: 1.4-beta1 02804f3 - Durations: watch=5018ms, gc=123ms, heap dump=580ms, analysis=4082ms - Excluded Refs: | Field: android.app.ActivityThread$ActivityClientRecord.nextIdle | Field: android.widget.Editor$EasyEditSpanController.this$0 | Field: android.widget.Editor$SpanController.this$0 | Field: android.os.Message.obj | Field: android.os.Message.next | Field: android.os.Message.target | Field: android.view.inputmethod.InputMethodManager.mNextServedView | Field: android.view.inputmethod.InputMethodManager.mServedView | Field: android.view.inputmethod.InputMethodManager.mServedInputConnection | Field: android.view.inputmethod.InputMethodManager.mCurRootView | Field: android.animation.LayoutTransition$1.val$parent | Field: android.view.textservice.SpellCheckerSession$1.this$0 | Field: android.support.v7.internal.widget.ActivityChooserModel.mActivityChoserModelPolicy | Field: android.widget.ActivityChooserModel.mActivityChoserModelPolicy | Field: android.speech.SpeechRecognizer$InternalListener.this$0 | Field: android.accounts.AccountManager$AmsTask$Response.this$1 | Field: android.media.MediaScannerConnection.mContext | Field: android.os.UserManager.mContext | Field: android.appwidget.AppWidgetHost$Callbacks.this$0 | Field: android.media.AudioManager$1.this$0 | Field: android.view.Choreographer$FrameDisplayEventReceiver.mMessageQueue (always) | Static field: android.text.TextLine.sCached | Thread:FinalizerWatchdogDaemon (always) | Thread:main (always) | Thread:LeakCanary-Heap-Dump (always) | Class:java.lang.ref.WeakReference (always) | Class:java.lang.ref.SoftReference (always) | Class:java.lang.ref.PhantomReference (always) | Class:java.lang.ref.Finalizer (always) | Class:java.lang.ref.FinalizerReference (always) | Root Class:android.os.Binder (always) dump http://pan.baidu.com/s/1c0KU7y4
9e74a8529ca94287fe0c3b02b7a6b39d51ecd704
3df74c4eb81f13053dd961d534ec152f467df6c4
https://github.com/square/leakcanary/compare/9e74a8529ca94287fe0c3b02b7a6b39d51ecd704...3df74c4eb81f13053dd961d534ec152f467df6c4
diff --git a/leakcanary-analyzer/src/main/java/com/squareup/leakcanary/HahaHelper.java b/leakcanary-analyzer/src/main/java/com/squareup/leakcanary/HahaHelper.java index fbbf8ba08..fe01cd23b 100644 --- a/leakcanary-analyzer/src/main/java/com/squareup/leakcanary/HahaHelper.java +++ b/leakcanary-analyzer/src/main/java/com/squareup/leakcanary/HahaHelper.java @@ -52,6 +52,11 @@ public final class HahaHelper { static String threadName(Instance holder) { List<ClassInstance.FieldValue> values = classInstanceValues(holder); Object nameField = fieldValue(values, "name"); + if (nameField == null) { + // Sometimes we can't find the String at the expected memory address in the heap dump. + // See https://github.com/square/leakcanary/issues/417 . + return "Thread name not available"; + } return asString(nameField); }
['leakcanary-analyzer/src/main/java/com/squareup/leakcanary/HahaHelper.java']
{'.java': 1}
1
1
0
0
1
171,568
37,467
4,680
43
237
56
5
1
3,022
158
820
53
1
0
1970-01-01T00:24:19
28,557
Kotlin
{'Kotlin': 1363625, 'Java': 4762, 'Shell': 481, 'AIDL': 203}
Apache License 2.0
1,658
square/leakcanary/458/449
square
leakcanary
https://github.com/square/leakcanary/issues/449
https://github.com/square/leakcanary/pull/458
https://github.com/square/leakcanary/pull/458
1
fixes
NullPointerException in LeakCanaryInternals.isInServiceProcess()
It looks like ActivityManager.getRunningAppProcesses can return null: http://developer.android.com/reference/android/app/ActivityManager.html#getRunningAppProcesses() LeakCanaryInternals.isInServiceProcess() doesn't seem to check for this case. Stack trace excerpt: java.lang.RuntimeException: Unable to create application [...]: java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4710) at android.app.ActivityThread.-wrap1(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1405) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference at com.squareup.leakcanary.internal.LeakCanaryInternals.isInServiceProcess(LeakCanaryInternals.java:117) at com.squareup.leakcanary.LeakCanary.isInAnalyzerProcess(LeakCanary.java:237) at com.squareup.leakcanary.LeakCanary.install(LeakCanary.java:77) at com.squareup.leakcanary.LeakCanary.install(LeakCanary.java:42) [...]
462561d249bddf5a28439bc588a7cb026a8425bf
efa41ac38b4fa4d48df06d011730a7ffdc8eb0d0
https://github.com/square/leakcanary/compare/462561d249bddf5a28439bc588a7cb026a8425bf...efa41ac38b4fa4d48df06d011730a7ffdc8eb0d0
diff --git a/leakcanary-android/src/main/java/com/squareup/leakcanary/internal/LeakCanaryInternals.java b/leakcanary-android/src/main/java/com/squareup/leakcanary/internal/LeakCanaryInternals.java index b334079f4..973b1b84d 100644 --- a/leakcanary-android/src/main/java/com/squareup/leakcanary/internal/LeakCanaryInternals.java +++ b/leakcanary-android/src/main/java/com/squareup/leakcanary/internal/LeakCanaryInternals.java @@ -29,6 +29,7 @@ import android.content.pm.ServiceInfo; import com.squareup.leakcanary.CanaryLog; import com.squareup.leakcanary.R; import java.lang.reflect.Method; +import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; @@ -114,10 +115,14 @@ public final class LeakCanaryInternals { ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); ActivityManager.RunningAppProcessInfo myProcess = null; - for (ActivityManager.RunningAppProcessInfo process : activityManager.getRunningAppProcesses()) { - if (process.pid == myPid) { - myProcess = process; - break; + List<ActivityManager.RunningAppProcessInfo> runningProcesses = + activityManager.getRunningAppProcesses(); + if (runningProcesses != null) { + for (ActivityManager.RunningAppProcessInfo process : runningProcesses) { + if (process.pid == myPid) { + myProcess = process; + break; + } } } if (myProcess == null) {
['leakcanary-android/src/main/java/com/squareup/leakcanary/internal/LeakCanaryInternals.java']
{'.java': 1}
1
1
0
0
1
170,559
37,251
4,662
43
540
112
13
1
1,565
81
361
23
1
0
1970-01-01T00:24:18
28,557
Kotlin
{'Kotlin': 1363625, 'Java': 4762, 'Shell': 481, 'AIDL': 203}
Apache License 2.0
1,659
square/leakcanary/405/382
square
leakcanary
https://github.com/square/leakcanary/issues/382
https://github.com/square/leakcanary/pull/405
https://github.com/square/leakcanary/pull/405
1
fixes
Crash opening "Leaks" activity on 1.4-beta1
My test device is running Android M, and I have not had a leak to get the notification to grant storage permissions. When I run the Leaks activity, it crashes with the dump below. The activity is able to open after granting storage permission. ``` D Shutting down VM E FATAL EXCEPTION: main E Process: com.meiste.tempalarm, PID: 14231 E java.lang.RuntimeException: Unable to resume activity {com.meiste.tempalarm/com.squareup.leakcanary.internal.DisplayLeakActivity}: java.lang.Unsupport edOperationException: Could not create leak directory /storage/emulated/0/Download/leakcanary-com.meiste.tempalarm E at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3121) E at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3152) E at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2495) E at android.app.ActivityThread.-wrap11(ActivityThread.java) E at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354) E at android.os.Handler.dispatchMessage(Handler.java:102) E at android.os.Looper.loop(Looper.java:148) E at android.app.ActivityThread.main(ActivityThread.java:5443) E at java.lang.reflect.Method.invoke(Native Method) E at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) E at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) E Caused by: java.lang.UnsupportedOperationException: Could not create leak directory /storage/emulated/0/Download/leakcanary-com.meiste.tempalarm E at com.squareup.leakcanary.DefaultLeakDirectoryProvider.leakDirectory(DefaultLeakDirectoryProvider.java:45) E at com.squareup.leakcanary.internal.DisplayLeakActivity.getLeakDirectory(DisplayLeakActivity.java:94) E at com.squareup.leakcanary.internal.DisplayLeakActivity$LoadLeaks.<init>(DisplayLeakActivity.java:431) E at com.squareup.leakcanary.internal.DisplayLeakActivity$LoadLeaks.load(DisplayLeakActivity.java:413) E at com.squareup.leakcanary.internal.DisplayLeakActivity.onResume(DisplayLeakActivity.java:142) E at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1281) E at android.app.Activity.performResume(Activity.java:6320) E at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3110) E ... 10 more ```
37cb2b7f3cb05bb0ac916d1cb308f9ba2c177472
131a8ae309b8f422d54685875ee0568da50ef2dc
https://github.com/square/leakcanary/compare/37cb2b7f3cb05bb0ac916d1cb308f9ba2c177472...131a8ae309b8f422d54685875ee0568da50ef2dc
diff --git a/leakcanary-android/src/main/java/com/squareup/leakcanary/AndroidHeapDumper.java b/leakcanary-android/src/main/java/com/squareup/leakcanary/AndroidHeapDumper.java index 86a232f0a..c46435f35 100644 --- a/leakcanary-android/src/main/java/com/squareup/leakcanary/AndroidHeapDumper.java +++ b/leakcanary-android/src/main/java/com/squareup/leakcanary/AndroidHeapDumper.java @@ -47,7 +47,7 @@ public final class AndroidHeapDumper implements HeapDumper { @Override public File dumpHeap() { if (!leakDirectoryProvider.isLeakStorageWritable()) { CanaryLog.d("Could not write to leak storage to dump heap."); - leakDirectoryProvider.requestWritePermission(); + leakDirectoryProvider.requestWritePermissionNotification(); return NO_DUMP; } File heapDumpFile = getHeapDumpFile(); diff --git a/leakcanary-android/src/main/java/com/squareup/leakcanary/DefaultLeakDirectoryProvider.java b/leakcanary-android/src/main/java/com/squareup/leakcanary/DefaultLeakDirectoryProvider.java index 988906e31..812b6e647 100644 --- a/leakcanary-android/src/main/java/com/squareup/leakcanary/DefaultLeakDirectoryProvider.java +++ b/leakcanary-android/src/main/java/com/squareup/leakcanary/DefaultLeakDirectoryProvider.java @@ -16,6 +16,7 @@ package com.squareup.leakcanary; import android.annotation.TargetApi; +import android.app.Activity; import android.app.PendingIntent; import android.content.Context; import android.os.Environment; @@ -48,7 +49,7 @@ public final class DefaultLeakDirectoryProvider implements LeakDirectoryProvider return directory; } - @Override public void requestWritePermission() { + @Override public void requestWritePermissionNotification() { if (hasStoragePermission()) { return; } @@ -60,6 +61,16 @@ public final class DefaultLeakDirectoryProvider implements LeakDirectoryProvider showNotification(context, contentTitle, contentText, pendingIntent); } + @TargetApi(M) @Override public void requestPermission(Activity activity) { + if (hasStoragePermission()) { + return; + } + String[] permissions = { + WRITE_EXTERNAL_STORAGE + }; + activity.requestPermissions(permissions, 42); + } + @Override public boolean isLeakStorageWritable() { if (!hasStoragePermission()) { return false; diff --git a/leakcanary-android/src/main/java/com/squareup/leakcanary/LeakDirectoryProvider.java b/leakcanary-android/src/main/java/com/squareup/leakcanary/LeakDirectoryProvider.java index 6c8cf0568..1e7ebf87b 100644 --- a/leakcanary-android/src/main/java/com/squareup/leakcanary/LeakDirectoryProvider.java +++ b/leakcanary-android/src/main/java/com/squareup/leakcanary/LeakDirectoryProvider.java @@ -15,6 +15,7 @@ */ package com.squareup.leakcanary; +import android.app.Activity; import java.io.File; /** @@ -27,7 +28,9 @@ public interface LeakDirectoryProvider { /** Returns a path to an existing directory were leaks can be stored. */ File leakDirectory(); - void requestWritePermission(); + void requestWritePermissionNotification(); + + void requestPermission(Activity activity); /** True if we can currently write to the leak directory. */ boolean isLeakStorageWritable(); diff --git a/leakcanary-android/src/main/java/com/squareup/leakcanary/internal/DisplayLeakActivity.java b/leakcanary-android/src/main/java/com/squareup/leakcanary/internal/DisplayLeakActivity.java index 2be0290d3..e746b04c5 100644 --- a/leakcanary-android/src/main/java/com/squareup/leakcanary/internal/DisplayLeakActivity.java +++ b/leakcanary-android/src/main/java/com/squareup/leakcanary/internal/DisplayLeakActivity.java @@ -88,13 +88,12 @@ public final class DisplayLeakActivity extends Activity { DisplayLeakActivity.leakDirectoryProvider = leakDirectoryProvider; } - static File getLeakDirectory(Context context) { + private static LeakDirectoryProvider leakDirectoryProvider(Context context) { LeakDirectoryProvider leakDirectoryProvider = DisplayLeakActivity.leakDirectoryProvider; - if (leakDirectoryProvider != null) { - return leakDirectoryProvider.leakDirectory(); - } else { - return new DefaultLeakDirectoryProvider(context).leakDirectory(); + if (leakDirectoryProvider == null) { + leakDirectoryProvider = new DefaultLeakDirectoryProvider(context); } + return leakDirectoryProvider; } // null until it's been first loaded. @@ -141,7 +140,13 @@ public final class DisplayLeakActivity extends Activity { @Override protected void onResume() { super.onResume(); - LoadLeaks.load(this); + LeakDirectoryProvider leakDirectoryProvider = leakDirectoryProvider(this); + if (leakDirectoryProvider.isLeakStorageWritable()) { + File leakDirectory = leakDirectoryProvider.leakDirectory(); + LoadLeaks.load(this, leakDirectory); + } else { + leakDirectoryProvider.requestPermission(this); + } } @Override public void setTheme(int resid) { @@ -237,7 +242,7 @@ public final class DisplayLeakActivity extends Activity { } void deleteAllLeaks() { - File leakDirectory = getLeakDirectory(DisplayLeakActivity.this); + File leakDirectory = leakDirectoryProvider(DisplayLeakActivity.this).leakDirectory(); File[] files = leakDirectory.listFiles(); if (files != null) { for (File file : files) { @@ -428,8 +433,8 @@ public final class DisplayLeakActivity extends Activity { static final Executor backgroundExecutor = newSingleThreadExecutor("LoadLeaks"); - static void load(DisplayLeakActivity activity) { - LoadLeaks loadLeaks = new LoadLeaks(activity); + static void load(DisplayLeakActivity activity, File leakDirectory) { + LoadLeaks loadLeaks = new LoadLeaks(activity, leakDirectory); inFlight.add(loadLeaks); backgroundExecutor.execute(loadLeaks); } @@ -445,9 +450,9 @@ public final class DisplayLeakActivity extends Activity { private final File leakDirectory; private final Handler mainHandler; - LoadLeaks(DisplayLeakActivity activity) { + LoadLeaks(DisplayLeakActivity activity, File leakDirectory) { this.activityOrNull = activity; - leakDirectory = getLeakDirectory(activity); + this.leakDirectory = leakDirectory; mainHandler = new Handler(Looper.getMainLooper()); }
['leakcanary-android/src/main/java/com/squareup/leakcanary/internal/DisplayLeakActivity.java', 'leakcanary-android/src/main/java/com/squareup/leakcanary/AndroidHeapDumper.java', 'leakcanary-android/src/main/java/com/squareup/leakcanary/DefaultLeakDirectoryProvider.java', 'leakcanary-android/src/main/java/com/squareup/leakcanary/LeakDirectoryProvider.java']
{'.java': 4}
4
4
0
0
4
172,324
37,637
4,696
43
2,121
409
47
4
2,380
146
552
31
0
1
1970-01-01T00:24:13
28,557
Kotlin
{'Kotlin': 1363625, 'Java': 4762, 'Shell': 481, 'AIDL': 203}
Apache License 2.0
1,326
alibaba/nacos/3816/3787
alibaba
nacos
https://github.com/alibaba/nacos/issues/3787
https://github.com/alibaba/nacos/pull/3816
https://github.com/alibaba/nacos/pull/3816
1
fixes
client error: invalid param. For input string: "${nacos.config.maxRetry${nacos.maxRetry:}}"
<!-- Here is for bug reports and feature requests ONLY! If you're looking for help, please check our mail list、WeChat group and the Gitter room. Please try to use English to describe your issue, or at least provide a snippet of English translation. 我们鼓励使用英文,如果不能直接使用,可以使用翻译软件,您仍旧可以保留中文原文。 --> **Describe the bug** 在1.3.1和1.3.2的版本中,若没有明确指定 nacos.config.max-retry 的值,启动springboot程序,将会报如标题所示错误。 **Expected behavior** 预期程序正常启动,该值采用默认值3 **Acutally behavior** 实际上会报如标题所示错误。 **How to Reproduce** Steps to reproduce the behavior: 调试发现,在1.3.0版本中,采用的是org.apache.commons.lang3.math.NumberUtils.toInt(String str, int defaultValue)方法。 而报错的版本采用的是com.alibaba.nacos.common.utils.ConvertUtils.toInt(String val, int defaultValue)方法。 理论上报错版本的方法也没问题,但是不知道为什么在默认情况下传进来的val的值是${nacos.config.maxRetry${nacos.maxRetry:}},导致程序出错。 **Desktop (please complete the following information):** - OS: [e.g. Centos] - Version [e.g. nacos-server 1.3.2, nacos-client 1.3.2] - Module [e.g. naming/config] - SDK [e.g. original, spring-cloud-alibaba-nacos, dubbo] **Additional context** Add any other context about the problem here.
a41d209d570ccf5deed6c6c608861b1638ded2f5
af2151e49c359b3fc7c9dd27ac9adbfb71d1ccec
https://github.com/alibaba/nacos/compare/a41d209d570ccf5deed6c6c608861b1638ded2f5...af2151e49c359b3fc7c9dd27ac9adbfb71d1ccec
diff --git a/common/src/main/java/com/alibaba/nacos/common/utils/ConvertUtils.java b/common/src/main/java/com/alibaba/nacos/common/utils/ConvertUtils.java index 628d79bc3..50670e411 100644 --- a/common/src/main/java/com/alibaba/nacos/common/utils/ConvertUtils.java +++ b/common/src/main/java/com/alibaba/nacos/common/utils/ConvertUtils.java @@ -51,7 +51,11 @@ public final class ConvertUtils { if (StringUtils.isBlank(val)) { return defaultValue; } - return Integer.parseInt(val); + try { + return Integer.parseInt(val); + } catch (NumberFormatException exception) { + return defaultValue; + } } /** @@ -77,7 +81,11 @@ public final class ConvertUtils { if (StringUtils.isBlank(val)) { return defaultValue; } - return Long.parseLong(val); + try { + return Long.parseLong(val); + } catch (NumberFormatException exception) { + return defaultValue; + } } /** @@ -92,7 +100,11 @@ public final class ConvertUtils { if (StringUtils.isBlank(val)) { return defaultValue; } - return Boolean.parseBoolean(val); + try { + return Boolean.parseBoolean(val); + } catch (NumberFormatException exception) { + return defaultValue; + } } // The following utility functions are extracted from <link>org.apache.commons.lang3</link>
['common/src/main/java/com/alibaba/nacos/common/utils/ConvertUtils.java']
{'.java': 1}
1
1
0
0
1
4,516,790
951,997
127,142
745
588
89
18
1
1,138
111
406
32
0
0
1970-01-01T00:26:40
27,123
Java
{'Java': 10177611, 'SCSS': 80453, 'JavaScript': 7472, 'Shell': 6561, 'TypeScript': 4774, 'Batchfile': 4434, 'EJS': 2645}
Apache License 2.0
987
alibaba/spring-cloud-alibaba/20/19
alibaba
spring-cloud-alibaba
https://github.com/alibaba/spring-cloud-alibaba/issues/19
https://github.com/alibaba/spring-cloud-alibaba/pull/20
https://github.com/alibaba/spring-cloud-alibaba/pull/20
1
fixes
Get wrong instance list at first time
How to reproduce this issue, refer to followings: I have registered 2 instances (ex service name are all 'a') to nacos server Then I stop them After a while, I do step 1 again Then I get 2 instances from interface, for first time, it returns 1 instance or 0 instance. But I invoke again, it is fine to return 2 instances. Guess the cache issue?
625e85b0401f5837b48697667ea10e62fe7e3855
1b733af0d515895f1d122bb0f67a6ab9c5d63121
https://github.com/alibaba/spring-cloud-alibaba/compare/625e85b0401f5837b48697667ea10e62fe7e3855...1b733af0d515895f1d122bb0f67a6ab9c5d63121
diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java index f766945f..0d4fdbb8 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java @@ -44,8 +44,17 @@ public class NacosServerList extends AbstractServerList<NacosServer> { @Override public List<NacosServer> getInitialListOfServers() { + return getServers(); + } + + @Override + public List<NacosServer> getUpdatedListOfServers() { + return getServers(); + } + + private List<NacosServer> getServers() { try { - List<Instance> instances = registration.getNacosNamingService().selectInstances(serviceId,true); + List<Instance> instances = registration.getNacosNamingService().selectInstances(serviceId, true); return instancesToServerList(instances); } catch (Exception e) { @@ -53,11 +62,6 @@ public class NacosServerList extends AbstractServerList<NacosServer> { } } - @Override - public List<NacosServer> getUpdatedListOfServers() { - return getInitialListOfServers(); - } - private List<NacosServer> instancesToServerList(List<Instance> instances) { List<NacosServer> result = new ArrayList<>(instances.size()); for (Instance instance : instances) {
['spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java']
{'.java': 1}
1
1
0
0
1
165,386
34,376
5,506
73
482
104
16
1
366
66
93
6
0
0
1970-01-01T00:25:37
26,133
Java
{'Java': 1218311, 'HTML': 9491, 'Shell': 2729, 'Dockerfile': 1686, 'JavaScript': 860}
Apache License 2.0
986
alibaba/spring-cloud-alibaba/21/19
alibaba
spring-cloud-alibaba
https://github.com/alibaba/spring-cloud-alibaba/issues/19
https://github.com/alibaba/spring-cloud-alibaba/pull/21
https://github.com/alibaba/spring-cloud-alibaba/pull/21
1
fixes
Get wrong instance list at first time
How to reproduce this issue, refer to followings: I have registered 2 instances (ex service name are all 'a') to nacos server Then I stop them After a while, I do step 1 again Then I get 2 instances from interface, for first time, it returns 1 instance or 0 instance. But I invoke again, it is fine to return 2 instances. Guess the cache issue?
8e89f6d15a89da422336b9a37d3c65985e6c15bc
541eaee0b8492f96fd488d862de10b65aa608a8c
https://github.com/alibaba/spring-cloud-alibaba/compare/8e89f6d15a89da422336b9a37d3c65985e6c15bc...541eaee0b8492f96fd488d862de10b65aa608a8c
diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java index f766945f..0d4fdbb8 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java @@ -44,8 +44,17 @@ public class NacosServerList extends AbstractServerList<NacosServer> { @Override public List<NacosServer> getInitialListOfServers() { + return getServers(); + } + + @Override + public List<NacosServer> getUpdatedListOfServers() { + return getServers(); + } + + private List<NacosServer> getServers() { try { - List<Instance> instances = registration.getNacosNamingService().selectInstances(serviceId,true); + List<Instance> instances = registration.getNacosNamingService().selectInstances(serviceId, true); return instancesToServerList(instances); } catch (Exception e) { @@ -53,11 +62,6 @@ public class NacosServerList extends AbstractServerList<NacosServer> { } } - @Override - public List<NacosServer> getUpdatedListOfServers() { - return getInitialListOfServers(); - } - private List<NacosServer> instancesToServerList(List<Instance> instances) { List<NacosServer> result = new ArrayList<>(instances.size()); for (Instance instance : instances) {
['spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java']
{'.java': 1}
1
1
0
0
1
172,726
34,556
5,555
73
482
104
16
1
366
66
93
6
0
0
1970-01-01T00:25:37
26,133
Java
{'Java': 1218311, 'HTML': 9491, 'Shell': 2729, 'Dockerfile': 1686, 'JavaScript': 860}
Apache License 2.0
985
alibaba/spring-cloud-alibaba/46/42
alibaba
spring-cloud-alibaba
https://github.com/alibaba/spring-cloud-alibaba/issues/42
https://github.com/alibaba/spring-cloud-alibaba/pull/46
https://github.com/alibaba/spring-cloud-alibaba/pull/46
1
fixes
Setting false on autoRegister of @EnableDiscoveryClient will throw exception and application failed to start
Description: Field nacosRegistration in org.springframework.cloud.alibaba.nacos.NacosDiscoveryClient required a bean of type 'org.springframework.cloud.alibaba.nacos.registry.NacosRegistration' that could not be found. - Bean method 'nacosRegistration' not loaded because @ConditionalOnProperty (spring.cloud.service-registry.auto-registration.enabled) found different value in property 'spring.cloud.service-registry.auto-registration.enabled'
0f444a40abbe830b108478e9e18f9a74d845f862
27ddaa68a81214832a0351db439eabbef9aed7ec
https://github.com/alibaba/spring-cloud-alibaba/compare/0f444a40abbe830b108478e9e18f9a74d845f862...27ddaa68a81214832a0351db439eabbef9aed7ec
diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfiguration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfiguration.java index 78c7ddcc..6e087422 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfiguration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfiguration.java @@ -16,7 +16,6 @@ package org.springframework.cloud.alibaba.nacos; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -48,12 +47,6 @@ public class NacosDiscoveryAutoConfiguration { return new NacosServiceRegistry(); } - @Bean - @ConditionalOnMissingBean - public NacosDiscoveryProperties nacosProperties() { - return new NacosDiscoveryProperties(); - } - @Bean @ConditionalOnBean(AutoServiceRegistrationProperties.class) public NacosRegistration nacosRegistration() { diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClient.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClient.java index f9acd947..bab4b1a2 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClient.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClient.java @@ -19,13 +19,15 @@ package org.springframework.cloud.alibaba.nacos; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cloud.alibaba.nacos.registry.NacosRegistration; +import org.springframework.cloud.client.DefaultServiceInstance; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.core.env.Environment; -import java.net.URI; import java.util.*; +import javax.annotation.PostConstruct; + import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; @@ -40,52 +42,37 @@ public class NacosDiscoveryClient implements DiscoveryClient { public static final String DESCRIPTION = "Spring Cloud Nacos Discovery Client"; @Autowired - private NacosRegistration nacosRegistration; + private NacosDiscoveryProperties discoveryProperties; + + @Autowired + private Environment environment; + + private NamingService namingService; @Override public String description() { return DESCRIPTION; } + @PostConstruct + public void init() { + discoveryProperties.overrideFromEnv(environment); + namingService = discoveryProperties.getNamingService(); + } + @Override public ServiceInstance getLocalServiceInstance() { - return new ServiceInstance() { - @Override - public String getServiceId() { - return nacosRegistration.getServiceId(); - } - - @Override - public String getHost() { - return nacosRegistration.getHost(); - } - - @Override - public int getPort() { - return nacosRegistration.getPort(); - } - - @Override - public boolean isSecure() { - return nacosRegistration.isSecure(); - } - - @Override - public URI getUri() { - return nacosRegistration.getUri(); - } - - @Override - public Map<String, String> getMetadata() { - return nacosRegistration.getMetadata(); - } - }; + String serviceId = discoveryProperties.getService(); + String host = discoveryProperties.getIp(); + int port = discoveryProperties.getPort(); + boolean secure = discoveryProperties.isSecure(); + Map<String, String> metadata = discoveryProperties.getMetadata(); + return new DefaultServiceInstance(serviceId, host, port, secure, metadata); } @Override public List<ServiceInstance> getInstances(String serviceId) { try { - NamingService namingService = nacosRegistration.getNacosNamingService(); List<Instance> instances = namingService.getAllInstances(serviceId); return hostToServiceInstanceList(instances, serviceId); } @@ -126,7 +113,6 @@ public class NacosDiscoveryClient implements DiscoveryClient { public List<String> getServices() { try { - NamingService namingService = nacosRegistration.getNacosNamingService(); ListView<String> services = namingService.getServicesOfServer(1, Integer.MAX_VALUE); return services.getData(); @@ -137,4 +123,7 @@ public class NacosDiscoveryClient implements DiscoveryClient { } } + public NamingService getNamingService() { + return namingService; + } } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClientAutoConfiguration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClientAutoConfiguration.java index 2563cbe6..05049f4b 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClientAutoConfiguration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClientAutoConfiguration.java @@ -36,4 +36,10 @@ public class NacosDiscoveryClientAutoConfiguration { return new NacosDiscoveryClient(); } + @Bean + @ConditionalOnMissingBean + public NacosDiscoveryProperties nacosProperties() { + return new NacosDiscoveryProperties(); + } + } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryProperties.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryProperties.java index 43b6a5c7..aa9271a8 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryProperties.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryProperties.java @@ -16,6 +16,8 @@ package org.springframework.cloud.alibaba.nacos; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -33,6 +35,18 @@ import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Objects; +import java.util.Properties; + +import com.alibaba.nacos.api.NacosFactory; +import com.alibaba.nacos.api.naming.NamingService; +import com.alibaba.nacos.client.naming.utils.UtilAndComs; + +import static com.alibaba.nacos.api.PropertyKeyConst.ACCESS_KEY; +import static com.alibaba.nacos.api.PropertyKeyConst.CLUSTER_NAME; +import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT; +import static com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE; +import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY; +import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; /** * @author dungu.zpf @@ -42,6 +56,9 @@ import java.util.Objects; @ConfigurationProperties("spring.cloud.nacos.discovery") public class NacosDiscoveryProperties { + private static final Logger LOGGER = LoggerFactory + .getLogger(NacosDiscoveryProperties.class); + /** * nacos discovery server address */ @@ -333,4 +350,22 @@ public class NacosDiscoveryProperties { } } + public NamingService getNamingService() { + Properties properties = new Properties(); + properties.put(SERVER_ADDR, serverAddr); + properties.put(NAMESPACE, namespace); + properties.put(UtilAndComs.NACOS_NAMING_LOG_NAME, logName); + properties.put(ENDPOINT, endpoint); + properties.put(ACCESS_KEY, accessKey); + properties.put(SECRET_KEY, secretKey); + properties.put(CLUSTER_NAME, clusterName); + try { + return NacosFactory.createNamingService(properties); + } + catch (Exception e) { + LOGGER.error("create naming service error!properties={},e=,", this, e); + return null; + } + } + } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpoint.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpoint.java index a68f6300..dfa1fbb6 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpoint.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpoint.java @@ -28,8 +28,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.AbstractEndpoint; +import org.springframework.cloud.alibaba.nacos.NacosDiscoveryClient; import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; -import org.springframework.cloud.alibaba.nacos.registry.NacosRegistration; /** * Endpoint for nacos discovery, get nacos properties and subscribed services @@ -44,7 +44,7 @@ public class NacosDiscoveryEndpoint extends AbstractEndpoint<Map<String, Object> private NacosDiscoveryProperties nacosDiscoveryProperties; @Autowired - private NacosRegistration nacosRegistration; + private NacosDiscoveryClient discoveryClient; public NacosDiscoveryEndpoint() { super("nacos_discovery", false); @@ -58,7 +58,7 @@ public class NacosDiscoveryEndpoint extends AbstractEndpoint<Map<String, Object> Map<String, Object> result = new HashMap<>(); result.put("NacosDiscoveryProperties", nacosDiscoveryProperties); - NamingService namingService = nacosRegistration.getNacosNamingService(); + NamingService namingService = discoveryClient.getNamingService(); List<ServiceInfo> subscribe = Collections.emptyList(); try { diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java index 5278cd3b..eab95411 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java @@ -26,7 +26,6 @@ import org.springframework.context.annotation.Configuration; * @author xiaojing */ @Configuration -@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) @ConditionalOnClass(name = "org.springframework.boot.actuate.endpoint.AbstractEndpoint") public class NacosDiscoveryEndpointAutoConfiguration { diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosRegistration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosRegistration.java index 1fc12d7f..872d7dd8 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosRegistration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosRegistration.java @@ -28,15 +28,10 @@ import org.springframework.util.StringUtils; import java.net.URI; import java.util.Map; -import java.util.Properties; import javax.annotation.PostConstruct; -import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.naming.NamingService; -import com.alibaba.nacos.client.naming.utils.UtilAndComs; - -import static com.alibaba.nacos.api.PropertyKeyConst.*; /** * @author xiaojing @@ -60,22 +55,7 @@ public class NacosRegistration implements Registration, ServiceInstance { Environment env = context.getEnvironment(); nacosDiscoveryProperties.overrideFromEnv(context.getEnvironment()); - - Properties properties = new Properties(); - properties.put(SERVER_ADDR, nacosDiscoveryProperties.getServerAddr()); - properties.put(NAMESPACE, nacosDiscoveryProperties.getNamespace()); - properties.put(UtilAndComs.NACOS_NAMING_LOG_NAME, - nacosDiscoveryProperties.getLogName()); - properties.put(ENDPOINT, nacosDiscoveryProperties.getEndpoint()); - properties.put(ACCESS_KEY, nacosDiscoveryProperties.getAccessKey()); - properties.put(SECRET_KEY, nacosDiscoveryProperties.getSecretKey()); - properties.put(CLUSTER_NAME, nacosDiscoveryProperties.getClusterName()); - try { - nacosNamingService = NacosFactory.createNamingService(properties); - } - catch (Exception e) { - - } + nacosNamingService = nacosDiscoveryProperties.getNamingService(); Integer managementPort = ManagementServerPortUtils.getPort(context); if (null != managementPort) { diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java index 3eb43bbc..c85339c3 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java @@ -19,7 +19,9 @@ package org.springframework.cloud.alibaba.nacos.ribbon; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.AbstractServerList; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.alibaba.nacos.NacosDiscoveryClient; import org.springframework.cloud.alibaba.nacos.registry.NacosRegistration; +import org.springframework.cloud.client.discovery.DiscoveryClient; import java.util.ArrayList; import java.util.List; @@ -32,7 +34,7 @@ import com.alibaba.nacos.api.naming.pojo.Instance; public class NacosServerList extends AbstractServerList<NacosServer> { @Autowired - private NacosRegistration registration; + private NacosDiscoveryClient discoveryClient; private String serviceId; @@ -55,7 +57,7 @@ public class NacosServerList extends AbstractServerList<NacosServer> { private List<NacosServer> getServers() { try { - List<Instance> instances = registration.getNacosNamingService() + List<Instance> instances = discoveryClient.getNamingService() .getAllInstances(serviceId); return instancesToServerList(instances); } diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfigurationTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfigurationTests.java index 1fe9fdaa..4be0dd92 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfigurationTests.java +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfigurationTests.java @@ -42,6 +42,7 @@ public class NacosDiscoveryAutoConfigurationTests { @Before public void setUp() throws Exception { this.context = new SpringApplicationBuilder(NacosDiscoveryTestConfiguration.class, + NacosDiscoveryClientAutoConfiguration.class, NacosDiscoveryAutoConfiguration.class).web(false).run( "--spring.cloud.nacos.discovery.server-addr=127.0.0.1:8080", "--spring.cloud.nacos.discovery.port=18080", diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosRibbonClientConfigurationTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosRibbonClientConfigurationTests.java index f0354b34..c0f808d9 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosRibbonClientConfigurationTests.java +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosRibbonClientConfigurationTests.java @@ -9,6 +9,7 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.alibaba.nacos.NacosDiscoveryAutoConfiguration; +import org.springframework.cloud.alibaba.nacos.NacosDiscoveryClientAutoConfiguration; import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; @@ -33,6 +34,7 @@ public class NacosRibbonClientConfigurationTests { public void setUp() throws Exception { this.context = new SpringApplicationBuilder(NacosRibbonTestConfiguration.class, NacosDiscoveryAutoConfiguration.class, + NacosDiscoveryClientAutoConfiguration.class, NacosRibbonClientConfiguration.class, RibbonNacosAutoConfiguration.class) .web(false).run("--server.port=18080", "--spring.cloud.nacos.discovery.server-addr=127.0.0.1:8080",
['spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosRibbonClientConfigurationTests.java', 'spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfigurationTests.java', 'spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfiguration.java', 'spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java', 'spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClient.java', 'spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClientAutoConfiguration.java', 'spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpoint.java', 'spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosRegistration.java', 'spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java', 'spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryProperties.java']
{'.java': 10}
10
10
0
0
10
178,400
36,270
5,846
73
5,326
1,079
144
8
449
31
81
4
0
0
1970-01-01T00:25:39
26,133
Java
{'Java': 1218311, 'HTML': 9491, 'Shell': 2729, 'Dockerfile': 1686, 'JavaScript': 860}
Apache License 2.0
984
alibaba/spring-cloud-alibaba/47/42
alibaba
spring-cloud-alibaba
https://github.com/alibaba/spring-cloud-alibaba/issues/42
https://github.com/alibaba/spring-cloud-alibaba/pull/47
https://github.com/alibaba/spring-cloud-alibaba/pull/47
1
fixes
Setting false on autoRegister of @EnableDiscoveryClient will throw exception and application failed to start
Description: Field nacosRegistration in org.springframework.cloud.alibaba.nacos.NacosDiscoveryClient required a bean of type 'org.springframework.cloud.alibaba.nacos.registry.NacosRegistration' that could not be found. - Bean method 'nacosRegistration' not loaded because @ConditionalOnProperty (spring.cloud.service-registry.auto-registration.enabled) found different value in property 'spring.cloud.service-registry.auto-registration.enabled'
1ce28f00f3255aba56662e2ab75e3e70d679b522
47cab99b2c767e4ce3ff8c0c73a7021ac4fa3f78
https://github.com/alibaba/spring-cloud-alibaba/compare/1ce28f00f3255aba56662e2ab75e3e70d679b522...47cab99b2c767e4ce3ff8c0c73a7021ac4fa3f78
diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfiguration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfiguration.java index b6180144..21a8d303 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfiguration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfiguration.java @@ -48,12 +48,6 @@ public class NacosDiscoveryAutoConfiguration { return new NacosServiceRegistry(); } - @Bean - @ConditionalOnMissingBean - public NacosDiscoveryProperties nacosProperties() { - return new NacosDiscoveryProperties(); - } - @Bean @ConditionalOnBean(AutoServiceRegistrationProperties.class) public NacosRegistration nacosRegistration() { diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClient.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClient.java index d32a6b0d..59ea1ec7 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClient.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClient.java @@ -19,12 +19,15 @@ package org.springframework.cloud.alibaba.nacos; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cloud.alibaba.nacos.registry.NacosRegistration; +import org.springframework.cloud.client.DefaultServiceInstance; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.core.env.Environment; import java.util.*; +import javax.annotation.PostConstruct; + import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; @@ -39,7 +42,18 @@ public class NacosDiscoveryClient implements DiscoveryClient { public static final String DESCRIPTION = "Spring Cloud Nacos Discovery Client"; @Autowired - private NacosRegistration nacosRegistration; + private NacosDiscoveryProperties discoveryProperties; + + @Autowired + private Environment environment; + + private NamingService namingService; + + @PostConstruct + public void init() { + discoveryProperties.overrideFromEnv(environment); + namingService = discoveryProperties.getNamingService(); + } @Override public String description() { @@ -49,7 +63,6 @@ public class NacosDiscoveryClient implements DiscoveryClient { @Override public List<ServiceInstance> getInstances(String serviceId) { try { - NamingService namingService = nacosRegistration.getNacosNamingService(); List<Instance> instances = namingService.getAllInstances(serviceId); return hostToServiceInstanceList(instances, serviceId); } @@ -79,7 +92,7 @@ public class NacosDiscoveryClient implements DiscoveryClient { List<Instance> instances, String serviceId) { List<ServiceInstance> result = new ArrayList<ServiceInstance>(instances.size()); for (Instance instance : instances) { - if(instance.isHealthy()) { + if (instance.isHealthy()) { result.add(hostToServiceInstance(instance, serviceId)); } } @@ -90,7 +103,6 @@ public class NacosDiscoveryClient implements DiscoveryClient { public List<String> getServices() { try { - NamingService namingService = nacosRegistration.getNacosNamingService(); ListView<String> services = namingService.getServicesOfServer(1, Integer.MAX_VALUE); return services.getData(); @@ -101,4 +113,7 @@ public class NacosDiscoveryClient implements DiscoveryClient { } } + public NamingService getNamingService() { + return namingService; + } } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClientAutoConfiguration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClientAutoConfiguration.java index 2563cbe6..05049f4b 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClientAutoConfiguration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClientAutoConfiguration.java @@ -36,4 +36,10 @@ public class NacosDiscoveryClientAutoConfiguration { return new NacosDiscoveryClient(); } + @Bean + @ConditionalOnMissingBean + public NacosDiscoveryProperties nacosProperties() { + return new NacosDiscoveryProperties(); + } + } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryProperties.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryProperties.java index 43b6a5c7..aa9271a8 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryProperties.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryProperties.java @@ -16,6 +16,8 @@ package org.springframework.cloud.alibaba.nacos; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -33,6 +35,18 @@ import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Objects; +import java.util.Properties; + +import com.alibaba.nacos.api.NacosFactory; +import com.alibaba.nacos.api.naming.NamingService; +import com.alibaba.nacos.client.naming.utils.UtilAndComs; + +import static com.alibaba.nacos.api.PropertyKeyConst.ACCESS_KEY; +import static com.alibaba.nacos.api.PropertyKeyConst.CLUSTER_NAME; +import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT; +import static com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE; +import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY; +import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; /** * @author dungu.zpf @@ -42,6 +56,9 @@ import java.util.Objects; @ConfigurationProperties("spring.cloud.nacos.discovery") public class NacosDiscoveryProperties { + private static final Logger LOGGER = LoggerFactory + .getLogger(NacosDiscoveryProperties.class); + /** * nacos discovery server address */ @@ -333,4 +350,22 @@ public class NacosDiscoveryProperties { } } + public NamingService getNamingService() { + Properties properties = new Properties(); + properties.put(SERVER_ADDR, serverAddr); + properties.put(NAMESPACE, namespace); + properties.put(UtilAndComs.NACOS_NAMING_LOG_NAME, logName); + properties.put(ENDPOINT, endpoint); + properties.put(ACCESS_KEY, accessKey); + properties.put(SECRET_KEY, secretKey); + properties.put(CLUSTER_NAME, clusterName); + try { + return NacosFactory.createNamingService(properties); + } + catch (Exception e) { + LOGGER.error("create naming service error!properties={},e=,", this, e); + return null; + } + } + } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpoint.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpoint.java index da49d6c2..db384df5 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpoint.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpoint.java @@ -29,8 +29,8 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; +import org.springframework.cloud.alibaba.nacos.NacosDiscoveryClient; import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties; -import org.springframework.cloud.alibaba.nacos.registry.NacosRegistration; /** * Endpoint for nacos discovery, get nacos properties and subscribed services @@ -46,7 +46,7 @@ public class NacosDiscoveryEndpoint { private NacosDiscoveryProperties nacosDiscoveryProperties; @Autowired - private NacosRegistration nacosRegistration; + private NacosDiscoveryClient discoveryClient; /** * @return nacos discovery endpoint @@ -56,7 +56,7 @@ public class NacosDiscoveryEndpoint { Map<String, Object> result = new HashMap<>(); result.put("NacosDiscoveryProperties", nacosDiscoveryProperties); - NamingService namingService = nacosRegistration.getNacosNamingService(); + NamingService namingService = discoveryClient.getNamingService(); List<ServiceInfo> subscribe = Collections.emptyList(); try { diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java index 2b6c4635..c8716ad4 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java @@ -28,7 +28,6 @@ import org.springframework.context.annotation.Configuration; * @author xiaojing */ @Configuration -@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) @ConditionalOnClass(Endpoint.class) public class NacosDiscoveryEndpointAutoConfiguration { diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosRegistration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosRegistration.java index 4d923fac..639dad98 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosRegistration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosRegistration.java @@ -28,15 +28,10 @@ import org.springframework.util.StringUtils; import java.net.URI; import java.util.Map; -import java.util.Properties; import javax.annotation.PostConstruct; -import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.naming.NamingService; -import com.alibaba.nacos.client.naming.utils.UtilAndComs; - -import static com.alibaba.nacos.api.PropertyKeyConst.*; /** * @author xiaojing @@ -60,22 +55,7 @@ public class NacosRegistration implements Registration, ServiceInstance { Environment env = context.getEnvironment(); nacosDiscoveryProperties.overrideFromEnv(context.getEnvironment()); - - Properties properties = new Properties(); - properties.put(SERVER_ADDR, nacosDiscoveryProperties.getServerAddr()); - properties.put(NAMESPACE, nacosDiscoveryProperties.getNamespace()); - properties.put(UtilAndComs.NACOS_NAMING_LOG_NAME, - nacosDiscoveryProperties.getLogName()); - properties.put(ENDPOINT, nacosDiscoveryProperties.getEndpoint()); - properties.put(ACCESS_KEY, nacosDiscoveryProperties.getAccessKey()); - properties.put(SECRET_KEY, nacosDiscoveryProperties.getSecretKey()); - properties.put(CLUSTER_NAME, nacosDiscoveryProperties.getClusterName()); - try { - nacosNamingService = NacosFactory.createNamingService(properties); - } - catch (Exception e) { - - } + nacosNamingService = nacosDiscoveryProperties.getNamingService(); Integer managementPort = ManagementServerPortUtils.getPort(context); if (null != managementPort) { diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java index 3eb43bbc..26145662 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java @@ -19,7 +19,7 @@ package org.springframework.cloud.alibaba.nacos.ribbon; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.AbstractServerList; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cloud.alibaba.nacos.registry.NacosRegistration; +import org.springframework.cloud.alibaba.nacos.NacosDiscoveryClient; import java.util.ArrayList; import java.util.List; @@ -32,7 +32,7 @@ import com.alibaba.nacos.api.naming.pojo.Instance; public class NacosServerList extends AbstractServerList<NacosServer> { @Autowired - private NacosRegistration registration; + private NacosDiscoveryClient discoveryClient; private String serviceId; @@ -55,7 +55,7 @@ public class NacosServerList extends AbstractServerList<NacosServer> { private List<NacosServer> getServers() { try { - List<Instance> instances = registration.getNacosNamingService() + List<Instance> instances = discoveryClient.getNamingService() .getAllInstances(serviceId); return instancesToServerList(instances); } diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfigurationTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfigurationTests.java index b7e5d801..3d15a8fc 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfigurationTests.java +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfigurationTests.java @@ -37,7 +37,8 @@ public class NacosDiscoveryAutoConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration( AutoConfigurations.of(NacosDiscoveryTestConfiguration.class, - NacosDiscoveryAutoConfiguration.class)) + NacosDiscoveryAutoConfiguration.class, + NacosDiscoveryClientAutoConfiguration.class)) .withPropertyValues("spring.cloud.nacos.discovery.server-addr=127.0.0.1:8080") .withPropertyValues("spring.cloud.nacos.discovery.port=18080") .withPropertyValues("spring.cloud.nacos.discovery.service=myapp"); diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosRibbonClientConfigurationTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosRibbonClientConfigurationTests.java index 8c6da429..ad5da1b2 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosRibbonClientConfigurationTests.java +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosRibbonClientConfigurationTests.java @@ -6,6 +6,7 @@ import org.junit.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; +import org.springframework.cloud.alibaba.nacos.NacosDiscoveryClientAutoConfiguration; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; @@ -19,49 +20,43 @@ import static org.assertj.core.api.Assertions.assertThat; */ public class NacosRibbonClientConfigurationTests { - - private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(NacosRibbonTestConfiguration.class, - NacosRibbonClientConfiguration.class, - RibbonNacosAutoConfiguration.class)) - .withPropertyValues("spring.cloud.nacos.discovery.server-addr=127.0.0.1:8080") - .withPropertyValues("spring.cloud.nacos.discovery.port=18080") - .withPropertyValues("spring.cloud.nacos.discovery.service=myapp"); - - - - @Test - public void testProperties() { - - this.contextRunner.run(context -> { - NacosServerList serverList = context.getBean(NacosServerList.class); - assertThat(serverList.getServiceId()).isEqualTo("myapp"); - }); - } - - - @Configuration - @EnableAutoConfiguration - @EnableDiscoveryClient - static class NacosRibbonTestConfiguration { - - - @Bean - IClientConfig iClientConfig(){ - //return new IClientConfig.Builder().s.build(); - DefaultClientConfigImpl config = new DefaultClientConfigImpl(); - config.setClientName("myapp"); - return config; - } - - - @Bean - @LoadBalanced - RestTemplate restTemplate(){ - return new RestTemplate(); - } - - } + private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(NacosRibbonTestConfiguration.class, + NacosRibbonClientConfiguration.class, + NacosDiscoveryClientAutoConfiguration.class, + RibbonNacosAutoConfiguration.class)) + .withPropertyValues("spring.cloud.nacos.discovery.server-addr=127.0.0.1:8080") + .withPropertyValues("spring.cloud.nacos.discovery.port=18080") + .withPropertyValues("spring.cloud.nacos.discovery.service=myapp"); + + @Test + public void testProperties() { + + this.contextRunner.run(context -> { + NacosServerList serverList = context.getBean(NacosServerList.class); + assertThat(serverList.getServiceId()).isEqualTo("myapp"); + }); + } + + @Configuration + @EnableAutoConfiguration + @EnableDiscoveryClient + static class NacosRibbonTestConfiguration { + + @Bean + IClientConfig iClientConfig() { + // return new IClientConfig.Builder().s.build(); + DefaultClientConfigImpl config = new DefaultClientConfigImpl(); + config.setClientName("myapp"); + return config; + } + + @Bean + @LoadBalanced + RestTemplate restTemplate() { + return new RestTemplate(); + } + + } }
['spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosRibbonClientConfigurationTests.java', 'spring-cloud-alibaba-nacos-discovery/src/test/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfigurationTests.java', 'spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryAutoConfiguration.java', 'spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/ribbon/NacosServerList.java', 'spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClient.java', 'spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryClientAutoConfiguration.java', 'spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpoint.java', 'spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/registry/NacosRegistration.java', 'spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java', 'spring-cloud-alibaba-nacos-discovery/src/main/java/org/springframework/cloud/alibaba/nacos/NacosDiscoveryProperties.java']
{'.java': 10}
10
10
0
0
10
174,914
36,444
5,827
73
4,323
869
107
8
449
31
81
4
0
0
1970-01-01T00:25:39
26,133
Java
{'Java': 1218311, 'HTML': 9491, 'Shell': 2729, 'Dockerfile': 1686, 'JavaScript': 860}
Apache License 2.0
1,205
seata/seata/104/101
seata
seata
https://github.com/seata/seata/issues/101
https://github.com/seata/seata/pull/104
https://github.com/seata/seata/pull/104
1
fixed
Instance will cause RMClientAT.init to execute twice
Once in the main method // 一次是main 方法里面 > String applicationId = "dubbo-demo-account-service"; > String txServiceGroup = "my_test_tx_group"; > RMClientAT.init(applicationId, txServiceGroup); Once is the xml inside GlobalTransactionScanner // 一次是xml 里面GlobalTransactionScanner > if ((AT_MODE & mode) > 0) { RMClientAT.init(applicationId, txServiceGroup); Will cause the AsyncWorker.init() method timerExecutor to be created 2 times and call the doBranchCommits() method. // 会造成AsyncWorker.init()方法timerExecutor 创建2次,并调用doBranchCommits()方法 The author intended that the RMClient could be created by code or xml's GlobalTransactionScanner method, but the document did not specify the information. // 作者本意是可以通过代码或者xml 的GlobalTransactionScanner方式去创建RMClient,但是文档没有说明该条信息 *** WE STRONGLY SUGGEST YOU TO DESCRIBE YOUR ISSUE IN ENGLISH ***
33275c72a103116e72936d5b91b4a19cc29924a3
5c411383274ee97f3128615a7013707ab93b6275
https://github.com/seata/seata/compare/33275c72a103116e72936d5b91b4a19cc29924a3...5c411383274ee97f3128615a7013707ab93b6275
diff --git a/examples/src/main/java/com/alibaba/fescar/tm/dubbo/impl/AccountServiceImpl.java b/examples/src/main/java/com/alibaba/fescar/tm/dubbo/impl/AccountServiceImpl.java index ed22f2a4a..401fa22f3 100644 --- a/examples/src/main/java/com/alibaba/fescar/tm/dubbo/impl/AccountServiceImpl.java +++ b/examples/src/main/java/com/alibaba/fescar/tm/dubbo/impl/AccountServiceImpl.java @@ -56,8 +56,6 @@ public class AccountServiceImpl implements AccountService { String applicationId = "dubbo-demo-account-service"; String txServiceGroup = "my_test_tx_group"; - RMClientAT.init(applicationId, txServiceGroup); - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"dubbo-account-service.xml"}); context.getBean("service"); JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate"); diff --git a/examples/src/main/java/com/alibaba/fescar/tm/dubbo/impl/OrderServiceImpl.java b/examples/src/main/java/com/alibaba/fescar/tm/dubbo/impl/OrderServiceImpl.java index 5a655b9ca..4093415ee 100644 --- a/examples/src/main/java/com/alibaba/fescar/tm/dubbo/impl/OrderServiceImpl.java +++ b/examples/src/main/java/com/alibaba/fescar/tm/dubbo/impl/OrderServiceImpl.java @@ -106,8 +106,6 @@ public class OrderServiceImpl implements OrderService { String applicationId = "dubbo-demo-order-service"; String txServiceGroup = "my_test_tx_group"; - RMClientAT.init(applicationId, txServiceGroup); - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"dubbo-order-service.xml"}); context.getBean("service"); JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate"); diff --git a/examples/src/main/java/com/alibaba/fescar/tm/dubbo/impl/StorageServiceImpl.java b/examples/src/main/java/com/alibaba/fescar/tm/dubbo/impl/StorageServiceImpl.java index c67bc3d27..c6a00357f 100644 --- a/examples/src/main/java/com/alibaba/fescar/tm/dubbo/impl/StorageServiceImpl.java +++ b/examples/src/main/java/com/alibaba/fescar/tm/dubbo/impl/StorageServiceImpl.java @@ -55,8 +55,6 @@ public class StorageServiceImpl implements StorageService { String applicationId = "dubbo-demo-storage-service"; String txServiceGroup = "my_test_tx_group"; - RMClientAT.init(applicationId, txServiceGroup); - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"dubbo-storage-service.xml"}); context.getBean("service"); JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
['examples/src/main/java/com/alibaba/fescar/tm/dubbo/impl/AccountServiceImpl.java', 'examples/src/main/java/com/alibaba/fescar/tm/dubbo/impl/StorageServiceImpl.java', 'examples/src/main/java/com/alibaba/fescar/tm/dubbo/impl/OrderServiceImpl.java']
{'.java': 3}
3
3
0
0
3
771,671
158,924
23,324
232
174
36
6
3
878
97
234
20
0
0
1970-01-01T00:25:47
23,994
Java
{'Java': 10427110, 'ANTLR': 140225, 'TypeScript': 78693, 'Shell': 39417, 'Lua': 38478, 'SCSS': 34747, 'Kotlin': 7651, 'Python': 4804, 'Batchfile': 3916, 'TSQL': 3476, 'Less': 2488, 'Mustache': 1767, 'Dockerfile': 1411}
Apache License 2.0
564
google/gson/2364/904
google
gson
https://github.com/google/gson/issues/904
https://github.com/google/gson/pull/2364
https://github.com/google/gson/pull/2364
1
fixes
BigDecimal equals problem
Dear developers, it looks like the primitive's equals to did not handle BigDecimal's comparison. The following test will fail: ``` public void testUnequalDecimals() { JsonPrimitive small = new JsonPrimitive(1.0); JsonPrimitive large = new JsonPrimitive(2.0); assertFalse("small = large", small.equals(large)); BigDecimal dmax = BigDecimal.valueOf(Double.MAX_VALUE); JsonPrimitive smallBD = // dmax + 100.0 new JsonPrimitive(dmax.add(new BigDecimal("100.0"))); JsonPrimitive largeBD = // dmax + 200.0 new JsonPrimitive(dmax.add(new BigDecimal("200.0"))); assertFalse("small = large", smallBD.equals(largeBD)); } ``` Could you consider a fix for this, so it can support big decimal comparisons, too? Thanks!
051cb43fd9040a432626ef53523f1e7db7ab52c1
3c364b9c945c0e337b51b59fa60fc32355519ed7
https://github.com/google/gson/compare/051cb43fd9040a432626ef53523f1e7db7ab52c1...3c364b9c945c0e337b51b59fa60fc32355519ed7
diff --git a/gson/src/main/java/com/google/gson/JsonPrimitive.java b/gson/src/main/java/com/google/gson/JsonPrimitive.java index 827de959..f143da97 100644 --- a/gson/src/main/java/com/google/gson/JsonPrimitive.java +++ b/gson/src/main/java/com/google/gson/JsonPrimitive.java @@ -290,11 +290,10 @@ public final class JsonPrimitive extends JsonElement { : this.getAsNumber().longValue() == other.getAsNumber().longValue(); } if (value instanceof Number && other.value instanceof Number) { - double a = getAsNumber().doubleValue(); - // Java standard types other than double return true for two NaN. So, need - // special handling for double. - double b = other.getAsNumber().doubleValue(); - return a == b || (Double.isNaN(a) && Double.isNaN(b)); + return this.value instanceof BigDecimal && other.value instanceof BigDecimal + ? this.getAsBigDecimal().compareTo(other.getAsBigDecimal()) == 0 + : this.getAsDouble() == other.getAsDouble() + || (Double.isNaN(this.getAsDouble()) && Double.isNaN(other.getAsDouble())); } return value.equals(other.value); } diff --git a/gson/src/test/java/com/google/gson/JsonPrimitiveTest.java b/gson/src/test/java/com/google/gson/JsonPrimitiveTest.java index 24947012..959313ad 100644 --- a/gson/src/test/java/com/google/gson/JsonPrimitiveTest.java +++ b/gson/src/test/java/com/google/gson/JsonPrimitiveTest.java @@ -316,4 +316,31 @@ public class JsonPrimitiveTest { JsonPrimitive a = new JsonPrimitive("a"); assertThat(a).isSameInstanceAs(a.deepCopy()); // Primitives are immutable! } + + @Test + public void testBigDecimalEquals() { + JsonPrimitive small = new JsonPrimitive(1.0); + JsonPrimitive large = new JsonPrimitive(2.0); + assertThat(small.equals(large)).isFalse(); + + BigDecimal doubleMax = BigDecimal.valueOf(Double.MAX_VALUE); + JsonPrimitive smallBD = new JsonPrimitive(doubleMax.add(new BigDecimal("100.0"))); + JsonPrimitive largeBD = new JsonPrimitive(doubleMax.add(new BigDecimal("200.0"))); + assertThat(smallBD.equals(largeBD)).isFalse(); + } + + @Test + public void testBigDecimalEqualsZero() { + assertThat(new JsonPrimitive(new BigDecimal("0.0")) + .equals(new JsonPrimitive(new BigDecimal("0.00")))).isTrue(); + + assertThat(new JsonPrimitive(new BigDecimal("0.00")) + .equals(new JsonPrimitive(Double.valueOf("0.00")))).isTrue(); + } + + @Test + public void testEqualsDoubleNaNAndBigDecimal() { + assertThat(new JsonPrimitive(Double.NaN) + .equals(new JsonPrimitive(new BigDecimal("1.0")))).isFalse(); + } }
['gson/src/test/java/com/google/gson/JsonPrimitiveTest.java', 'gson/src/main/java/com/google/gson/JsonPrimitive.java']
{'.java': 2}
2
2
0
0
2
703,753
158,568
19,868
100
588
119
9
1
790
84
183
21
0
1
1970-01-01T00:28:00
22,315
Java
{'Java': 1674830}
Apache License 2.0
227
libgdx/libgdx/856/798
libgdx
libgdx
https://github.com/libgdx/libgdx/issues/798
https://github.com/libgdx/libgdx/pull/856
https://github.com/libgdx/libgdx/pull/856
1
fixes
Image are flipped in Particle Editor preview window
To Reproduce: - open particle editor - open any image - image is shown flipped upside down However, when particle is saved then loaded from file image is shown normal. It's also mentioned in this thread: http://www.badlogicgames.com/forum/viewtopic.php?f=11&t=3370&p=16574&hilit=particle+flipped#p16574
956c5671356974cab234cc1f8368f1ef583456a5
cf01bc29946f1b3bd9ab3e4f1c6f99078944da02
https://github.com/libgdx/libgdx/compare/956c5671356974cab234cc1f8368f1ef583456a5...cf01bc29946f1b3bd9ab3e4f1c6f99078944da02
diff --git a/extensions/gdx-tools/src/com/badlogic/gdx/tools/particleeditor/EffectPanel.java b/extensions/gdx-tools/src/com/badlogic/gdx/tools/particleeditor/EffectPanel.java index 04fa9b42d..9cb496f2f 100644 --- a/extensions/gdx-tools/src/com/badlogic/gdx/tools/particleeditor/EffectPanel.java +++ b/extensions/gdx-tools/src/com/badlogic/gdx/tools/particleeditor/EffectPanel.java @@ -65,7 +65,6 @@ class EffectPanel extends JPanel { emitter.getTint().setColors(new float[] {1, 0.12156863f, 0.047058824f}); emitter.getTransparency().setHigh(1); - emitter.setFlip(false, true); emitter.setMaxParticleCount(25); emitter.setImagePath("particle.png"); @@ -107,7 +106,6 @@ class EffectPanel extends JPanel { emitter.getTransparency().setTimeline(new float[] {0, 0.2f, 0.8f, 1}); emitter.getTransparency().setScaling(new float[] {0, 1, 0.75f, 0}); - emitter.setFlip(false, true); emitter.setMaxParticleCount(200); emitter.setImagePath("particle.png");
['extensions/gdx-tools/src/com/badlogic/gdx/tools/particleeditor/EffectPanel.java']
{'.java': 1}
1
1
0
0
1
10,173,648
2,601,633
291,201
1,754
67
19
2
1
305
37
79
10
1
0
1970-01-01T00:23:02
21,772
Java
{'Java': 15083440, 'C++': 10753718, 'C': 1692234, 'SWIG': 162005, 'GLSL': 124461, 'CSS': 58715, 'Assembly': 53505, 'CMake': 31706, 'Ragel': 30666, 'OpenEdge ABL': 17727, 'Lua': 1682, 'HTML': 1193, 'Shell': 1102}
Apache License 2.0
226
libgdx/libgdx/2014/2001
libgdx
libgdx
https://github.com/libgdx/libgdx/issues/2001
https://github.com/libgdx/libgdx/pull/2014
https://github.com/libgdx/libgdx/pull/2014
1
fixes
Config file is not always positioning window
Hey, just found a small bug with window positioning when using config vars. If i put my code like so, then it centers both axis. config.x=-1; config.y=0; or config.x=0; config.y=-1; But if i put it like so, then window is in top left corner. config.x=0; config.y=0;
b96fa2d867f3b600f4177f82782a2dbdf54c3b75
ac402df89ec40f22d673f0ef95e50c29e4a8abfb
https://github.com/libgdx/libgdx/compare/b96fa2d867f3b600f4177f82782a2dbdf54c3b75...ac402df89ec40f22d673f0ef95e50c29e4a8abfb
diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGraphics.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGraphics.java index cf5c18d8b..2c0af30a1 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGraphics.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGraphics.java @@ -152,10 +152,8 @@ public class LwjglGraphics implements Graphics { Display.setInitialBackground(config.initialBackgroundColor.r, config.initialBackgroundColor.g, config.initialBackgroundColor.b); - if (config.x != -1 && config.y != -1) Display.setLocation(config.x, config.y); + Display.setLocation(config.x, config.y); createDisplayPixelFormat(); - config.x = Display.getX(); - config.y = Display.getY(); initiateGLInstances(); }
['backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGraphics.java']
{'.java': 1}
1
1
0
0
1
10,076,517
2,555,473
282,827
1,542
189
50
4
1
268
46
77
13
0
0
1970-01-01T00:23:23
21,772
Java
{'Java': 15083440, 'C++': 10753718, 'C': 1692234, 'SWIG': 162005, 'GLSL': 124461, 'CSS': 58715, 'Assembly': 53505, 'CMake': 31706, 'Ragel': 30666, 'OpenEdge ABL': 17727, 'Lua': 1682, 'HTML': 1193, 'Shell': 1102}
Apache License 2.0
225
libgdx/libgdx/2296/2136
libgdx
libgdx
https://github.com/libgdx/libgdx/issues/2136
https://github.com/libgdx/libgdx/pull/2296
https://github.com/libgdx/libgdx/pull/2296
1
fixes
allowIpod config not working if music started after app is launched
Setting allowIpod = true in IOSApplicationConfiguration seems to have no effect if the libGDX application is launched without any music playing. Steps to reproduce: - start libGDX app with music off (with allowIpod = true) - switch to iTunes/music app - start music - return to libGDX app (music stops, it should keep playing) I get the same result in iOS 6 and 7 libGDX version: 1.2.0 roboVM version 0.0.14 There is another report of the same issue on stack overflow: http://stackoverflow.com/questions/23473429/libgdx-robovm-allowipod-does-not-work-if-game-starts-then-paused
72af560ce559b6af5f7b7b6caba9b2ef661092ac
c31a342d19654eafa9495d6bf0b570e5466ed900
https://github.com/libgdx/libgdx/compare/72af560ce559b6af5f7b7b6caba9b2ef661092ac...c31a342d19654eafa9495d6bf0b570e5466ed900
diff --git a/backends/gdx-backend-robovm/src/com/badlogic/gdx/backends/iosrobovm/IOSApplication.java b/backends/gdx-backend-robovm/src/com/badlogic/gdx/backends/iosrobovm/IOSApplication.java index 96f15ec53..22eb09dda 100644 --- a/backends/gdx-backend-robovm/src/com/badlogic/gdx/backends/iosrobovm/IOSApplication.java +++ b/backends/gdx-backend-robovm/src/com/badlogic/gdx/backends/iosrobovm/IOSApplication.java @@ -1,12 +1,12 @@ /******************************************************************************* * Copyright 2011 See AUTHORS file. - * + * * 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. @@ -45,6 +45,7 @@ import com.badlogic.gdx.LifecycleListener; import com.badlogic.gdx.Net; import com.badlogic.gdx.Preferences; import com.badlogic.gdx.backends.iosrobovm.objectal.OALAudioSession; +import com.badlogic.gdx.backends.iosrobovm.objectal.OALSimpleAudio; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Clipboard; @@ -176,7 +177,7 @@ public class IOSApplication implements Application { } /** Returns our real display dimension based on screen orientation. - * + * * @param viewController The view controller. * @return Or real display dimension. */ CGSize getBounds (UIViewController viewController) { @@ -227,6 +228,9 @@ public class IOSApplication implements Application { // workaround for ObjectAL crash problem // see: https://groups.google.com/forum/?fromgroups=#!topic/objectal-for-iphone/ubRWltp_i1Q OALAudioSession.sharedInstance().forceEndInterruption(); + if (config.allowIpod) { + OALSimpleAudio.sharedInstance().setUseHardwareIfAvailable(false); + } graphics.makeCurrent(); graphics.resume(); } diff --git a/backends/gdx-backend-robovm/src/com/badlogic/gdx/backends/iosrobovm/objectal/OALSimpleAudio.java b/backends/gdx-backend-robovm/src/com/badlogic/gdx/backends/iosrobovm/objectal/OALSimpleAudio.java index 4824f7aae..1a048556c 100644 --- a/backends/gdx-backend-robovm/src/com/badlogic/gdx/backends/iosrobovm/objectal/OALSimpleAudio.java +++ b/backends/gdx-backend-robovm/src/com/badlogic/gdx/backends/iosrobovm/objectal/OALSimpleAudio.java @@ -1,12 +1,12 @@ /******************************************************************************* * Copyright 2013 See AUTHORS file. - * + * * 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. @@ -17,13 +17,10 @@ package com.badlogic.gdx.backends.iosrobovm.objectal; import org.robovm.apple.foundation.NSObject; -import org.robovm.objc.ObjCClass; import org.robovm.objc.ObjCRuntime; -import org.robovm.objc.Selector; import org.robovm.objc.annotation.Method; import org.robovm.objc.annotation.NativeClass; import org.robovm.objc.annotation.Property; -import org.robovm.rt.bro.annotation.Bridge; import org.robovm.rt.bro.annotation.Library; /** @@ -60,4 +57,10 @@ public final class OALSimpleAudio extends NSObject { @Property public native void setHonorSilentSwitch (boolean honorSilentSwitch); + + @Property + public native boolean isUseHardwareIfAvailable(); + + @Property + public native void setUseHardwareIfAvailable(boolean b); }
['backends/gdx-backend-robovm/src/com/badlogic/gdx/backends/iosrobovm/IOSApplication.java', 'backends/gdx-backend-robovm/src/com/badlogic/gdx/backends/iosrobovm/objectal/OALSimpleAudio.java']
{'.java': 2}
2
2
0
0
2
10,590,068
2,679,484
297,386
1,632
488
127
27
2
582
82
158
14
1
0
1970-01-01T00:23:29
21,772
Java
{'Java': 15083440, 'C++': 10753718, 'C': 1692234, 'SWIG': 162005, 'GLSL': 124461, 'CSS': 58715, 'Assembly': 53505, 'CMake': 31706, 'Ragel': 30666, 'OpenEdge ABL': 17727, 'Lua': 1682, 'HTML': 1193, 'Shell': 1102}
Apache License 2.0
224
libgdx/libgdx/2303/2301
libgdx
libgdx
https://github.com/libgdx/libgdx/issues/2301
https://github.com/libgdx/libgdx/pull/2303
https://github.com/libgdx/libgdx/pull/2303
1
fixes
setDrawContact() missing
setDrawContact() fails when compiling for GWT. [Box2DDebugRenderer.java](https://github.com/libgdx/libgdx/blob/master/extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/com/badlogic/gdx/physics/box2d/Box2DDebugRenderer.java) file does not contain such function. Cheers
1900f0593506091c63146579c7bacb84e99a357d
cf054cb5d540bc909a46a1466bf9000d5a61569c
https://github.com/libgdx/libgdx/compare/1900f0593506091c63146579c7bacb84e99a357d...cf054cb5d540bc909a46a1466bf9000d5a61569c
diff --git a/extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/com/badlogic/gdx/physics/box2d/Box2DDebugRenderer.java b/extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/com/badlogic/gdx/physics/box2d/Box2DDebugRenderer.java index 447b2a027..66ff4a387 100644 --- a/extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/com/badlogic/gdx/physics/box2d/Box2DDebugRenderer.java +++ b/extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/com/badlogic/gdx/physics/box2d/Box2DDebugRenderer.java @@ -352,6 +352,14 @@ public class Box2DDebugRenderer { public void setDrawVelocities (boolean drawVelocities) { this.drawVelocities = drawVelocities; } + + public boolean isDrawContacts () { + return drawContacts; + } + + public void setDrawContacts (boolean drawContacts) { + this.drawContacts = drawContacts; + } public static Vector2 getAxis () { return axis;
['extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/com/badlogic/gdx/physics/box2d/Box2DDebugRenderer.java']
{'.java': 1}
1
1
0
0
1
10,591,157
2,679,699
297,429
1,632
166
37
8
1
297
14
90
5
1
0
1970-01-01T00:23:29
21,772
Java
{'Java': 15083440, 'C++': 10753718, 'C': 1692234, 'SWIG': 162005, 'GLSL': 124461, 'CSS': 58715, 'Assembly': 53505, 'CMake': 31706, 'Ragel': 30666, 'OpenEdge ABL': 17727, 'Lua': 1682, 'HTML': 1193, 'Shell': 1102}
Apache License 2.0
222
libgdx/libgdx/3767/3766
libgdx
libgdx
https://github.com/libgdx/libgdx/issues/3766
https://github.com/libgdx/libgdx/pull/3767
https://github.com/libgdx/libgdx/pull/3767
1
fix
GWT isButtonPressed is wrong.
After trying right button calls it just check for left button. It will always return true if you check if button is left first. https://github.com/libgdx/libgdx/blob/master/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtInput.java#L170
926767148b3801b468daaa8615d89f2fae379026
1443fd0977a4acb5fef69d98595edf166ec57359
https://github.com/libgdx/libgdx/compare/926767148b3801b468daaa8615d89f2fae379026...1443fd0977a4acb5fef69d98595edf166ec57359
diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtInput.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtInput.java index 7d00e78d5..3f098bf16 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtInput.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtInput.java @@ -167,7 +167,7 @@ public class GwtInput implements Input { @Override public boolean isButtonPressed (int button) { - return button == Buttons.LEFT && touched[0]; + return pressedButtons.contains(button) && touched[0]; } @Override
['backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtInput.java']
{'.java': 1}
1
1
0
0
1
11,723,252
2,972,993
328,357
1,770
106
24
2
1
256
25
67
4
1
0
1970-01-01T00:24:13
21,772
Java
{'Java': 15083440, 'C++': 10753718, 'C': 1692234, 'SWIG': 162005, 'GLSL': 124461, 'CSS': 58715, 'Assembly': 53505, 'CMake': 31706, 'Ragel': 30666, 'OpenEdge ABL': 17727, 'Lua': 1682, 'HTML': 1193, 'Shell': 1102}
Apache License 2.0
221
libgdx/libgdx/6382/6380
libgdx
libgdx
https://github.com/libgdx/libgdx/issues/6380
https://github.com/libgdx/libgdx/pull/6382
https://github.com/libgdx/libgdx/pull/6382
1
fixes
TextureArray
#### Issue details After create `TextureArray` I change the parameters (UV-wrapping and texture-filtering) The texture is not working (I see a black box) If I don't change the parameters after creation, everything is fine. I think the texture is incorrectly invalidated then I use the setFilter function (and maybe setWrap) #### Reproduction steps/code Create instance `new TextureArray(useMipMaps=true,...)` or `new TextureArray(useMipMaps=true,...)` See what works correctly. Create an instance again. And change the property `setFilter(MipMapLinearLinear, Linear)` Now I only see black (I believe the textures are invalid and some are broken, then I use the mip-map filter) #### Version of LibGDX and/or relevant dependencies 1.9.13 #### Stacktrace #### Please select the affected platforms + Linux
9e9ecd47dcb9c96cc3a9ac8f89434530bd92b759
22943947c5da4fef1870d9bbac37be7f4783c2de
https://github.com/libgdx/libgdx/compare/9e9ecd47dcb9c96cc3a9ac8f89434530bd92b759...22943947c5da4fef1870d9bbac37be7f4783c2de
diff --git a/gdx/src/com/badlogic/gdx/graphics/glutils/FileTextureArrayData.java b/gdx/src/com/badlogic/gdx/graphics/glutils/FileTextureArrayData.java index 0a30b6974..a8160f2fc 100644 --- a/gdx/src/com/badlogic/gdx/graphics/glutils/FileTextureArrayData.java +++ b/gdx/src/com/badlogic/gdx/graphics/glutils/FileTextureArrayData.java @@ -86,6 +86,9 @@ public class FileTextureArrayData implements TextureArrayData { disposePixmap = true; } Gdx.gl30.glTexSubImage3D(GL30.GL_TEXTURE_2D_ARRAY, 0, 0, 0, i, pixmap.getWidth(), pixmap.getHeight(), 1, pixmap.getGLInternalFormat(), pixmap.getGLType(), pixmap.getPixels()); + if (useMipMaps) { + Gdx.gl20.glGenerateMipmap(GL30.GL_TEXTURE_2D_ARRAY); + } if (disposePixmap) pixmap.dispose(); } } diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/g3d/TextureArrayTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/g3d/TextureArrayTest.java index 8bef00a41..918d6ea22 100644 --- a/tests/gdx-tests/src/com/badlogic/gdx/tests/g3d/TextureArrayTest.java +++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/g3d/TextureArrayTest.java @@ -18,6 +18,7 @@ package com.badlogic.gdx.tests.g3d; import com.badlogic.gdx.Application; import com.badlogic.gdx.Gdx; +import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Mesh; @@ -27,13 +28,17 @@ import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.TextureArray; import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes; +import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.g3d.utils.FirstPersonCameraController; import com.badlogic.gdx.graphics.glutils.ShaderProgram; +import com.badlogic.gdx.graphics.profiling.GLErrorListener; import com.badlogic.gdx.graphics.profiling.GLProfiler; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.tests.utils.GdxTest; +import com.badlogic.gdx.tests.utils.GdxTestConfig; /** @author Tomski **/ +@GdxTestConfig(requireGL30=true) public class TextureArrayTest extends GdxTest { TextureArray textureArray; @@ -66,8 +71,14 @@ public class TextureArrayTest extends GdxTest { cameraController = new FirstPersonCameraController(camera); Gdx.input.setInputProcessor(cameraController); - textureArray = new TextureArray(texPaths); + FileHandle [] texFiles = new FileHandle[texPaths.length]; + for(int i=0 ; i<texPaths.length ; i++){ + texFiles[i] = Gdx.files.internal(texPaths[i]); + } + + textureArray = new TextureArray(true, texFiles); textureArray.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat); + textureArray.setFilter(TextureFilter.MipMapLinearLinear, TextureFilter.Linear); shaderProgram = new ShaderProgram(Gdx.files.internal("data/shaders/texturearray.vert"), Gdx.files.internal("data/shaders/texturearray.frag")); System.out.println(shaderProgram.getLog());
['tests/gdx-tests/src/com/badlogic/gdx/tests/g3d/TextureArrayTest.java', 'gdx/src/com/badlogic/gdx/graphics/glutils/FileTextureArrayData.java']
{'.java': 2}
2
2
0
0
2
12,882,101
3,279,985
353,511
1,923
88
30
3
1
839
113
189
28
0
0
1970-01-01T00:26:51
21,772
Java
{'Java': 15083440, 'C++': 10753718, 'C': 1692234, 'SWIG': 162005, 'GLSL': 124461, 'CSS': 58715, 'Assembly': 53505, 'CMake': 31706, 'Ragel': 30666, 'OpenEdge ABL': 17727, 'Lua': 1682, 'HTML': 1193, 'Shell': 1102}
Apache License 2.0
219
libgdx/libgdx/2449/2087
libgdx
libgdx
https://github.com/libgdx/libgdx/issues/2087
https://github.com/libgdx/libgdx/pull/2449
https://github.com/libgdx/libgdx/issues/2087#issuecomment-58633764
1
fixes
Lwjgl backend doesn't support OpenGL ES 3.2+
Creating a LwjglApplication with useGL30 set to true still doesn't create an OpenGL ES 3 context. Additionally, Gdx.gl30 is null. The issue seems to be [here](https://github.com/libgdx/libgdx/blob/master/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGraphics.java#L166). context should be passed in to Display.create along with the PixelFormat. [This line](https://github.com/libgdx/libgdx/blob/master/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGraphics.java#L241) should also check whether the major version is 3 and set gl30 accordingly.
ce386db862a0a9639f513c40163b819c0729ed79
d4d3941299d4c9e969169034dce025f9c4826056
https://github.com/libgdx/libgdx/compare/ce386db862a0a9639f513c40163b819c0729ed79...d4d3941299d4c9e969169034dce025f9c4826056
diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGL20.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGL20.java index 290afba2e..57cecebb6 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGL20.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGL20.java @@ -89,7 +89,7 @@ class LwjglGL20 implements com.badlogic.gdx.graphics.GL20 { public void glBufferData (int target, int size, Buffer data, int usage) { if(data == null) - throw new GdxRuntimeException("Using null for the data not possible, blame LWJGL"); + GL15.glBufferData(target, size, usage); else if (data instanceof ByteBuffer) GL15.glBufferData(target, (ByteBuffer)data, usage); else if (data instanceof IntBuffer) diff --git a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGraphics.java b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGraphics.java index c193b5f17..985bc76f3 100644 --- a/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGraphics.java +++ b/backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGraphics.java @@ -263,6 +263,7 @@ public class LwjglGraphics implements Graphics { Gdx.gl = gl20; Gdx.gl20 = gl20; + Gdx.gl30 = gl30; } private String glInfo () {
['backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGL20.java', 'backends/gdx-backend-lwjgl/src/com/badlogic/gdx/backends/lwjgl/LwjglGraphics.java']
{'.java': 2}
2
2
0
0
2
10,748,723
2,720,129
301,959
1,652
152
41
3
2
589
52
150
6
2
0
1970-01-01T00:23:32
21,772
Java
{'Java': 15083440, 'C++': 10753718, 'C': 1692234, 'SWIG': 162005, 'GLSL': 124461, 'CSS': 58715, 'Assembly': 53505, 'CMake': 31706, 'Ragel': 30666, 'OpenEdge ABL': 17727, 'Lua': 1682, 'HTML': 1193, 'Shell': 1102}
Apache License 2.0
523
google/exoplayer/9525/9524
google
exoplayer
https://github.com/google/ExoPlayer/issues/9524
https://github.com/google/ExoPlayer/pull/9525
https://github.com/google/ExoPlayer/pull/9525
1
fixes
PlayerControlView time position not being initialized to 0:00 in ExoPlayer r2.15.1
Reproduction: 1. Change the demo app to use PlayerControlView instead of StyledPlayerControlView. 2. Open a video. See that the timestamp is blank instead of starting at 0:00. This appears to be a regression in 86f8c4e44e5467cb9d3b79dcf0593903ddd58422 / dd33afb33508018a2734ebbc65eb34b179259983 from fixing #9111
b192465bba5c0705ff8db195ad043e0846b6c9cf
e883c04006694392aae3f8c23223158cd653306d
https://github.com/google/exoplayer/compare/b192465bba5c0705ff8db195ad043e0846b6c9cf...e883c04006694392aae3f8c23223158cd653306d
diff --git a/library/ui/src/main/java/com/google/android/exoplayer2/ui/PlayerControlView.java b/library/ui/src/main/java/com/google/android/exoplayer2/ui/PlayerControlView.java index 7035372b32..24dbde6a72 100644 --- a/library/ui/src/main/java/com/google/android/exoplayer2/ui/PlayerControlView.java +++ b/library/ui/src/main/java/com/google/android/exoplayer2/ui/PlayerControlView.java @@ -343,8 +343,8 @@ public class PlayerControlView extends FrameLayout { private long[] extraAdGroupTimesMs; private boolean[] extraPlayedAdGroups; private long currentWindowOffset; - private long currentPosition; - private long currentBufferedPosition; + private long currentPosition = C.POSITION_UNSET; + private long currentBufferedPosition = C.POSITION_UNSET; public PlayerControlView(Context context) { this(context, /* attrs= */ null);
['library/ui/src/main/java/com/google/android/exoplayer2/ui/PlayerControlView.java']
{'.java': 1}
1
1
0
0
1
9,859,066
2,207,633
262,532
958
185
38
4
1
322
40
99
7
0
0
1970-01-01T00:27:13
20,925
Java
{'Java': 18182600, 'C++': 112860, 'GLSL': 48506, 'Shell': 25961, 'Makefile': 11496, 'CMake': 3728}
Apache License 2.0
524
google/exoplayer/4441/4419
google
exoplayer
https://github.com/google/ExoPlayer/issues/4419
https://github.com/google/ExoPlayer/pull/4441
https://github.com/google/ExoPlayer/pull/4441
1
solves
ANR on Fire TV when changing surface holder
### Issue description ANR occurs when setting video surface holder to null after it got destroyed. ### Reproduction steps Trigger replacing surface. ### Link to test content Any video. ### Version of ExoPlayer being used 2.7.0, 2.7.2 and 2.8.1 ### Device(s) and version(s) of Android being used Fire TV 6.0.1.4-012, OS 6.2.1.3 Codec: OMX.amlogic.avc.decoder.awesome Device: needle Model: AFTN ### A full bug report captured from the device Will be sent by email.
a1f89bec0dcc30bdc2f3a8889371447f701ae9b7
99d3e8f1d39e1f605ec34345a4673dc817e95f70
https://github.com/google/exoplayer/compare/a1f89bec0dcc30bdc2f3a8889371447f701ae9b7...99d3e8f1d39e1f605ec34345a4673dc817e95f70
diff --git a/library/core/src/main/java/com/google/android/exoplayer2/video/MediaCodecVideoRenderer.java b/library/core/src/main/java/com/google/android/exoplayer2/video/MediaCodecVideoRenderer.java index 990025b5af..5e8a98ea68 100644 --- a/library/core/src/main/java/com/google/android/exoplayer2/video/MediaCodecVideoRenderer.java +++ b/library/core/src/main/java/com/google/android/exoplayer2/video/MediaCodecVideoRenderer.java @@ -825,10 +825,11 @@ public class MediaCodecVideoRenderer extends MediaCodecRenderer { private boolean shouldUseDummySurface(MediaCodecInfo codecInfo) { return Util.SDK_INT >= 23 && !tunneling + && !codecNeedsDummySurfaceWorkaround(codecInfo.name) && !codecNeedsSetOutputSurfaceWorkaround(codecInfo.name) && (!codecInfo.secure || DummySurface.isSecureSupported(context)); } - + private void setJoiningDeadlineMs() { joiningDeadlineMs = allowedJoiningTimeMs > 0 ? (SystemClock.elapsedRealtime() + allowedJoiningTimeMs) : C.TIME_UNSET; @@ -1171,6 +1172,12 @@ public class MediaCodecVideoRenderer extends MediaCodecRenderer { return Util.SDK_INT <= 22 && "foster".equals(Util.DEVICE) && "NVIDIA".equals(Util.MANUFACTURER); } + private static boolean codecNeedsDummySurfaceWorkaround(String name) { + // Work around https://github.com/google/ExoPlayer/issues/4419. + return (("needle".equals(Util.DEVICE)) // FireTV 4K + && "OMX.amlogic.avc.decoder.awesome".equals(name)); + } + /** * Returns whether the device is known to implement {@link MediaCodec#setOutputSurface(Surface)} * incorrectly.
['library/core/src/main/java/com/google/android/exoplayer2/video/MediaCodecVideoRenderer.java']
{'.java': 1}
1
1
0
0
1
5,348,254
1,230,405
145,879
599
341
82
9
1
492
72
139
23
0
0
1970-01-01T00:25:30
20,925
Java
{'Java': 18182600, 'C++': 112860, 'GLSL': 48506, 'Shell': 25961, 'Makefile': 11496, 'CMake': 3728}
Apache License 2.0
3,480
apache/shardingsphere/2529/2528
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2528
https://github.com/apache/shardingsphere/pull/2529
https://github.com/apache/shardingsphere/pull/2529
1
fixes
tinyint column don't return a 8-bit integer value but a boolean value
## 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-RC1-SNAPSHOT ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-Proxy ### Expected behavior When the column type is **tinyint**, return a 8-bit integer in MySQL protocol ### Actual behavior When the column type is **tinyint**, return a boolean value in MySQL protocol ### Reason analyze (If you can) JDBC's getObject() return a boolean value if the column occupy one byte. ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc. Any query SQL. ### Example codes for reproduce this issue (such as a github link).
7a56c4ba2a4a63a3b1cf2846de6fc3c70cd5ccf6
ba8c9e48052cd04c6dbeaeefb1ffba3579f772c0
https://github.com/apache/shardingsphere/compare/7a56c4ba2a4a63a3b1cf2846de6fc3c70cd5ccf6...ba8c9e48052cd04c6dbeaeefb1ffba3579f772c0
diff --git a/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java b/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java index a7dcbb9b07c..ee8d6833be1 100644 --- a/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java +++ b/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java @@ -24,15 +24,9 @@ import org.apache.shardingsphere.core.rule.ShardingRule; import org.apache.shardingsphere.spi.encrypt.ShardingEncryptor; import java.io.InputStream; -import java.io.Reader; -import java.math.BigDecimal; -import java.net.URL; -import java.sql.Blob; -import java.sql.Clob; import java.sql.Date; import java.sql.ResultSet; import java.sql.SQLException; -import java.sql.SQLXML; import java.sql.Time; import java.sql.Timestamp; import java.util.Calendar; @@ -74,96 +68,12 @@ public final class StreamQueryResult implements QueryResult { @Override public Object getValue(final int columnIndex, final Class<?> type) throws SQLException { - Object result; - if (Object.class == type) { - result = decrypt(columnIndex, resultSet.getObject(columnIndex)); - } else if (boolean.class == type) { - result = decrypt(columnIndex, resultSet.getBoolean(columnIndex)); - } else if (byte.class == type) { - result = decrypt(columnIndex, resultSet.getByte(columnIndex)); - } else if (short.class == type) { - result = decrypt(columnIndex, resultSet.getShort(columnIndex)); - } else if (int.class == type) { - result = decrypt(columnIndex, resultSet.getInt(columnIndex)); - } else if (long.class == type) { - result = decrypt(columnIndex, resultSet.getLong(columnIndex)); - } else if (float.class == type) { - result = decrypt(columnIndex, resultSet.getFloat(columnIndex)); - } else if (double.class == type) { - result = decrypt(columnIndex, resultSet.getDouble(columnIndex)); - } else if (String.class == type) { - result = decrypt(columnIndex, resultSet.getString(columnIndex)); - } else if (BigDecimal.class == type) { - result = decrypt(columnIndex, resultSet.getBigDecimal(columnIndex)); - } else if (byte[].class == type) { - result = resultSet.getBytes(columnIndex); - } else if (Date.class == type) { - result = resultSet.getDate(columnIndex); - } else if (Time.class == type) { - result = resultSet.getTime(columnIndex); - } else if (Timestamp.class == type) { - result = resultSet.getTimestamp(columnIndex); - } else if (URL.class == type) { - result = resultSet.getURL(columnIndex); - } else if (Blob.class == type) { - result = resultSet.getBlob(columnIndex); - } else if (Clob.class == type) { - result = resultSet.getClob(columnIndex); - } else if (SQLXML.class == type) { - result = resultSet.getSQLXML(columnIndex); - } else if (Reader.class == type) { - result = resultSet.getCharacterStream(columnIndex); - } else { - result = decrypt(columnIndex, resultSet.getObject(columnIndex)); - } - return result; + return decrypt(columnIndex, QueryResultUtil.getValue(resultSet, columnIndex)); } @Override public Object getValue(final String columnLabel, final Class<?> type) throws SQLException { - Object result; - if (Object.class == type) { - result = decrypt(columnLabel, resultSet.getObject(columnLabel)); - } else if (boolean.class == type) { - result = decrypt(columnLabel, resultSet.getBoolean(columnLabel)); - } else if (byte.class == type) { - result = decrypt(columnLabel, resultSet.getByte(columnLabel)); - } else if (short.class == type) { - result = decrypt(columnLabel, resultSet.getShort(columnLabel)); - } else if (int.class == type) { - result = decrypt(columnLabel, resultSet.getInt(columnLabel)); - } else if (long.class == type) { - result = decrypt(columnLabel, resultSet.getLong(columnLabel)); - } else if (float.class == type) { - result = decrypt(columnLabel, resultSet.getFloat(columnLabel)); - } else if (double.class == type) { - result = decrypt(columnLabel, resultSet.getDouble(columnLabel)); - } else if (String.class == type) { - result = decrypt(columnLabel, resultSet.getString(columnLabel)); - } else if (BigDecimal.class == type) { - result = decrypt(columnLabel, resultSet.getBigDecimal(columnLabel)); - } else if (byte[].class == type) { - result = resultSet.getBytes(columnLabel); - } else if (Date.class == type) { - result = resultSet.getDate(columnLabel); - } else if (Time.class == type) { - result = resultSet.getTime(columnLabel); - } else if (Timestamp.class == type) { - result = resultSet.getTimestamp(columnLabel); - } else if (URL.class == type) { - result = resultSet.getURL(columnLabel); - } else if (Blob.class == type) { - result = resultSet.getBlob(columnLabel); - } else if (Clob.class == type) { - result = resultSet.getClob(columnLabel); - } else if (SQLXML.class == type) { - result = resultSet.getSQLXML(columnLabel); - } else if (Reader.class == type) { - result = resultSet.getCharacterStream(columnLabel); - } else { - result = decrypt(columnLabel, resultSet.getObject(columnLabel)); - } - return result; + return decrypt(columnLabel, QueryResultUtil.getValue(resultSet, metaData.getColumnIndex(columnLabel))); } @Override 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 f16b15b1de1..88a94151f73 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 @@ -34,6 +34,7 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; +import java.sql.Types; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -81,6 +82,7 @@ public final class PreparedStatementExecutorTest extends AbstractBaseExecutorTes when(resultSetMetaData.getColumnLabel(1)).thenReturn("column"); when(resultSetMetaData.getTableName(1)).thenReturn("table_x"); when(resultSetMetaData.getColumnCount()).thenReturn(1); + when(resultSetMetaData.getColumnType(1)).thenReturn(Types.VARCHAR); when(resultSet.getString(1)).thenReturn("value"); when(resultSet.getMetaData()).thenReturn(resultSetMetaData); when(preparedStatement.executeQuery()).thenReturn(resultSet); @@ -99,6 +101,7 @@ public final class PreparedStatementExecutorTest extends AbstractBaseExecutorTes when(resultSetMetaData.getColumnLabel(1)).thenReturn("column"); when(resultSetMetaData.getTableName(1)).thenReturn("table_x"); when(resultSetMetaData.getColumnCount()).thenReturn(1); + when(resultSetMetaData.getColumnType(1)).thenReturn(Types.INTEGER); when(resultSet1.getMetaData()).thenReturn(resultSetMetaData); when(resultSet2.getMetaData()).thenReturn(resultSetMetaData); when(resultSet1.getInt(1)).thenReturn(1); 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 058a9a90112..068e7913aaa 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 @@ -35,6 +35,7 @@ import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; +import java.sql.Types; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -82,6 +83,7 @@ public final class StatementExecutorTest extends AbstractBaseExecutorTest { when(resultSetMetaData.getColumnLabel(1)).thenReturn("column"); when(resultSetMetaData.getTableName(1)).thenReturn("table_x"); when(resultSetMetaData.getColumnCount()).thenReturn(1); + when(resultSetMetaData.getColumnType(1)).thenReturn(Types.VARCHAR); when(resultSet.getString(1)).thenReturn("value"); when(resultSet.getMetaData()).thenReturn(resultSetMetaData); when(statement.executeQuery(DQL_SQL)).thenReturn(resultSet); @@ -101,6 +103,7 @@ public final class StatementExecutorTest extends AbstractBaseExecutorTest { when(resultSetMetaData.getColumnLabel(1)).thenReturn("column"); when(resultSetMetaData.getTableName(1)).thenReturn("table_x"); when(resultSetMetaData.getColumnCount()).thenReturn(1); + when(resultSetMetaData.getColumnType(1)).thenReturn(Types.INTEGER); when(resultSet1.getMetaData()).thenReturn(resultSetMetaData); when(resultSet2.getMetaData()).thenReturn(resultSetMetaData); when(resultSet1.getInt(1)).thenReturn(1);
['sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/executor/PreparedStatementExecutorTest.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/StreamQueryResult.java']
{'.java': 3}
3
3
0
0
3
2,927,062
588,103
75,053
1,031
4,851
942
94
1
1,256
174
284
28
2
0
1970-01-01T00:26:00
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,484
apache/shardingsphere/2352/2343
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2343
https://github.com/apache/shardingsphere/pull/2352
https://github.com/apache/shardingsphere/pull/2352
1
fixes
Sharding-proxy Query result :extraneous data in "D" message ,reason: have chinese
## 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-RC1 ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-Proxy ### Expected behavior table data have Chinese .select * from table show error message : extraneous data in "D" message ### Actual behavior proxy backend POSTGRES , frontend postgres ### Reason analyze (If you can) reason Chinese , Postgres server_encoding ,client_encoding UTF-8 ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc. any table ,have Chinese is error. ### Example codes for reproduce this issue (such as a github link).
6c49107d434c31e5f95365bb1bfcbcd52f7f4585
a4adf6df82926c267a74fb287249106a9582715d
https://github.com/apache/shardingsphere/compare/6c49107d434c31e5f95365bb1bfcbcd52f7f4585...a4adf6df82926c267a74fb287249106a9582715d
diff --git a/sharding-proxy/sharding-proxy-transport/sharding-proxy-transport-postgresql/src/main/java/org/apache/shardingsphere/shardingproxy/transport/postgresql/packet/command/query/text/PostgreSQLDataRowPacket.java b/sharding-proxy/sharding-proxy-transport/sharding-proxy-transport-postgresql/src/main/java/org/apache/shardingsphere/shardingproxy/transport/postgresql/packet/command/query/text/PostgreSQLDataRowPacket.java index ee4b0ac0032..9eabe5a9c31 100644 --- a/sharding-proxy/sharding-proxy-transport/sharding-proxy-transport-postgresql/src/main/java/org/apache/shardingsphere/shardingproxy/transport/postgresql/packet/command/query/text/PostgreSQLDataRowPacket.java +++ b/sharding-proxy/sharding-proxy-transport/sharding-proxy-transport-postgresql/src/main/java/org/apache/shardingsphere/shardingproxy/transport/postgresql/packet/command/query/text/PostgreSQLDataRowPacket.java @@ -50,7 +50,7 @@ public final class PostgreSQLDataRowPacket implements PostgreSQLPacket { payload.writeBytes((byte[]) each); } else { String columnData = each.toString(); - payload.writeInt4(columnData.length()); + payload.writeInt4(columnData.getBytes().length); payload.writeStringEOF(columnData); } }
['sharding-proxy/sharding-proxy-transport/sharding-proxy-transport-postgresql/src/main/java/org/apache/shardingsphere/shardingproxy/transport/postgresql/packet/command/query/text/PostgreSQLDataRowPacket.java']
{'.java': 1}
1
1
0
0
1
3,278,405
662,802
82,927
1,137
130
18
2
1
1,243
169
277
28
2
0
1970-01-01T00:25:57
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,481
apache/shardingsphere/2467/2460
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2460
https://github.com/apache/shardingsphere/pull/2467
https://github.com/apache/shardingsphere/pull/2467
1
fixes
The problem that the value of the bit type cannot be returned correctly
I used shardingproxy to do the sharding, but there is a field of bit type. The value stored in this field is 1 regardless of the number of questions. Please ask how to solve this problem. Thank you.
529a1e80231d4ac2efc49d4884644cb716570f4c
2e0a7ebe1fd49b596242f62e68c877cb766a5092
https://github.com/apache/shardingsphere/compare/529a1e80231d4ac2efc49d4884644cb716570f4c...2e0a7ebe1fd49b596242f62e68c877cb766a5092
diff --git a/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultUtil.java b/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultUtil.java index e41c8c2a35b..82bbd806543 100644 --- a/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultUtil.java +++ b/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultUtil.java @@ -54,6 +54,7 @@ public class QueryResultUtil { ResultSetMetaData metaData = resultSet.getMetaData(); switch (metaData.getColumnType(columnIndex)) { case Types.BIT: + return resultSet.getBytes(columnIndex); case Types.BOOLEAN: return resultSet.getBoolean(columnIndex); case Types.TINYINT: diff --git a/sharding-core/sharding-core-execute/src/test/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultUtilTest.java b/sharding-core/sharding-core-execute/src/test/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultUtilTest.java index 89531decbcc..7d5fc308701 100644 --- a/sharding-core/sharding-core-execute/src/test/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultUtilTest.java +++ b/sharding-core/sharding-core-execute/src/test/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultUtilTest.java @@ -61,8 +61,9 @@ public class QueryResultUtilTest { @SneakyThrows public void assertGetValueByBit() { when(resultSetMetaData.getColumnType(1)).thenReturn(Types.BIT); - when(resultSet.getBoolean(1)).thenReturn(true); - assertTrue((boolean) QueryResultUtil.getValue(resultSet, 1)); + byte[] bytes = {1}; + when(resultSet.getBytes(1)).thenReturn(bytes); + assertThat((byte[]) QueryResultUtil.getValue(resultSet, 1), is(bytes)); } @Test
['sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultUtil.java', 'sharding-core/sharding-core-execute/src/test/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultUtilTest.java']
{'.java': 2}
2
2
0
0
2
2,864,781
575,718
73,500
997
56
7
1
1
198
38
47
1
0
0
1970-01-01T00:25:59
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,482
apache/shardingsphere/2424/2417
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2417
https://github.com/apache/shardingsphere/pull/2424
https://github.com/apache/shardingsphere/pull/2424
1
fixes
Get error index info when use hibernate.hbm2ddl.auto=update
## Version * Spring Boot 2.1.5.RELEASE * ShardingSphere 4.0.0-RC1 * MySQL 5.7 ## Question I have set the option "spring.jpa.properties.hibernate.hbm2ddl.auto=update" config application.yml: ``` datasource: names: ds0, ds1, ds2 # **** sharding: default-data-source-name: ds0 # ... tables: cpn_code: actual-data-nodes: ds$->{1..2}.cpn_code$->{0..9} # ... ``` * Apllication start always send sql **CREATE INDEX idx_cpnId ON cpn_code...** Because Index Name in MySql is 'idx_cpnId_cpn_code0, idx_cpnId_cpn_code2...' , hibernate entity ``` @Entity @Table(name = "cpn_code", indexes = { @Index(name = "idx_cpnId", columnList = "cpnId") }) public class CouponCode { ``` * Sometimes application start fail because got Exception **Cannot find actual data node for data source name: 'ds0' and logic table name: 'cpn_code'** ``` //org.hibernate.tool.schema.internal.GroupedSchemaMigratorImpl#performTablesMigration //org.hibernate.tool.schema.internal.AbstractSchemaMigrator#applyIndexes //org.hibernate.tool.schema.internal.AbstractSchemaMigrator#findMatchingIndex //org.hibernate.tool.schema.extract.internal.TableInformationImpl#getIndex //org.hibernate.tool.schema.extract.internal.TableInformationImpl#indexes //org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl#getIndexes //org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.metadata.ResultSetReturnedDatabaseMetaData#getIndexInfo // when currentDataSourceName is 'ds0' , method getDataNode will throw Exception return null == table || null == shardingRule ? table : (shardingRule.findTableRule(table).isPresent() ? shardingRule.getDataNode(currentDataSourceName, table).getTableName() : table); // so I config actual-data-nodes: ds$->{0..2} to avoid error ```
e298fc8b022e24f5465ee66fbf25c505267a417e
30f895655a2cef66d6506de45daebfcbfa869e62
https://github.com/apache/shardingsphere/compare/e298fc8b022e24f5465ee66fbf25c505267a417e...30f895655a2cef66d6506de45daebfcbfa869e62
diff --git a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/metadata/ResultSetReturnedDatabaseMetaData.java b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/metadata/ResultSetReturnedDatabaseMetaData.java index e029f4baa9e..3db568a57c2 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/metadata/ResultSetReturnedDatabaseMetaData.java +++ b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/metadata/ResultSetReturnedDatabaseMetaData.java @@ -17,6 +17,7 @@ package org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.metadata; +import org.apache.shardingsphere.core.rule.DataNode; import org.apache.shardingsphere.core.rule.ShardingRule; import org.apache.shardingsphere.shardingjdbc.jdbc.adapter.WrapperAdapter; import org.apache.shardingsphere.shardingjdbc.jdbc.core.resultset.DatabaseMetaDataResultSet; @@ -257,7 +258,7 @@ public abstract class ResultSetReturnedDatabaseMetaData extends WrapperAdapter i } private String getCurrentDataSourceName() { - currentDataSourceName = shardingRule.getShardingDataSourceNames().getRandomDataSourceName(); + currentDataSourceName = null == currentDataSourceName ? shardingRule.getShardingDataSourceNames().getRandomDataSourceName() : currentDataSourceName; return shardingRule.getShardingDataSourceNames().getRawMasterDataSourceName(currentDataSourceName); } @@ -266,6 +267,15 @@ public abstract class ResultSetReturnedDatabaseMetaData extends WrapperAdapter i } private String getActualTable(final String table) { - return null == table || null == shardingRule ? table : (shardingRule.findTableRule(table).isPresent() ? shardingRule.getDataNode(currentDataSourceName, table).getTableName() : table); + if (null == table || null == shardingRule) { + return table; + } + String result = table; + if (shardingRule.findTableRule(table).isPresent()) { + DataNode dataNode = shardingRule.getDataNode(table); + currentDataSourceName = dataNode.getDataSourceName(); + result = dataNode.getTableName(); + } + return result; } } diff --git a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/DatabaseMetaDataResultSet.java b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/DatabaseMetaDataResultSet.java index aa4ff31c13c..b71bf21f0a1 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/DatabaseMetaDataResultSet.java +++ b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/DatabaseMetaDataResultSet.java @@ -45,6 +45,8 @@ public final class DatabaseMetaDataResultSet extends AbstractUnsupportedDatabase private static final String TABLE_NAME = "TABLE_NAME"; + private static final String INDEX_NAME = "INDEX_NAME"; + private final int type; private final int concurrency; @@ -82,8 +84,9 @@ public final class DatabaseMetaDataResultSet extends AbstractUnsupportedDatabase ArrayList<DatabaseMetaDataObject> result = Lists.newArrayList(); Set<DatabaseMetaDataObject> removeDuplicationSet = new HashSet<>(); int tableNameColumnIndex = columnLabelIndexMap.containsKey(TABLE_NAME) ? columnLabelIndexMap.get(TABLE_NAME) : -1; + int indexNameColumnIndex = columnLabelIndexMap.containsKey(INDEX_NAME) ? columnLabelIndexMap.get(INDEX_NAME) : -1; while (resultSet.next()) { - DatabaseMetaDataObject databaseMetaDataObject = generateDatabaseMetaDataObject(tableNameColumnIndex, resultSet); + DatabaseMetaDataObject databaseMetaDataObject = generateDatabaseMetaDataObject(tableNameColumnIndex, indexNameColumnIndex, resultSet); if (!removeDuplicationSet.contains(databaseMetaDataObject)) { result.add(databaseMetaDataObject); removeDuplicationSet.add(databaseMetaDataObject); @@ -92,13 +95,17 @@ public final class DatabaseMetaDataResultSet extends AbstractUnsupportedDatabase return result.iterator(); } - private DatabaseMetaDataObject generateDatabaseMetaDataObject(final int tableNameColumnIndex, final ResultSet resultSet) throws SQLException { + private DatabaseMetaDataObject generateDatabaseMetaDataObject(final int tableNameColumnIndex, final int indexNameColumnIndex, final ResultSet resultSet) throws SQLException { DatabaseMetaDataObject result = new DatabaseMetaDataObject(resultSetMetaData.getColumnCount()); for (int i = 1; i <= columnLabelIndexMap.size(); i++) { if (tableNameColumnIndex == i) { String tableName = resultSet.getString(i); Collection<String> logicTableNames = shardingRule.getLogicTableNames(tableName); result.addObject(logicTableNames.isEmpty() ? tableName : logicTableNames.iterator().next()); + } else if (indexNameColumnIndex == i) { + String tableName = resultSet.getString(tableNameColumnIndex); + String indexName = resultSet.getString(i); + result.addObject(indexName.endsWith(tableName) ? indexName.substring(0, indexName.indexOf(tableName) - 1) : indexName); } else { result.addObject(resultSet.getObject(i)); } diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/metadata/CachedDatabaseMetaDataTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/metadata/CachedDatabaseMetaDataTest.java index 47a26a5bcb2..875519df792 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/metadata/CachedDatabaseMetaDataTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/metadata/CachedDatabaseMetaDataTest.java @@ -17,8 +17,10 @@ package org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.metadata; +import org.apache.shardingsphere.core.rule.DataNode; import org.apache.shardingsphere.core.rule.ShardingDataSourceNames; import org.apache.shardingsphere.core.rule.ShardingRule; +import org.apache.shardingsphere.core.rule.TableRule; import org.apache.shardingsphere.shardingjdbc.jdbc.core.resultset.DatabaseMetaDataResultSet; import org.junit.Before; import org.junit.Test; @@ -43,9 +45,15 @@ import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.google.common.base.Optional; + @RunWith(MockitoJUnitRunner.class) public final class CachedDatabaseMetaDataTest { + private final String DATASOURCE_NAME = "ds"; + + private final String TABLE_NAME = "table"; + @Mock private DataSource dataSource; @@ -64,7 +72,7 @@ public final class CachedDatabaseMetaDataTest { @Before public void setUp() throws SQLException { - dataSourceMap.put("ds", dataSource); + dataSourceMap.put(DATASOURCE_NAME, dataSource); when(dataSource.getConnection()).thenReturn(connection); when(connection.getMetaData()).thenReturn(databaseMetaData); when(resultSet.getMetaData()).thenReturn(mock(ResultSetMetaData.class)); @@ -74,9 +82,11 @@ public final class CachedDatabaseMetaDataTest { private ShardingRule mockShardingRule() { ShardingRule result = mock(ShardingRule.class); ShardingDataSourceNames shardingDataSourceNames = mock(ShardingDataSourceNames.class); - when(shardingDataSourceNames.getRandomDataSourceName()).thenReturn("ds"); - when(shardingDataSourceNames.getRawMasterDataSourceName("ds")).thenReturn("ds"); + when(shardingDataSourceNames.getRandomDataSourceName()).thenReturn(DATASOURCE_NAME); + when(shardingDataSourceNames.getRawMasterDataSourceName(DATASOURCE_NAME)).thenReturn(DATASOURCE_NAME); when(result.getShardingDataSourceNames()).thenReturn(shardingDataSourceNames); + when(result.findTableRule(TABLE_NAME)).thenReturn(Optional.of(new TableRule(DATASOURCE_NAME, TABLE_NAME))); + when(result.getDataNode(TABLE_NAME)).thenReturn(new DataNode(DATASOURCE_NAME, TABLE_NAME)); return result; } @@ -938,8 +948,8 @@ public final class CachedDatabaseMetaDataTest { @Test public void assertGetIndexInfo() throws SQLException { - when(databaseMetaData.getIndexInfo("test", null, null, true, true)).thenReturn(resultSet); - assertThat(cachedDatabaseMetaData.getIndexInfo("test", null, null, true, true), instanceOf(DatabaseMetaDataResultSet.class)); + when(databaseMetaData.getIndexInfo("test", null, TABLE_NAME, true, true)).thenReturn(resultSet); + assertThat(cachedDatabaseMetaData.getIndexInfo("test", null, TABLE_NAME, true, true), instanceOf(DatabaseMetaDataResultSet.class)); } @Test diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/DatabaseMetaDataResultSetTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/DatabaseMetaDataResultSetTest.java index d0440a854c3..00030b4a8d0 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/DatabaseMetaDataResultSetTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/DatabaseMetaDataResultSetTest.java @@ -65,6 +65,12 @@ public class DatabaseMetaDataResultSetTest { private static final Date DATE = new Date(System.currentTimeMillis()); + private static final String INDEX_NAME_COLUMN_LABEL = "INDEX_NAME"; + + private static final String ACTUAL_INDEX_NAME = "idx_index_test_table_0"; + + private static final String LOGIC_INDEX_NAME = "idx_index"; + @Mock private ResultSetMetaData resultSetMetaData; @@ -78,12 +84,13 @@ public class DatabaseMetaDataResultSetTest { @SneakyThrows private void mockResultSetMetaData() { - when(resultSetMetaData.getColumnCount()).thenReturn(5); + when(resultSetMetaData.getColumnCount()).thenReturn(6); when(resultSetMetaData.getColumnLabel(1)).thenReturn(TABLE_NAME_COLUMN_LABEL); when(resultSetMetaData.getColumnLabel(2)).thenReturn(NON_TABLE_NAME_COLUMN_LABEL); when(resultSetMetaData.getColumnLabel(3)).thenReturn(NUMBER_COLUMN_LABEL); when(resultSetMetaData.getColumnLabel(4)).thenReturn(BYTES_COLUMN_LABEL); when(resultSetMetaData.getColumnLabel(5)).thenReturn(DATE_COLUMN_LABEL); + when(resultSetMetaData.getColumnLabel(6)).thenReturn(INDEX_NAME_COLUMN_LABEL); } @SneakyThrows @@ -95,6 +102,7 @@ public class DatabaseMetaDataResultSetTest { when(result.getObject(3)).thenReturn(NUMBER); when(result.getObject(4)).thenReturn(BYTES); when(result.getObject(5)).thenReturn(DATE); + when(result.getString(6)).thenReturn(ACTUAL_INDEX_NAME); when(result.getType()).thenReturn(ResultSet.TYPE_FORWARD_ONLY); when(result.getConcurrency()).thenReturn(ResultSet.CONCUR_READ_ONLY); when(result.next()).thenReturn(true, true, false); @@ -131,6 +139,7 @@ public class DatabaseMetaDataResultSetTest { assertThat(databaseMetaDataResultSet.getString(1), is(LOGIC_TABLE_NAME)); assertThat(databaseMetaDataResultSet.getString(2), is("true")); assertThat(databaseMetaDataResultSet.getString(3), is("100")); + assertThat(databaseMetaDataResultSet.getString(6), is(LOGIC_INDEX_NAME)); } @Test @@ -139,6 +148,7 @@ public class DatabaseMetaDataResultSetTest { assertThat(databaseMetaDataResultSet.getString(TABLE_NAME_COLUMN_LABEL), is(LOGIC_TABLE_NAME)); assertThat(databaseMetaDataResultSet.getString(NON_TABLE_NAME_COLUMN_LABEL), is("true")); assertThat(databaseMetaDataResultSet.getString(NUMBER_COLUMN_LABEL), is("100")); + assertThat(databaseMetaDataResultSet.getString(INDEX_NAME_COLUMN_LABEL), is(LOGIC_INDEX_NAME)); } @Test @@ -314,7 +324,7 @@ public class DatabaseMetaDataResultSetTest { @Test(expected = SQLException.class) public void assertGetObjectOutOfIndexRange() throws SQLException { databaseMetaDataResultSet.next(); - databaseMetaDataResultSet.getObject(6); + databaseMetaDataResultSet.getObject(7); } @Test(expected = SQLException.class)
['sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/metadata/ResultSetReturnedDatabaseMetaData.java', 'sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/DatabaseMetaDataResultSetTest.java', 'sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/metadata/CachedDatabaseMetaDataTest.java', 'sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/DatabaseMetaDataResultSet.java']
{'.java': 4}
4
4
0
0
4
2,829,855
568,294
72,587
983
2,027
379
25
2
1,849
153
462
53
0
3
1970-01-01T00:25:58
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,483
apache/shardingsphere/2374/2398
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2398
https://github.com/apache/shardingsphere/pull/2374
https://github.com/apache/shardingsphere/pull/2374
1
fix
Wrong result set for `select between and` when using encrypt data source
## 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? ### Which project did you use? Sharding-JDBC or Sharding-Proxy? ### Expected behavior get correct result set for `select between and` when using encrypt data source ### Actual behavior get wrong result set for `select between and` when using encrypt data source ### Reason analyze (If you can) Actually, when data is encrypted and stored in db, user can not use `select encrypted column between value1 an value2` to get correct result set. The reason is that encrypted data in db is different from the original data. Therefore when ss finds this scenario, it will throw exception. ### 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).
b0be6b29f0cdbd022270cf44b1e48fbbc52ac202
e7623cdfcd1c941acf3e2f9912c60ccf0221d8fd
https://github.com/apache/shardingsphere/compare/b0be6b29f0cdbd022270cf44b1e48fbbc52ac202...e7623cdfcd1c941acf3e2f9912c60ccf0221d8fd
diff --git a/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/SQLJudgeEngine.java b/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/SQLJudgeEngine.java index 8f945a0f9dc..c0ec2bf6ac1 100644 --- a/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/SQLJudgeEngine.java +++ b/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/SQLJudgeEngine.java @@ -179,7 +179,7 @@ public final class SQLJudgeEngine { lexerEngine.nextToken(); if (lexerEngine.skipIfEqual(DefaultKeyword.FROM, DefaultKeyword.IN)) { int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length(); - result.addSQLToken(new SchemaToken(beginPosition, lexerEngine.getCurrentToken().getEndPosition() - 1, null)); + result.addSQLToken(new SchemaToken(beginPosition, lexerEngine.getCurrentToken().getEndPosition() - 1, lexerEngine.getCurrentToken().getLiterals(), null)); } return result; } @@ -188,7 +188,7 @@ public final class SQLJudgeEngine { DALStatement result = new ShowTablesStatement(); if (lexerEngine.skipIfEqual(DefaultKeyword.FROM, DefaultKeyword.IN)) { int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length(); - result.addSQLToken(new SchemaToken(beginPosition, lexerEngine.getCurrentToken().getEndPosition() - 1, null)); + result.addSQLToken(new SchemaToken(beginPosition, lexerEngine.getCurrentToken().getEndPosition() - 1, lexerEngine.getCurrentToken().getLiterals(), null)); } return result; } @@ -199,7 +199,7 @@ public final class SQLJudgeEngine { parseSingleTableWithSchema(lexerEngine, result); if (lexerEngine.skipIfEqual(DefaultKeyword.FROM, DefaultKeyword.IN)) { int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length(); - result.addSQLToken(new SchemaToken(beginPosition, lexerEngine.getCurrentToken().getEndPosition() - 1, null)); + result.addSQLToken(new SchemaToken(beginPosition, lexerEngine.getCurrentToken().getEndPosition() - 1, lexerEngine.getCurrentToken().getLiterals(), null)); } return result; } @@ -216,7 +216,7 @@ public final class SQLJudgeEngine { parseSingleTableWithSchema(lexerEngine, result); if (lexerEngine.skipIfEqual(DefaultKeyword.FROM, DefaultKeyword.IN)) { int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length(); - result.addSQLToken(new SchemaToken(beginPosition, lexerEngine.getCurrentToken().getEndPosition() - 1, null)); + result.addSQLToken(new SchemaToken(beginPosition, lexerEngine.getCurrentToken().getEndPosition() - 1, lexerEngine.getCurrentToken().getLiterals(), null)); } return result; } @@ -225,7 +225,7 @@ public final class SQLJudgeEngine { int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length(); lexerEngine.nextToken(); if (lexerEngine.skipIfEqual(Symbol.DOT)) { - sqlStatement.addSQLToken(new SchemaToken(beginPosition, lexerEngine.getCurrentToken().getEndPosition() - 1, null)); + sqlStatement.addSQLToken(new SchemaToken(beginPosition, lexerEngine.getCurrentToken().getEndPosition() - 1, lexerEngine.getCurrentToken().getLiterals(), null)); lexerEngine.nextToken(); } } diff --git a/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/extractor/impl/common/index/IndexExtractor.java b/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/extractor/impl/common/index/IndexExtractor.java index 74600c2d4f6..d1f2c568a3a 100644 --- a/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/extractor/impl/common/index/IndexExtractor.java +++ b/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/extractor/impl/common/index/IndexExtractor.java @@ -41,6 +41,6 @@ public final class IndexExtractor implements OptionalSQLSegmentExtractor { } private IndexToken getIndexToken(final ParserRuleContext indexNameNode) { - return new IndexToken(indexNameNode.getStart().getStartIndex(), indexNameNode.getStop().getStopIndex()); + return new IndexToken(indexNameNode.getStart().getStartIndex(), indexNameNode.getStop().getStopIndex(), indexNameNode.getText()); } } diff --git a/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/filler/common/dal/SchemaFiller.java b/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/filler/common/dal/SchemaFiller.java index edf45812d25..403654df9d7 100644 --- a/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/filler/common/dal/SchemaFiller.java +++ b/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/filler/common/dal/SchemaFiller.java @@ -37,7 +37,7 @@ public final class SchemaFiller implements SQLSegmentFiller<SchemaSegment> { if (sqlStatement instanceof UseStatement) { ((UseStatement) sqlStatement).setSchema(sqlSegment.getName()); } else if (sqlStatement instanceof ShowColumnsStatement || sqlStatement instanceof ShowIndexStatement) { - sqlStatement.addSQLToken(new SchemaToken(sqlSegment.getStartIndex(), sqlSegment.getStopIndex(), sqlStatement.getTables().getSingleTableName())); + sqlStatement.addSQLToken(new SchemaToken(sqlSegment.getStartIndex(), sqlSegment.getStopIndex(), sqlSegment.getName(), sqlStatement.getTables().getSingleTableName())); } } } diff --git a/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/sql/token/impl/IndexToken.java b/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/sql/token/impl/IndexToken.java index fdfddd36b1e..370bfde9d84 100644 --- a/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/sql/token/impl/IndexToken.java +++ b/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/sql/token/impl/IndexToken.java @@ -20,6 +20,7 @@ package org.apache.shardingsphere.core.parse.sql.token.impl; import lombok.Getter; import lombok.Setter; import lombok.ToString; +import org.apache.shardingsphere.core.parse.constant.QuoteCharacter; import org.apache.shardingsphere.core.parse.sql.token.SQLToken; import org.apache.shardingsphere.core.parse.sql.token.Substitutable; import org.apache.shardingsphere.core.parse.util.SQLUtil; @@ -35,17 +36,23 @@ import org.apache.shardingsphere.core.parse.util.SQLUtil; @ToString public final class IndexToken extends SQLToken implements Substitutable { - private String tableName; + private final String indexName; private final int stopIndex; - public IndexToken(final int startIndex, final int stopIndex) { + private String tableName; + + private final QuoteCharacter quoteCharacter; + + public IndexToken(final int startIndex, final int stopIndex, final String indexName) { super(startIndex); + this.indexName = SQLUtil.getExactlyValue(indexName); this.stopIndex = stopIndex; + quoteCharacter = QuoteCharacter.getQuoteCharacter(indexName); } - public IndexToken(final int startIndex, final int stopIndex, final String tableName) { - this(startIndex, stopIndex); + public IndexToken(final int startIndex, final int stopIndex, final String indexName, final String tableName) { + this(startIndex, stopIndex, indexName); this.tableName = tableName; } diff --git a/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/sql/token/impl/SchemaToken.java b/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/sql/token/impl/SchemaToken.java index 929522e54c1..c1a97ce3407 100644 --- a/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/sql/token/impl/SchemaToken.java +++ b/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/sql/token/impl/SchemaToken.java @@ -19,6 +19,7 @@ package org.apache.shardingsphere.core.parse.sql.token.impl; import lombok.Getter; import lombok.ToString; +import org.apache.shardingsphere.core.parse.constant.QuoteCharacter; import org.apache.shardingsphere.core.parse.sql.token.SQLToken; import org.apache.shardingsphere.core.parse.sql.token.Substitutable; import org.apache.shardingsphere.core.parse.util.SQLUtil; @@ -29,18 +30,24 @@ import org.apache.shardingsphere.core.parse.util.SQLUtil; * @author zhangliang * @author panjuan */ +@Getter @ToString public final class SchemaToken extends SQLToken implements Substitutable { + private final String schemaName; + private final String tableName; - @Getter + private final QuoteCharacter quoteCharacter; + private final int stopIndex; - public SchemaToken(final int startIndex, final int stopIndex, final String tableName) { + public SchemaToken(final int startIndex, final int stopIndex, final String schemaName, final String tableName) { super(startIndex); + this.schemaName = SQLUtil.getExactlyValue(schemaName); this.tableName = tableName; this.stopIndex = stopIndex; + this.quoteCharacter = QuoteCharacter.getQuoteCharacter(schemaName); } /** diff --git a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/engine/MasterSlaveSQLRewriteEngine.java b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/engine/MasterSlaveSQLRewriteEngine.java index 0c5366322b3..38c9306ae05 100644 --- a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/engine/MasterSlaveSQLRewriteEngine.java +++ b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/engine/MasterSlaveSQLRewriteEngine.java @@ -75,8 +75,7 @@ public final class MasterSlaveSQLRewriteEngine implements SQLRewriteEngine { } private void appendSchemaPlaceholder(final SQLBuilder sqlBuilder, final SchemaToken schemaToken, final int count) { - String schemaName = originalSQL.substring(schemaToken.getStartIndex(), schemaToken.getStopIndex() + 1); - sqlBuilder.appendPlaceholder(new SchemaPlaceholder(schemaName.toLowerCase(), schemaToken.getTableName().toLowerCase(), masterSlaveRule, dataSourceMetaData)); + sqlBuilder.appendPlaceholder(new SchemaPlaceholder(schemaToken.getSchemaName().toLowerCase(), schemaToken.getTableName().toLowerCase(), schemaToken.getQuoteCharacter(), masterSlaveRule, dataSourceMetaData)); appendRest(sqlBuilder, count, schemaToken.getStopIndex() + 1); } diff --git a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/engine/ShardingSQLRewriteEngine.java b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/engine/ShardingSQLRewriteEngine.java index 2795cd73e0f..84f1a2936e0 100644 --- a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/engine/ShardingSQLRewriteEngine.java +++ b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/engine/ShardingSQLRewriteEngine.java @@ -211,18 +211,17 @@ public final class ShardingSQLRewriteEngine implements SQLRewriteEngine { } private void appendSchemaPlaceholder(final SQLBuilder sqlBuilder, final SchemaToken schemaToken, final int count) { - String schemaName = originalSQL.substring(schemaToken.getStartIndex(), schemaToken.getStopIndex() + 1); - sqlBuilder.appendPlaceholder(new SchemaPlaceholder(schemaName.toLowerCase(), schemaToken.getTableName().toLowerCase(), shardingRule, dataSourceMetaData)); + sqlBuilder.appendPlaceholder( + new SchemaPlaceholder(schemaToken.getSchemaName().toLowerCase(), schemaToken.getTableName().toLowerCase(), schemaToken.getQuoteCharacter(), shardingRule, dataSourceMetaData)); appendRest(sqlBuilder, count, schemaToken.getStopIndex() + 1); } private void appendIndexPlaceholder(final SQLBuilder sqlBuilder, final IndexToken indexToken, final int count) { - String indexName = originalSQL.substring(indexToken.getStartIndex(), indexToken.getStopIndex() + 1); String logicTableName = indexToken.getTableName().toLowerCase(); if (Strings.isNullOrEmpty(logicTableName)) { - logicTableName = shardingRule.getLogicTableName(indexName); + logicTableName = shardingRule.getLogicTableName(indexToken.getIndexName()); } - sqlBuilder.appendPlaceholder(new IndexPlaceholder(indexName, logicTableName)); + sqlBuilder.appendPlaceholder(new IndexPlaceholder(indexToken.getIndexName(), logicTableName, indexToken.getQuoteCharacter())); appendRest(sqlBuilder, count, indexToken.getStopIndex() + 1); } diff --git a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/placeholder/IndexPlaceholder.java b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/placeholder/IndexPlaceholder.java index fbac3002f4e..e072c71a4d3 100644 --- a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/placeholder/IndexPlaceholder.java +++ b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/placeholder/IndexPlaceholder.java @@ -19,8 +19,8 @@ package org.apache.shardingsphere.core.rewrite.placeholder; import com.google.common.base.Strings; import lombok.Getter; +import lombok.RequiredArgsConstructor; import org.apache.shardingsphere.core.parse.constant.QuoteCharacter; -import org.apache.shardingsphere.core.parse.util.SQLUtil; import org.apache.shardingsphere.core.route.type.RoutingUnit; import java.util.Map; @@ -31,6 +31,7 @@ import java.util.Map; * @author zhangliang * @author panjuan */ +@RequiredArgsConstructor @Getter public final class IndexPlaceholder implements ShardingPlaceholder, Alterable { @@ -40,12 +41,6 @@ public final class IndexPlaceholder implements ShardingPlaceholder, Alterable { private final QuoteCharacter quoteCharacter; - public IndexPlaceholder(final String logicIndexLiteral, final String logicTableName) { - logicIndexName = SQLUtil.getExactlyValue(logicIndexLiteral); - this.logicTableName = logicTableName; - quoteCharacter = QuoteCharacter.getQuoteCharacter(logicIndexLiteral); - } - @Override public String toString(final RoutingUnit routingUnit, final Map<String, String> logicAndActualTables) { StringBuilder result = new StringBuilder(); diff --git a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/placeholder/SchemaPlaceholder.java b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/placeholder/SchemaPlaceholder.java index 62057b2d451..a717ce48e3c 100644 --- a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/placeholder/SchemaPlaceholder.java +++ b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/placeholder/SchemaPlaceholder.java @@ -21,6 +21,7 @@ import com.google.common.base.Strings; import lombok.Getter; import lombok.RequiredArgsConstructor; import org.apache.shardingsphere.core.metadata.datasource.ShardingDataSourceMetaData; +import org.apache.shardingsphere.core.parse.constant.QuoteCharacter; import org.apache.shardingsphere.core.route.type.RoutingUnit; import org.apache.shardingsphere.core.rule.BaseRule; @@ -40,15 +41,16 @@ public final class SchemaPlaceholder implements ShardingPlaceholder, Alterable { private final String logicTableName; + private final QuoteCharacter quoteCharacter; + private final BaseRule baseRule; private final ShardingDataSourceMetaData dataSourceMetaData; @Override public String toString(final RoutingUnit routingUnit, final Map<String, String> logicAndActualTables) { - if (Strings.isNullOrEmpty(logicTableName)) { - return logicTableName; - } - return dataSourceMetaData.getActualDataSourceMetaData(baseRule.getActualDataSourceName(logicAndActualTables.get(logicTableName))).getSchemaName(); + String actualSchemaName = Strings.isNullOrEmpty(logicTableName) + ? logicSchemaName : dataSourceMetaData.getActualDataSourceMetaData(baseRule.getActualDataSourceName(logicAndActualTables.get(logicTableName))).getSchemaName(); + return quoteCharacter.getStartDelimiter() + actualSchemaName + quoteCharacter.getEndDelimiter(); } } diff --git a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/placeholder/WhereEncryptColumnPlaceholder.java b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/placeholder/WhereEncryptColumnPlaceholder.java index d6b42f63ea9..5addadefcec 100644 --- a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/placeholder/WhereEncryptColumnPlaceholder.java +++ b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/placeholder/WhereEncryptColumnPlaceholder.java @@ -47,8 +47,6 @@ public final class WhereEncryptColumnPlaceholder implements ShardingPlaceholder switch (operator) { case EQUAL: return parameterMarkerIndexes.isEmpty() ? String.format("%s = '%s'", columnName, indexValues.get(0)) : String.format("%s = ?", columnName); - case BETWEEN: - return toStringFromBetween(); case IN: return toStringFromIn(); default: @@ -56,19 +54,6 @@ public final class WhereEncryptColumnPlaceholder implements ShardingPlaceholder } } - private String toStringFromBetween() { - if (parameterMarkerIndexes.isEmpty()) { - return String.format("%s %s '%s' AND '%s'", columnName, operator.name(), indexValues.get(0), indexValues.get(1)); - } - if (2 == parameterMarkerIndexes.size()) { - return String.format("%s %s ? AND ?", columnName, operator.name()); - } - if (0 == parameterMarkerIndexes.iterator().next()) { - return String.format("%s %s ? AND '%s'", columnName, operator.name(), indexValues.get(0)); - } - return String.format("%s %s '%s' AND ?", columnName, operator.name(), indexValues.get(0)); - } - private String toStringFromIn() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(columnName).append(" ").append(operator.name()).append(" ("); diff --git a/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/SQLBuilderTest.java b/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/SQLBuilderTest.java index 794788ab886..42be742c835 100644 --- a/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/SQLBuilderTest.java +++ b/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/SQLBuilderTest.java @@ -91,7 +91,7 @@ public final class SQLBuilderTest { public void assertIndexPlaceholderAppendTableWithoutTableToken() { SQLBuilder sqlBuilder = new SQLBuilder(); sqlBuilder.appendLiterals("CREATE INDEX "); - sqlBuilder.appendPlaceholder(new IndexPlaceholder("index_name", "index_name")); + sqlBuilder.appendPlaceholder(new IndexPlaceholder("index_name", "index_name", QuoteCharacter.NONE)); sqlBuilder.appendLiterals(" ON "); sqlBuilder.appendPlaceholder(new TablePlaceholder("table_x", QuoteCharacter.NONE)); sqlBuilder.appendLiterals(" ('column')"); @@ -102,7 +102,7 @@ public final class SQLBuilderTest { public void assertIndexPlaceholderAppendTableWithTableToken() { SQLBuilder sqlBuilder = new SQLBuilder(); sqlBuilder.appendLiterals("CREATE INDEX "); - sqlBuilder.appendPlaceholder(new IndexPlaceholder("index_name", "table_x")); + sqlBuilder.appendPlaceholder(new IndexPlaceholder("index_name", "table_x", QuoteCharacter.NONE)); sqlBuilder.appendLiterals(" ON "); sqlBuilder.appendPlaceholder(new TablePlaceholder("table_x", QuoteCharacter.NONE)); sqlBuilder.appendLiterals(" ('column')"); @@ -118,7 +118,7 @@ public final class SQLBuilderTest { sqlBuilder.appendLiterals("CREATE TABLE "); sqlBuilder.appendPlaceholder(new TablePlaceholder("table_x", QuoteCharacter.NONE)); sqlBuilder.appendLiterals("ON "); - sqlBuilder.appendPlaceholder(new SchemaPlaceholder("dx", "table_x", createShardingRule(), null)); + sqlBuilder.appendPlaceholder(new SchemaPlaceholder("dx", "table_x", QuoteCharacter.NONE, createShardingRule(), null)); sqlBuilder.toSQL(null, Collections.<String, String>emptyMap()); } @@ -129,7 +129,7 @@ public final class SQLBuilderTest { sqlBuilder.appendLiterals("CREATE TABLE "); sqlBuilder.appendPlaceholder(new TablePlaceholder("table_0", QuoteCharacter.NONE)); sqlBuilder.appendLiterals(" ON "); - sqlBuilder.appendPlaceholder(new SchemaPlaceholder("ds0", "table_0", createShardingRule(), shardingDataSourceMetaData)); + sqlBuilder.appendPlaceholder(new SchemaPlaceholder("ds0", "table_0", QuoteCharacter.NONE, createShardingRule(), shardingDataSourceMetaData)); Map<String, String> tableTokens = new HashMap<>(1, 1); tableTokens.put("table_0", "table_1"); // ShardingDataSourceMetaData shardingDataSourceMetaData = Mockito.mock(ShardingDataSourceMetaData.class); @@ -165,7 +165,7 @@ public final class SQLBuilderTest { public void assertIndexPlaceholderAppendTableWithoutTableTokenWithBackQuotes() { SQLBuilder sqlBuilder = new SQLBuilder(); sqlBuilder.appendLiterals("CREATE INDEX "); - sqlBuilder.appendPlaceholder(new IndexPlaceholder("index_name", "index_name")); + sqlBuilder.appendPlaceholder(new IndexPlaceholder("index_name", "index_name", QuoteCharacter.NONE)); sqlBuilder.appendLiterals(" ON "); sqlBuilder.appendPlaceholder(new TablePlaceholder("table_x", QuoteCharacter.BACK_QUOTE)); sqlBuilder.appendLiterals(" ('column')"); @@ -176,7 +176,7 @@ public final class SQLBuilderTest { public void assertIndexPlaceholderAppendTableWithTableTokenWithBackQuotes() { SQLBuilder sqlBuilder = new SQLBuilder(); sqlBuilder.appendLiterals("CREATE INDEX "); - sqlBuilder.appendPlaceholder(new IndexPlaceholder("index_name", "table_x")); + sqlBuilder.appendPlaceholder(new IndexPlaceholder("index_name", "table_x", QuoteCharacter.NONE)); sqlBuilder.appendLiterals(" ON "); sqlBuilder.appendPlaceholder(new TablePlaceholder("table_x", QuoteCharacter.BACK_QUOTE)); sqlBuilder.appendLiterals(" ('column')"); @@ -192,7 +192,7 @@ public final class SQLBuilderTest { sqlBuilder.appendLiterals("CREATE TABLE "); sqlBuilder.appendPlaceholder(new TablePlaceholder("table_0", QuoteCharacter.BACK_QUOTE)); sqlBuilder.appendLiterals(" ON "); - sqlBuilder.appendPlaceholder(new SchemaPlaceholder("ds", "table_0", createShardingRule(), shardingDataSourceMetaData)); + sqlBuilder.appendPlaceholder(new SchemaPlaceholder("ds", "table_0", QuoteCharacter.NONE, createShardingRule(), shardingDataSourceMetaData)); Map<String, String> tableTokens = new HashMap<>(1, 1); tableTokens.put("table_0", "table_1"); assertThat(sqlBuilder.toSQL(null, tableTokens).getSql(), is("SHOW CREATE TABLE `table_1` ON actual_db")); @@ -226,7 +226,7 @@ public final class SQLBuilderTest { public void assertIndexPlaceholderAppendTableWithoutTableTokenWithDoubleQuotes() { SQLBuilder sqlBuilder = new SQLBuilder(); sqlBuilder.appendLiterals("CREATE INDEX "); - sqlBuilder.appendPlaceholder(new IndexPlaceholder("index_name", "index_name")); + sqlBuilder.appendPlaceholder(new IndexPlaceholder("index_name", "index_name", QuoteCharacter.NONE)); sqlBuilder.appendLiterals(" ON "); sqlBuilder.appendPlaceholder(new TablePlaceholder("table_x", QuoteCharacter.QUOTE)); sqlBuilder.appendLiterals(" ('column')"); @@ -237,7 +237,7 @@ public final class SQLBuilderTest { public void assertIndexPlaceholderAppendTableWithTableTokenWithDoubleQuotes() { SQLBuilder sqlBuilder = new SQLBuilder(); sqlBuilder.appendLiterals("CREATE INDEX "); - sqlBuilder.appendPlaceholder(new IndexPlaceholder("index_name", "table_x")); + sqlBuilder.appendPlaceholder(new IndexPlaceholder("index_name", "table_x", QuoteCharacter.NONE)); sqlBuilder.appendLiterals(" ON "); sqlBuilder.appendPlaceholder(new TablePlaceholder("table_x", QuoteCharacter.QUOTE)); sqlBuilder.appendLiterals(" ('column')"); @@ -253,7 +253,7 @@ public final class SQLBuilderTest { sqlBuilder.appendLiterals("CREATE TABLE "); sqlBuilder.appendPlaceholder(new TablePlaceholder("table_0", QuoteCharacter.QUOTE)); sqlBuilder.appendLiterals(" ON "); - sqlBuilder.appendPlaceholder(new SchemaPlaceholder("ds", "table_0", createShardingRule(), shardingDataSourceMetaData)); + sqlBuilder.appendPlaceholder(new SchemaPlaceholder("ds", "table_0", QuoteCharacter.NONE, createShardingRule(), shardingDataSourceMetaData)); Map<String, String> tableTokens = new HashMap<>(1, 1); tableTokens.put("table_0", "table_1"); assertThat(sqlBuilder.toSQL(null, tableTokens).getSql(), is("SHOW CREATE TABLE \\"table_1\\" ON actual_db")); @@ -261,7 +261,7 @@ public final class SQLBuilderTest { @Test public void assertShardingPlaceholderToString() { - assertThat(new IndexPlaceholder("index_name", "table_x").toString(null, Collections.<String, String>emptyMap()), is("index_name")); + assertThat(new IndexPlaceholder("index_name", "table_x", QuoteCharacter.NONE).toString(null, Collections.<String, String>emptyMap()), is("index_name")); assertThat(new TablePlaceholder("table_name", QuoteCharacter.BACK_QUOTE).toString(null, Collections.<String, String>emptyMap()), is("`table_name`")); } diff --git a/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/engine/ShardingSQLRewriteEngineTest.java b/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/engine/ShardingSQLRewriteEngineTest.java index 28393c2ed69..8d38f632ddc 100644 --- a/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/engine/ShardingSQLRewriteEngineTest.java +++ b/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/engine/ShardingSQLRewriteEngineTest.java @@ -550,7 +550,7 @@ public final class ShardingSQLRewriteEngineTest { tableTokens = new HashMap<>(1, 1); tableTokens.put("table_x", "table_y"); selectStatement.addSQLToken(new TableToken(18, 24, "table_x", QuoteCharacter.NONE)); - selectStatement.addSQLToken(new SchemaToken(29, 35, "table_x")); + selectStatement.addSQLToken(new SchemaToken(29, 35, "db0", "table_x")); routeResult = new SQLRouteResult(selectStatement); routeResult.setLimit(selectStatement.getLimit()); routeResult.setRoutingResult(new RoutingResult()); @@ -561,7 +561,7 @@ public final class ShardingSQLRewriteEngineTest { @Test public void assertIndexTokenForIndexNameTableName() { - selectStatement.addSQLToken(new IndexToken(13, 22, "table_x")); + selectStatement.addSQLToken(new IndexToken(13, 22, "index_name", "table_x")); selectStatement.addSQLToken(new TableToken(27, 33, "table_x", QuoteCharacter.NONE)); routeResult = new SQLRouteResult(selectStatement); routeResult.setLimit(selectStatement.getLimit()); @@ -573,7 +573,7 @@ public final class ShardingSQLRewriteEngineTest { @Test public void assertIndexTokenForIndexNameTableNameWithoutLogicTableName() { - selectStatement.addSQLToken(new IndexToken(13, 23, "")); + selectStatement.addSQLToken(new IndexToken(13, 23, "logic_index", "table_x")); selectStatement.addSQLToken(new TableToken(28, 34, "table_x", QuoteCharacter.NONE)); routeResult = new SQLRouteResult(selectStatement); routeResult.setLimit(selectStatement.getLimit()); @@ -598,7 +598,7 @@ public final class ShardingSQLRewriteEngineTest { @Test public void assertTableTokenWithoutBackQuoteFromSchemaForShow() { showTablesStatement.addSQLToken(new TableToken(18, 24, "table_x", QuoteCharacter.NONE)); - showTablesStatement.addSQLToken(new SchemaToken(31, 43, "table_x")); + showTablesStatement.addSQLToken(new SchemaToken(31, 43, "db0", "table_x")); routeResult = new SQLRouteResult(showTablesStatement); RoutingResult routingResult = new RoutingResult(); routingResult.getRoutingUnits().add(new RoutingUnit("ds")); @@ -771,22 +771,6 @@ public final class ShardingSQLRewriteEngineTest { assertThat(parameters.get(0), is((Object) "encryptValue")); } - @Test - public void assertSelectBetweenWithShardingEncryptor() { - Column column = new Column("id", "table_z"); - selectStatement.addSQLToken(new TableToken(15, 21, "table_z", QuoteCharacter.NONE)); - selectStatement.addSQLToken(new EncryptColumnToken(29, 46, column, true)); - selectStatement.getEncryptCondition().getOrConditions().add(new AndCondition()); - selectStatement.getEncryptCondition().getOrConditions().get(0).getConditions().add(new Condition(column, new SQLNumberExpression(3), new SQLNumberExpression(5))); - routeResult = new SQLRouteResult(selectStatement); - routeResult.setLimit(selectStatement.getLimit()); - routeResult.setRoutingResult(new RoutingResult()); - ShardingSQLRewriteEngine rewriteEngine = new ShardingSQLRewriteEngine(shardingRule, - "SELECT id FROM table_z WHERE id between 3 and 5", DatabaseType.MySQL, routeResult, new LinkedList<>(), shardingDataSourceMetaData); - assertThat(rewriteEngine.rewrite().toSQL(null, tableTokens).getSql(), - is("SELECT id FROM table_z WHERE id BETWEEN 'encryptValue' AND 'encryptValue'")); - } - @Test public void assertSelectInWithShardingEncryptor() { Column column = new Column("id", "table_z"); @@ -886,27 +870,4 @@ public final class ShardingSQLRewriteEngineTest { assertThat(rewriteEngine.rewrite().toSQL(null, tableTokens).getSql(), is("UPDATE table_z SET id = 'encryptValue' WHERE id = 'encryptValue'")); } - - @Test - public void assertUpdateWithQueryAssistedShardingEncryptor() { - List<Object> parameters = new ArrayList<>(2); - parameters.add(1); - parameters.add(5); - Column column = new Column("id", "table_k"); - updateStatement.addSQLToken(new TableToken(7, 13, "table_k", QuoteCharacter.NONE)); - updateStatement.addSQLToken(new EncryptColumnToken(19, 24, column, false)); - updateStatement.getAssignments().put(column, new SQLParameterMarkerExpression(0)); - updateStatement.addSQLToken(new EncryptColumnToken(32, 49, column, true)); - updateStatement.getEncryptCondition().getOrConditions().add(new AndCondition()); - updateStatement.getEncryptCondition().getOrConditions().get(0).getConditions().add(new Condition(column, new SQLNumberExpression(3), new SQLParameterMarkerExpression(1))); - routeResult = new SQLRouteResult(updateStatement); - routeResult.setRoutingResult(new RoutingResult()); - ShardingSQLRewriteEngine rewriteEngine = new ShardingSQLRewriteEngine(shardingRule, - "UPDATE table_k SET id = ? WHERE id between 3 and ?", DatabaseType.MySQL, routeResult, parameters, shardingDataSourceMetaData); - assertThat(rewriteEngine.rewrite().toSQL(null, tableTokens).getSql(), - is("UPDATE table_k SET id = ?, query_id = ? WHERE query_id BETWEEN 'assistedEncryptValue' AND ?")); - assertThat(parameters.get(0), is((Object) "encryptValue")); - assertThat(parameters.get(1), is((Object) "assistedEncryptValue")); - assertThat(parameters.get(1), is((Object) "assistedEncryptValue")); - } } diff --git a/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/placeholder/WhereEncryptColumnPlaceholderTest.java b/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/placeholder/WhereEncryptColumnPlaceholderTest.java index 1bccadb63e1..4d276d9aa5d 100644 --- a/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/placeholder/WhereEncryptColumnPlaceholderTest.java +++ b/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/placeholder/WhereEncryptColumnPlaceholderTest.java @@ -17,7 +17,6 @@ package org.apache.shardingsphere.core.rewrite.placeholder; -import com.google.common.collect.Lists; import org.apache.shardingsphere.core.constant.ShardingOperator; import org.junit.Before; import org.junit.Test; @@ -55,37 +54,6 @@ public class WhereEncryptColumnPlaceholderTest { assertThat(whereEncryptColumnPlaceholder.toString(), is("column_x = ?")); } - @Test - public void assertToStringWithoutPlaceholderWithBetween() { - Map<Integer, Comparable<?>> indexValues = new LinkedHashMap<>(); - indexValues.put(0, "a"); - indexValues.put(1, "b"); - whereEncryptColumnPlaceholder = new WhereEncryptColumnPlaceholder("column_x", indexValues, Collections.<Integer>emptyList(), ShardingOperator.BETWEEN); - assertThat(whereEncryptColumnPlaceholder.toString(), is("column_x BETWEEN 'a' AND 'b'")); - } - - @Test - public void assertToStringWithFirstPlaceholderWithBetween() { - Map<Integer, Comparable<?>> indexValues = new LinkedHashMap<>(); - indexValues.put(0, "a"); - whereEncryptColumnPlaceholder = new WhereEncryptColumnPlaceholder("column_x", indexValues, Collections.singletonList(1), ShardingOperator.BETWEEN); - assertThat(whereEncryptColumnPlaceholder.toString(), is("column_x BETWEEN 'a' AND ?")); - } - - @Test - public void assertToStringWithSecondPlaceholderWithBetween() { - Map<Integer, Comparable<?>> indexValues = new LinkedHashMap<>(); - indexValues.put(0, "a"); - whereEncryptColumnPlaceholder = new WhereEncryptColumnPlaceholder("column_x", indexValues, Collections.singletonList(0), ShardingOperator.BETWEEN); - assertThat(whereEncryptColumnPlaceholder.toString(), is("column_x BETWEEN ? AND 'a'")); - } - - @Test - public void assertToStringWithTwoPlaceholderWithBetween() { - whereEncryptColumnPlaceholder = new WhereEncryptColumnPlaceholder("column_x", Collections.<Integer, Comparable<?>>emptyMap(), Lists.newArrayList(0, 1), ShardingOperator.BETWEEN); - assertThat(whereEncryptColumnPlaceholder.toString(), is("column_x BETWEEN ? AND ?")); - } - @Test public void assertToStringWithoutPlaceholderWithIn() { Map<Integer, Comparable<?>> indexValues = new LinkedHashMap<>(); diff --git a/sharding-core/sharding-core-route/src/test/java/org/apache/shardingsphere/core/route/type/broadcast/TableBroadcastRoutingEngineTest.java b/sharding-core/sharding-core-route/src/test/java/org/apache/shardingsphere/core/route/type/broadcast/TableBroadcastRoutingEngineTest.java index 2d49b498bd3..7f50bdccd4f 100644 --- a/sharding-core/sharding-core-route/src/test/java/org/apache/shardingsphere/core/route/type/broadcast/TableBroadcastRoutingEngineTest.java +++ b/sharding-core/sharding-core-route/src/test/java/org/apache/shardingsphere/core/route/type/broadcast/TableBroadcastRoutingEngineTest.java @@ -87,7 +87,7 @@ public final class TableBroadcastRoutingEngineTest { private RoutingResult createDDLStatementRoutingResult() { DDLStatement ddlStatement = new DDLStatement(); ddlStatement.setLogicSQL("CREATE INDEX t_order_index on t_order"); - ddlStatement.addSQLToken(new IndexToken(13, 25, "t_order")); + ddlStatement.addSQLToken(new IndexToken(13, 25, "t_order_index", "t_order")); TableBroadcastRoutingEngine tableBroadcastRoutingEngine = new TableBroadcastRoutingEngine(shardingRule, ddlStatement); return tableBroadcastRoutingEngine.route(); }
['sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/sql/token/impl/SchemaToken.java', 'sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/placeholder/WhereEncryptColumnPlaceholderTest.java', 'sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/sql/token/impl/IndexToken.java', 'sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/SQLBuilderTest.java', 'sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/placeholder/WhereEncryptColumnPlaceholder.java', 'sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/extractor/impl/common/index/IndexExtractor.java', 'sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/placeholder/IndexPlaceholder.java', 'sharding-core/sharding-core-route/src/test/java/org/apache/shardingsphere/core/route/type/broadcast/TableBroadcastRoutingEngineTest.java', 'sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/placeholder/SchemaPlaceholder.java', 'sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/engine/MasterSlaveSQLRewriteEngine.java', 'sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/SQLJudgeEngine.java', 'sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/engine/ShardingSQLRewriteEngine.java', 'sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/engine/ShardingSQLRewriteEngineTest.java', 'sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/filler/common/dal/SchemaFiller.java']
{'.java': 14}
14
14
0
0
14
2,902,562
584,510
74,812
1,006
6,817
1,308
86
10
1,425
206
304
29
2
0
1970-01-01T00:25:57
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,485
apache/shardingsphere/2330/2329
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2329
https://github.com/apache/shardingsphere/pull/2330
https://github.com/apache/shardingsphere/pull/2330
1
fixes
The SQL of `insert set` can not run well when sharding
## 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-RC1 ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-JDBC ### Expected behavior `insert into t_order set order_id =1, user_id =1; ` can run well. ### Actual behavior throw exception: > ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'org.apache.shardingsphere.core.rewrite.placeholder.InsertSetPlaceholder@2f60192a' ### Reason analyze (If you can) SQLBuilder does not handle `InsertSetPlaceholder`. ### 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).
29120e83d4b03580495d5a9965174775c6183455
34caf8df7aaee032d6a7125084e0f75cf28c758c
https://github.com/apache/shardingsphere/compare/29120e83d4b03580495d5a9965174775c6183455...34caf8df7aaee032d6a7125084e0f75cf28c758c
diff --git a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java index 468b450962a..221a2cbf223 100644 --- a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java +++ b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java @@ -114,6 +114,8 @@ public final class SQLBuilder { appendIndexPlaceholder((IndexPlaceholder) each, actualTableName, result); } else if (each instanceof InsertValuesPlaceholder) { appendInsertValuesPlaceholder(tableUnit, (InsertValuesPlaceholder) each, insertParameters, result); + } else if (each instanceof InsertSetPlaceholder) { + appendInsertSetPlaceholder(tableUnit, (InsertSetPlaceholder) each, insertParameters, result); } else { result.append(each); }
['sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java']
{'.java': 1}
1
1
0
0
1
3,275,216
662,046
82,821
1,133
174
32
2
1
1,379
182
316
30
2
0
1970-01-01T00:25:57
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,486
apache/shardingsphere/2323/2312
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2312
https://github.com/apache/shardingsphere/pull/2323
https://github.com/apache/shardingsphere/pull/2323
1
fixes
If there is quoteCharacter for index name, sql can not be executed
## 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-RC1 ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-Proxy ### Expected behavior The following SQL can be executed correctly. ``` CREATE TABLE `t_order` ( `order_id` varchar(100) NOT NULL, `user_id` varchar(100) DEFAULT NULL, `status` varchar(45) DEFAULT NULL, PRIMARY KEY (`order_id`), KEY `order_index_t_order` (`order_id`) ) DEFAULT CHARSET=utf8; ``` ### Actual behavior An exception is thrown. ``` ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '_t_order_0 (`order_id`) ) DEFAULT CHARSET=utf8' at line 1 ``` ### Reason analyze (If you can) The rewritten SQL is not correct: > CREATE TABLE `t_order_0` ( `order_id` varchar(100) NOT NULL, `user_id` varchar(100) DEFAULT NULL, `status` varchar(45) DEFAULT NULL, PRIMARY KEY (`order_id`), KEY \\`order_index_t_order\\`_t_order_0 (\\`order_id\\`) ) DEFAULT CHARSET=utf8 The related code is: In SQLRewriteEngine class: ``` private void appendIndexPlaceholder(final SQLBuilder sqlBuilder, final IndexToken indexToken, final int count) { String indexName = originalSQL.substring(indexToken.getStartIndex(), indexToken.getStopIndex() + 1); String logicTableName = indexToken.getTableName().toLowerCase(); if (Strings.isNullOrEmpty(logicTableName)) { logicTableName = shardingRule.getLogicTableName(indexName); } sqlBuilder.appendPlaceholder(new IndexPlaceholder(indexName, logicTableName)); appendRest(sqlBuilder, count, indexToken.getStopIndex() + 1); } ``` ### 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).
e5f9dea2c3e002c1b7d0f24cc1cbccea652c9eb6
3c0802d8535a4fb216e762455da7234108c1e64f
https://github.com/apache/shardingsphere/compare/e5f9dea2c3e002c1b7d0f24cc1cbccea652c9eb6...3c0802d8535a4fb216e762455da7234108c1e64f
diff --git a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java index c7fd883b2cd..468b450962a 100644 --- a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java +++ b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java @@ -174,17 +174,11 @@ public final class SQLBuilder { } private void appendIndexPlaceholder(final IndexPlaceholder placeholder, final String actualTableName, final StringBuilder stringBuilder) { - stringBuilder.append(placeholder.getLogicIndexName()); - if (!Strings.isNullOrEmpty(actualTableName)) { - if ('`' == stringBuilder.charAt(stringBuilder.length() - 1)) { - stringBuilder.deleteCharAt(stringBuilder.length() - 1); - stringBuilder.append("_"); - stringBuilder.append(actualTableName); - stringBuilder.append("`"); - } else { - stringBuilder.append("_"); - stringBuilder.append(actualTableName); - } + if (Strings.isNullOrEmpty(actualTableName)) { + stringBuilder.append(placeholder.getQuoteCharacter().getStartDelimiter()).append(placeholder.getLogicIndexName()).append(placeholder.getQuoteCharacter().getEndDelimiter()); + } else { + stringBuilder.append(placeholder.getQuoteCharacter().getStartDelimiter()) + .append(placeholder.getLogicIndexName()).append("_").append(actualTableName).append(placeholder.getQuoteCharacter().getEndDelimiter()); } } diff --git a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/placeholder/IndexPlaceholder.java b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/placeholder/IndexPlaceholder.java index b6a1b831f57..cb29ab440e5 100644 --- a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/placeholder/IndexPlaceholder.java +++ b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/placeholder/IndexPlaceholder.java @@ -18,14 +18,15 @@ package org.apache.shardingsphere.core.rewrite.placeholder; import lombok.Getter; -import lombok.RequiredArgsConstructor; +import org.apache.shardingsphere.core.parse.antlr.constant.QuoteCharacter; +import org.apache.shardingsphere.core.parse.util.SQLUtil; /** * Index placeholder for rewrite. * * @author zhangliang + * @author panjuan */ -@RequiredArgsConstructor @Getter public final class IndexPlaceholder implements ShardingPlaceholder { @@ -33,6 +34,14 @@ public final class IndexPlaceholder implements ShardingPlaceholder { private final String logicTableName; + private final QuoteCharacter quoteCharacter; + + public IndexPlaceholder(final String logicIndexLiteral, final String logicTableName) { + logicIndexName = SQLUtil.getExactlyValue(logicIndexLiteral); + this.logicTableName = logicTableName; + quoteCharacter = QuoteCharacter.getQuoteCharacter(logicIndexLiteral); + } + @Override public String toString() { return logicIndexName;
['sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/placeholder/IndexPlaceholder.java', 'sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java']
{'.java': 2}
2
2
0
0
2
3,276,235
662,267
82,843
1,133
1,633
281
29
2
2,491
289
590
51
2
3
1970-01-01T00:25:57
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,487
apache/shardingsphere/2322/2252
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2252
https://github.com/apache/shardingsphere/pull/2322
https://github.com/apache/shardingsphere/pull/2322
1
fixes
insert with generated keys,when the last column value is null,cause NullPointerException
sharding-jdbc <version>4.0.0-RC1</version> <sharding:key-generator id="xxxxxx" type="SNOWFLAKE" column="id" /> useGeneratedKeys,when insert sql the last column value is null,cause NullPointerException when update the last column,success! exception: Caused by: java.lang.NullPointerException at org.apache.shardingsphere.core.route.type.standard.StandardRoutingEngine.isQualifiedInsertOptimizeResult(StandardRoutingEngine.java:221) at org.apache.shardingsphere.core.route.type.standard.StandardRoutingEngine.reviseInsertOptimizeResult(StandardRoutingEngine.java:211) at org.apache.shardingsphere.core.route.type.standard.StandardRoutingEngine.routeByShardingConditionsWithCondition(StandardRoutingEngine.java:110) at org.apache.shardingsphere.core.route.type.standard.StandardRoutingEngine.routeByShardingConditions(StandardRoutingEngine.java:102) at org.apache.shardingsphere.core.route.type.standard.StandardRoutingEngine.getDataNodes(StandardRoutingEngine.java:87) at org.apache.shardingsphere.core.route.type.standard.StandardRoutingEngine.route(StandardRoutingEngine.java:69) at org.apache.shardingsphere.core.route.router.sharding.ParsingSQLRouter.route(ParsingSQLRouter.java:106) at org.apache.shardingsphere.core.route.PreparedStatementRoutingEngine.route(PreparedStatementRoutingEngine.java:66) at org.apache.shardingsphere.core.PreparedQueryShardingEngine.route(PreparedQueryShardingEngine.java:60) at org.apache.shardingsphere.core.BaseShardingEngine.shard(BaseShardingEngine.java:64) at org.apache.shardingsphere.shardingjdbc.jdbc.core.statement.ShardingPreparedStatement.shard(ShardingPreparedStatement.java:224) at org.apache.shardingsphere.shardingjdbc.jdbc.core.statement.ShardingPreparedStatement.execute(ShardingPreparedStatement.java:170) at org.apache.ibatis.executor.statement.PreparedStatementHandler.update(PreparedStatementHandler.java:45) at org.apache.ibatis.executor.statement.RoutingStatementHandler.update(RoutingStatementHandler.java:73) at org.apache.ibatis.executor.SimpleExecutor.doUpdate(SimpleExecutor.java:49) at org.apache.ibatis.executor.BaseExecutor.update(BaseExecutor.java:115) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.apache.ibatis.plugin.Invocation.proceed(Invocation.java:49) at cn.uce.core.db.interceptor.BatchUpdateExecutorInterceptor.intercept(BatchUpdateExecutorInterceptor.java:79) at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:61) at com.sun.proxy.$Proxy40.update(Unknown Source) at org.apache.ibatis.executor.CachingExecutor.update(CachingExecutor.java:75) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:63) at com.sun.proxy.$Proxy40.update(Unknown Source) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:63) at com.sun.proxy.$Proxy40.update(Unknown Source) at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:170)
3d5d62647549560806c01b466c4185160339ddf2
426930a63eed3a0892f397ce822e5f2dc85725c6
https://github.com/apache/shardingsphere/compare/3d5d62647549560806c01b466c4185160339ddf2...426930a63eed3a0892f397ce822e5f2dc85725c6
diff --git a/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/engine/encrypt/EncryptInsertOptimizeEngine.java b/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/engine/encrypt/EncryptInsertOptimizeEngine.java index 886f9cc7424..f9f70c6e5ce 100644 --- a/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/engine/encrypt/EncryptInsertOptimizeEngine.java +++ b/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/engine/encrypt/EncryptInsertOptimizeEngine.java @@ -61,7 +61,7 @@ public final class EncryptInsertOptimizeEngine implements OptimizeEngine { SQLExpression[] currentColumnValues = createCurrentColumnValues(each); Object[] currentParameters = createCurrentParameters(parametersCount, each); parametersCount = parametersCount + each.getParametersCount(); - insertOptimizeResult.addUnit(currentColumnValues, currentParameters); + insertOptimizeResult.addUnit(currentColumnValues, currentParameters, each.getParametersCount()); if (isNeededToAppendQueryAssistedColumn()) { fillWithQueryAssistedColumn(insertOptimizeResult, insertOptimizeResultIndex); } diff --git a/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/engine/sharding/insert/InsertOptimizeEngine.java b/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/engine/sharding/insert/InsertOptimizeEngine.java index dbb95eca66f..78f712f4e9b 100644 --- a/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/engine/sharding/insert/InsertOptimizeEngine.java +++ b/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/engine/sharding/insert/InsertOptimizeEngine.java @@ -77,7 +77,7 @@ public final class InsertOptimizeEngine implements OptimizeEngine { Object[] currentParameters = createCurrentParameters(parametersCount, insertValue); parametersCount = parametersCount + insertValue.getParametersCount(); ShardingCondition shardingCondition = createShardingCondition(andConditions.get(i)); - insertOptimizeResult.addUnit(currentColumnValues, currentParameters); + insertOptimizeResult.addUnit(currentColumnValues, currentParameters, insertValue.getParametersCount()); if (isNeededToAppendGeneratedKey()) { Comparable<?> currentGeneratedKey = generatedKeys.next(); fillWithGeneratedKeyName(insertOptimizeResult); diff --git a/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/insert/ColumnValueOptimizeResult.java b/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/insert/ColumnValueOptimizeResult.java index 3bc8fa7156c..0b2dbbe74c7 100644 --- a/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/insert/ColumnValueOptimizeResult.java +++ b/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/insert/ColumnValueOptimizeResult.java @@ -29,8 +29,8 @@ import java.util.Collection; */ public final class ColumnValueOptimizeResult extends InsertOptimizeResultUnit { - public ColumnValueOptimizeResult(final Collection<String> columnNames, final SQLExpression[] values, final Object[] parameters) { - super(columnNames, values, parameters); + public ColumnValueOptimizeResult(final Collection<String> columnNames, final SQLExpression[] values, final Object[] parameters, final int startIndexOfAppendedParameters) { + super(columnNames, values, parameters, startIndexOfAppendedParameters); } @Override diff --git a/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/insert/InsertOptimizeResult.java b/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/insert/InsertOptimizeResult.java index 4e6c6c92057..ff34c0accf4 100644 --- a/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/insert/InsertOptimizeResult.java +++ b/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/insert/InsertOptimizeResult.java @@ -49,12 +49,13 @@ public final class InsertOptimizeResult { * * @param columnValues column values * @param columnParameters column parameters + * @param startIndexOfAppendedParameters start index of appended parameters */ - public void addUnit(final SQLExpression[] columnValues, final Object[] columnParameters) { + public void addUnit(final SQLExpression[] columnValues, final Object[] columnParameters, final int startIndexOfAppendedParameters) { if (type == InsertType.VALUES) { - this.units.add(new ColumnValueOptimizeResult(columnNames, columnValues, columnParameters)); + this.units.add(new ColumnValueOptimizeResult(columnNames, columnValues, columnParameters, startIndexOfAppendedParameters)); } else { - this.units.add(new SetAssignmentOptimizeResult(columnNames, columnValues, columnParameters)); + this.units.add(new SetAssignmentOptimizeResult(columnNames, columnValues, columnParameters, startIndexOfAppendedParameters)); } } } diff --git a/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/insert/InsertOptimizeResultUnit.java b/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/insert/InsertOptimizeResultUnit.java index 6b03e7de6d7..6f5f8ea7c6e 100644 --- a/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/insert/InsertOptimizeResultUnit.java +++ b/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/insert/InsertOptimizeResultUnit.java @@ -48,6 +48,8 @@ public abstract class InsertOptimizeResultUnit { private final Object[] parameters; + private final int startIndexOfAppendedParameters; + private final List<DataNode> dataNodes = new LinkedList<>(); /** @@ -56,26 +58,25 @@ public abstract class InsertOptimizeResultUnit { * @param sqlExpression SQL expression */ public final void addColumnValue(final SQLExpression sqlExpression) { - values[getCurrentIndex(values)] = sqlExpression; + values[getCurrentIndex(values, 0)] = sqlExpression; } /** * Add column parameter. * - * @param parameter parameter + * @param parameter parameter */ public final void addColumnParameter(final Object parameter) { - parameters[getCurrentIndex(parameters)] = parameter; + parameters[getCurrentIndex(parameters, startIndexOfAppendedParameters)] = parameter; } - private int getCurrentIndex(final Object[] array) { - int count = 0; - for (Object each : array) { - if (null != each) { - count++; + private int getCurrentIndex(final Object[] array, final int startIndex) { + for (int i = startIndex; i < array.length; i++) { + if (null == array[i]) { + return i; } } - return count; + throw new ShardingException("Index Out Of Bounds For InsertOptimizeResultUnit."); } /** diff --git a/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/insert/SetAssignmentOptimizeResult.java b/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/insert/SetAssignmentOptimizeResult.java index bba0a7163fc..7ddf5b26189 100644 --- a/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/insert/SetAssignmentOptimizeResult.java +++ b/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/insert/SetAssignmentOptimizeResult.java @@ -30,8 +30,8 @@ import java.util.Collection; */ public final class SetAssignmentOptimizeResult extends InsertOptimizeResultUnit { - public SetAssignmentOptimizeResult(final Collection<String> columnNames, final SQLExpression[] values, final Object[] parameters) { - super(columnNames, values, parameters); + public SetAssignmentOptimizeResult(final Collection<String> columnNames, final SQLExpression[] values, final Object[] parameters, final int startIndexOfAppendedParameters) { + super(columnNames, values, parameters, startIndexOfAppendedParameters); } @Override diff --git a/sharding-core/sharding-core-optimize/src/test/java/org/apache/shardingsphere/core/optimize/result/InsertOptimizeResultTest.java b/sharding-core/sharding-core-optimize/src/test/java/org/apache/shardingsphere/core/optimize/result/InsertOptimizeResultTest.java index 62b5a867ac0..cc88f872124 100644 --- a/sharding-core/sharding-core-optimize/src/test/java/org/apache/shardingsphere/core/optimize/result/InsertOptimizeResultTest.java +++ b/sharding-core/sharding-core-optimize/src/test/java/org/apache/shardingsphere/core/optimize/result/InsertOptimizeResultTest.java @@ -39,7 +39,7 @@ public final class InsertOptimizeResultTest { public void assertAddUnitWithSet() { SQLExpression[] expressions = {new SQLNumberExpression(1), new SQLParameterMarkerExpression(1), new SQLTextExpression("test")}; Object[] parameters = {"parameter"}; - setInsertOptimizeResult.addUnit(expressions, parameters); + setInsertOptimizeResult.addUnit(expressions, parameters, 1); assertThat(setInsertOptimizeResult.getColumnNames().size(), is(3)); assertThat(setInsertOptimizeResult.getType(), is(InsertType.SET)); assertThat(setInsertOptimizeResult.getUnits().get(0).getValues(), is(expressions)); @@ -58,7 +58,7 @@ public final class InsertOptimizeResultTest { public void assertAddUnitWithValues() { SQLExpression[] expressions = {new SQLNumberExpression(1), new SQLParameterMarkerExpression(1), new SQLTextExpression("test")}; Object[] parameters = {"parameter"}; - valuesInsertOptimizeResult.addUnit(expressions, parameters); + valuesInsertOptimizeResult.addUnit(expressions, parameters, 1); assertThat(valuesInsertOptimizeResult.getUnits().get(0).toString(), is("(1, ?, 'test')")); } } diff --git a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/EncryptSQLRewriteEngine.java b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/EncryptSQLRewriteEngine.java index 523021e1f9a..e5f225e2c58 100644 --- a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/EncryptSQLRewriteEngine.java +++ b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/EncryptSQLRewriteEngine.java @@ -48,6 +48,7 @@ import org.apache.shardingsphere.core.rewrite.placeholder.EncryptUpdateItemColum import org.apache.shardingsphere.core.rewrite.placeholder.EncryptWhereColumnPlaceholder; import org.apache.shardingsphere.core.rewrite.placeholder.InsertSetPlaceholder; import org.apache.shardingsphere.core.rewrite.placeholder.InsertValuesPlaceholder; +import org.apache.shardingsphere.core.rewrite.placeholder.SelectItemsPlaceholder; import org.apache.shardingsphere.core.rewrite.placeholder.ShardingPlaceholder; import org.apache.shardingsphere.core.rule.EncryptRule; import org.apache.shardingsphere.spi.encrypt.ShardingEncryptor; @@ -133,11 +134,11 @@ public final class EncryptSQLRewriteEngine { sqlBuilder.appendLiterals(originalSQL.substring(0, sqlTokens.get(0).getStartIndex())); for (SQLToken each : sqlTokens) { if (each instanceof SelectItemsToken) { - appendItemsToken(sqlBuilder, (SelectItemsToken) each, count); + appendSelectItemsPlaceholder(sqlBuilder, (SelectItemsToken) each, count); } else if (each instanceof InsertValuesToken) { - appendInsertValuesToken(sqlBuilder, (InsertValuesToken) each, count, optimizeResult.getInsertOptimizeResult().get()); + appendInsertValuesPlaceholder(sqlBuilder, (InsertValuesToken) each, count, optimizeResult.getInsertOptimizeResult().get()); } else if (each instanceof InsertSetToken) { - appendInsertSetToken(sqlBuilder, (InsertSetToken) each, count, optimizeResult.getInsertOptimizeResult().get()); + appendInsertSetPlaceholder(sqlBuilder, (InsertSetToken) each, count, optimizeResult.getInsertOptimizeResult().get()); } else if (each instanceof EncryptColumnToken) { appendEncryptColumnPlaceholder(sqlBuilder, (EncryptColumnToken) each, count); } else if (each instanceof RemoveToken) { @@ -147,22 +148,22 @@ public final class EncryptSQLRewriteEngine { } } - private void appendItemsToken(final SQLBuilder sqlBuilder, final SelectItemsToken selectItemsToken, final int count) { - if (!(sqlStatement instanceof InsertStatement)) { - return; - } - for (int i = 0; i < selectItemsToken.getItems().size(); i++) { - if (selectItemsToken.isFirstOfItemsSpecial() && 0 == i) { - sqlBuilder.appendLiterals(SQLUtil.getOriginalValue(selectItemsToken.getItems().get(i), databaseType)); - } else { - sqlBuilder.appendLiterals(", "); - sqlBuilder.appendLiterals(SQLUtil.getOriginalValue(selectItemsToken.getItems().get(i), databaseType)); - } + private void appendSelectItemsPlaceholder(final SQLBuilder sqlBuilder, final SelectItemsToken selectItemsToken, final int count) { + if (sqlStatement instanceof InsertStatement) { + SelectItemsPlaceholder selectItemsPlaceholder = new SelectItemsPlaceholder(selectItemsToken.isFirstOfItemsSpecial()); + selectItemsPlaceholder.getItems().addAll(Lists.transform(selectItemsToken.getItems(), new Function<String, String>() { + + @Override + public String apply(final String input) { + return SQLUtil.getOriginalValue(input, databaseType); + } + })); + sqlBuilder.appendPlaceholder(selectItemsPlaceholder); } appendRest(sqlBuilder, count, getStopIndex(selectItemsToken)); } - private void appendInsertValuesToken(final SQLBuilder sqlBuilder, final InsertValuesToken insertValuesToken, final int count, final InsertOptimizeResult insertOptimizeResult) { + private void appendInsertValuesPlaceholder(final SQLBuilder sqlBuilder, final InsertValuesToken insertValuesToken, final int count, final InsertOptimizeResult insertOptimizeResult) { for (InsertOptimizeResultUnit each : insertOptimizeResult.getUnits()) { encryptInsertOptimizeResult(insertOptimizeResult.getColumnNames(), each); } @@ -171,7 +172,7 @@ public final class EncryptSQLRewriteEngine { appendRest(sqlBuilder, count, getStopIndex(insertValuesToken)); } - private void appendInsertSetToken(final SQLBuilder sqlBuilder, final InsertSetToken insertSetToken, final int count, final InsertOptimizeResult insertOptimizeResult) { + private void appendInsertSetPlaceholder(final SQLBuilder sqlBuilder, final InsertSetToken insertSetToken, final int count, final InsertOptimizeResult insertOptimizeResult) { for (InsertOptimizeResultUnit each : insertOptimizeResult.getUnits()) { encryptInsertOptimizeResult(insertOptimizeResult.getColumnNames(), each); } diff --git a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java index 8b2717964eb..c7fd883b2cd 100644 --- a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java +++ b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java @@ -176,15 +176,15 @@ public final class SQLBuilder { private void appendIndexPlaceholder(final IndexPlaceholder placeholder, final String actualTableName, final StringBuilder stringBuilder) { stringBuilder.append(placeholder.getLogicIndexName()); if (!Strings.isNullOrEmpty(actualTableName)) { - if ('`' == stringBuilder.charAt(stringBuilder.length() - 1)) { - stringBuilder.deleteCharAt(stringBuilder.length() - 1); + if ('`' == stringBuilder.charAt(stringBuilder.length() - 1)) { + stringBuilder.deleteCharAt(stringBuilder.length() - 1); stringBuilder.append("_"); stringBuilder.append(actualTableName); - stringBuilder.append("`"); - } else { - stringBuilder.append("_"); - stringBuilder.append(actualTableName); - } + stringBuilder.append("`"); + } else { + stringBuilder.append("_"); + stringBuilder.append(actualTableName); + } } } diff --git a/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/SQLRewriteEngineTest.java b/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/SQLRewriteEngineTest.java index a40730a942e..0d6c1779d1a 100644 --- a/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/SQLRewriteEngineTest.java +++ b/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/SQLRewriteEngineTest.java @@ -186,7 +186,7 @@ public final class SQLRewriteEngineTest { InsertOptimizeResult insertOptimizeResult = new InsertOptimizeResult(InsertType.VALUES, Arrays.asList("name", "age", "id")); Object[] parameters = {"x", 1, 1}; SQLExpression[] sqlExpressions = {new SQLParameterMarkerExpression(0), new SQLParameterMarkerExpression(1), new SQLParameterMarkerExpression(2)}; - insertOptimizeResult.addUnit(sqlExpressions, parameters); + insertOptimizeResult.addUnit(sqlExpressions, parameters, 3); insertOptimizeResult.getUnits().get(0).getDataNodes().add(new DataNode("db0.table_1")); TableUnit tableUnit = new TableUnit("db0"); tableUnit.getRoutingTables().add(new RoutingTable("table_x", "table_1")); @@ -207,7 +207,7 @@ public final class SQLRewriteEngineTest { InsertOptimizeResult insertOptimizeResult = new InsertOptimizeResult(InsertType.VALUES, Arrays.asList("name", "id")); Object[] parameters = {"Bill", 1}; SQLExpression[] sqlExpressions = {new SQLParameterMarkerExpression(0), new SQLParameterMarkerExpression(1)}; - insertOptimizeResult.addUnit(sqlExpressions, parameters); + insertOptimizeResult.addUnit(sqlExpressions, parameters, 2); insertOptimizeResult.getUnits().get(0).getDataNodes().add(new DataNode("db0.table_1")); TableUnit tableUnit = new TableUnit("db0"); tableUnit.getRoutingTables().add(new RoutingTable("table_x", "table_1")); @@ -226,7 +226,7 @@ public final class SQLRewriteEngineTest { insertStatement.addSQLToken(new InsertValuesToken(21, 32)); InsertOptimizeResult insertOptimizeResult = new InsertOptimizeResult(InsertType.VALUES, Arrays.asList("name", "id")); SQLExpression[] sqlExpressions = {new SQLNumberExpression(10), new SQLNumberExpression(1)}; - insertOptimizeResult.addUnit(sqlExpressions, new Object[0]); + insertOptimizeResult.addUnit(sqlExpressions, new Object[0], 0); insertOptimizeResult.getUnits().get(0).getDataNodes().add(new DataNode("db0.table_1")); TableUnit tableUnit = new TableUnit("db0"); tableUnit.getRoutingTables().add(new RoutingTable("table_x", "table_1")); @@ -248,7 +248,7 @@ public final class SQLRewriteEngineTest { insertStatement.addSQLToken(new InsertValuesToken(21, 35)); InsertOptimizeResult insertOptimizeResult = new InsertOptimizeResult(InsertType.VALUES, Arrays.asList("name", "id")); SQLExpression[] sqlExpressions = {new SQLNumberExpression(10), new SQLNumberExpression(1)}; - insertOptimizeResult.addUnit(sqlExpressions, new Object[0]); + insertOptimizeResult.addUnit(sqlExpressions, new Object[0], 0); insertOptimizeResult.getUnits().get(0).getDataNodes().add(new DataNode("db0.table_1")); TableUnit tableUnit = new TableUnit("db0"); tableUnit.getRoutingTables().add(new RoutingTable("table_x", "table_1")); @@ -268,7 +268,7 @@ public final class SQLRewriteEngineTest { InsertOptimizeResult insertOptimizeResult = new InsertOptimizeResult(InsertType.VALUES, Arrays.asList("name", "id")); SQLExpression[] sqlExpressions = {new SQLParameterMarkerExpression(0), new SQLParameterMarkerExpression(1)}; Object[] parameters = {"x", 1}; - insertOptimizeResult.addUnit(sqlExpressions, parameters); + insertOptimizeResult.addUnit(sqlExpressions, parameters, 2); insertOptimizeResult.getUnits().get(0).getDataNodes().add(new DataNode("db0.table_1")); TableUnit tableUnit = new TableUnit("db0"); tableUnit.getRoutingTables().add(new RoutingTable("table_x", "table_1"));
['sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/SQLRewriteEngineTest.java', 'sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/engine/encrypt/EncryptInsertOptimizeEngine.java', 'sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/insert/InsertOptimizeResultUnit.java', 'sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/EncryptSQLRewriteEngine.java', 'sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/insert/InsertOptimizeResult.java', 'sharding-core/sharding-core-optimize/src/test/java/org/apache/shardingsphere/core/optimize/result/InsertOptimizeResultTest.java', 'sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/insert/SetAssignmentOptimizeResult.java', 'sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/result/insert/ColumnValueOptimizeResult.java', 'sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java', 'sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/engine/sharding/insert/InsertOptimizeEngine.java']
{'.java': 10}
10
10
0
0
10
3,280,187
663,169
82,955
1,136
6,552
1,232
85
8
3,725
108
779
46
0
0
1970-01-01T00:25:57
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,488
apache/shardingsphere/2320/2312
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2312
https://github.com/apache/shardingsphere/pull/2320
https://github.com/apache/shardingsphere/pull/2320
1
fixes
If there is quoteCharacter for index name, sql can not be executed
## 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-RC1 ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-Proxy ### Expected behavior The following SQL can be executed correctly. ``` CREATE TABLE `t_order` ( `order_id` varchar(100) NOT NULL, `user_id` varchar(100) DEFAULT NULL, `status` varchar(45) DEFAULT NULL, PRIMARY KEY (`order_id`), KEY `order_index_t_order` (`order_id`) ) DEFAULT CHARSET=utf8; ``` ### Actual behavior An exception is thrown. ``` ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '_t_order_0 (`order_id`) ) DEFAULT CHARSET=utf8' at line 1 ``` ### Reason analyze (If you can) The rewritten SQL is not correct: > CREATE TABLE `t_order_0` ( `order_id` varchar(100) NOT NULL, `user_id` varchar(100) DEFAULT NULL, `status` varchar(45) DEFAULT NULL, PRIMARY KEY (`order_id`), KEY \\`order_index_t_order\\`_t_order_0 (\\`order_id\\`) ) DEFAULT CHARSET=utf8 The related code is: In SQLRewriteEngine class: ``` private void appendIndexPlaceholder(final SQLBuilder sqlBuilder, final IndexToken indexToken, final int count) { String indexName = originalSQL.substring(indexToken.getStartIndex(), indexToken.getStopIndex() + 1); String logicTableName = indexToken.getTableName().toLowerCase(); if (Strings.isNullOrEmpty(logicTableName)) { logicTableName = shardingRule.getLogicTableName(indexName); } sqlBuilder.appendPlaceholder(new IndexPlaceholder(indexName, logicTableName)); appendRest(sqlBuilder, count, indexToken.getStopIndex() + 1); } ``` ### 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).
1add261f7f9cf5492337096982bb63b824bcd40c
11da8fb2496a5bc2e40c6c88454b65e66b9da124
https://github.com/apache/shardingsphere/compare/1add261f7f9cf5492337096982bb63b824bcd40c...11da8fb2496a5bc2e40c6c88454b65e66b9da124
diff --git a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java index faea1845972..8b2717964eb 100644 --- a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java +++ b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java @@ -176,8 +176,15 @@ public final class SQLBuilder { private void appendIndexPlaceholder(final IndexPlaceholder placeholder, final String actualTableName, final StringBuilder stringBuilder) { stringBuilder.append(placeholder.getLogicIndexName()); if (!Strings.isNullOrEmpty(actualTableName)) { - stringBuilder.append("_"); - stringBuilder.append(actualTableName); + if ('`' == stringBuilder.charAt(stringBuilder.length() - 1)) { + stringBuilder.deleteCharAt(stringBuilder.length() - 1); + stringBuilder.append("_"); + stringBuilder.append(actualTableName); + stringBuilder.append("`"); + } else { + stringBuilder.append("_"); + stringBuilder.append(actualTableName); + } } }
['sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/SQLBuilder.java']
{'.java': 1}
1
1
0
0
1
3,258,051
658,607
82,369
1,123
503
78
11
1
2,491
289
590
51
2
3
1970-01-01T00:25:57
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,478
apache/shardingsphere/2539/2527
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2527
https://github.com/apache/shardingsphere/pull/2539
https://github.com/apache/shardingsphere/pull/2539
1
fixes
CachedDatabaseMetaData.getTables throw NullPointerException when use MasterSlaveDataSource
## 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-RC1 ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-JDBC ### Expected behavior Return table names ### Actual behavior Get npe ### Reason analyze (If you can) asset shardingRule is null ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc. DatabaseMetaData databaseMetaData = connection.getMetaData(); databaseMetaData.getTables(null, null, "ACT_ID_PROPERTY", new String[]{ "TABLE" }); ### Example codes for reproduce this issue (such as a github link).
6981f690ae2864fa4927fdb5fc74f795a981191e
d367e25213a530a87c9242225dcf64310f70691d
https://github.com/apache/shardingsphere/compare/6981f690ae2864fa4927fdb5fc74f795a981191e...d367e25213a530a87c9242225dcf64310f70691d
diff --git a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/metadata/ResultSetReturnedDatabaseMetaData.java b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/metadata/ResultSetReturnedDatabaseMetaData.java index 3db568a57c2..13c2a12d1e1 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/metadata/ResultSetReturnedDatabaseMetaData.java +++ b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/metadata/ResultSetReturnedDatabaseMetaData.java @@ -263,7 +263,10 @@ public abstract class ResultSetReturnedDatabaseMetaData extends WrapperAdapter i } private String getActualTableNamePattern(final String tableNamePattern) { - return null == tableNamePattern ? tableNamePattern : (shardingRule.findTableRule(tableNamePattern).isPresent() ? "%" + tableNamePattern + "%" : tableNamePattern); + if (null == tableNamePattern || null == shardingRule) { + return tableNamePattern; + } + return shardingRule.findTableRule(tableNamePattern).isPresent() ? "%" + tableNamePattern + "%" : tableNamePattern; } private String getActualTable(final String table) { diff --git a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/DatabaseMetaDataResultSet.java b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/DatabaseMetaDataResultSet.java index b71bf21f0a1..5aff76a5d4b 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/DatabaseMetaDataResultSet.java +++ b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/DatabaseMetaDataResultSet.java @@ -30,6 +30,7 @@ import java.sql.Time; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -100,7 +101,7 @@ public final class DatabaseMetaDataResultSet extends AbstractUnsupportedDatabase for (int i = 1; i <= columnLabelIndexMap.size(); i++) { if (tableNameColumnIndex == i) { String tableName = resultSet.getString(i); - Collection<String> logicTableNames = shardingRule.getLogicTableNames(tableName); + Collection<String> logicTableNames = null == shardingRule ? Collections.<String>emptyList() : shardingRule.getLogicTableNames(tableName); result.addObject(logicTableNames.isEmpty() ? tableName : logicTableNames.iterator().next()); } else if (indexNameColumnIndex == i) { String tableName = resultSet.getString(tableNameColumnIndex); diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/metadata/CachedDatabaseMetaDataTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/metadata/CachedDatabaseMetaDataTest.java index 875519df792..7b3c07fc90e 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/metadata/CachedDatabaseMetaDataTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/metadata/CachedDatabaseMetaDataTest.java @@ -858,8 +858,8 @@ public final class CachedDatabaseMetaDataTest { @Test public void assertGetTables() throws SQLException { - when(databaseMetaData.getTables("test", null, null, null)).thenReturn(resultSet); - assertThat(cachedDatabaseMetaData.getTables("test", null, null, null), instanceOf(DatabaseMetaDataResultSet.class)); + when(databaseMetaData.getTables("test", null, "%" + TABLE_NAME + "%", null)).thenReturn(resultSet); + assertThat(cachedDatabaseMetaData.getTables("test", null, TABLE_NAME, null), instanceOf(DatabaseMetaDataResultSet.class)); } @Test
['sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/metadata/ResultSetReturnedDatabaseMetaData.java', 'sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/datasource/metadata/CachedDatabaseMetaDataTest.java', 'sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/DatabaseMetaDataResultSet.java']
{'.java': 3}
3
3
0
0
3
2,928,004
588,266
75,103
1,033
692
134
8
2
1,203
153
269
29
2
0
1970-01-01T00:26:00
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,468
apache/shardingsphere/2886/2883
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2883
https://github.com/apache/shardingsphere/pull/2886
https://github.com/apache/shardingsphere/pull/2886
1
fixes
Encrypt replace the table name with the column name.
## Bug Report ### Which version of ShardingSphere did you use? 4.0.0-RC2-SNAPSHOT ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-JDBC ### Expected behavior encrypt successfully. ### Actual behavior Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'status.status' in 'field list' ### Reason analyze (If you can) Logic SQL: `select orderentit0_.order_id as order_id1_1_, orderentit0_.status as status2_1_, orderentit0_.user_id as user_id3_1_ from t_order orderentit0_` actual SQL: `select orderentit0_.order_id as order_id1_1_, status.status as status2_1_, orderentit0_.user_id as user_id3_1_ from t_order orderentit0_` Replace the table name with column name when rewrite. ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc. clone example code use `local-zookeeper-encrypt` as spring.profiles.active run `/Users/yangyi/Documents/java/sharding-sphere-example-sion/sharding-jdbc-example/orchestration-example/orchestration-spring-boot-example/src/main/java/org/apache/shardingsphere/example/orchestration/spring/boot/SpringBootExample` ### Example codes for reproduce this issue (such as a github link). https://github.com/apache/incubator-shardingsphere-example
a67c09f9d4b15e8ac18eab9a0a1026eb0b9ec2ae
215186d381c9c1ead9fb32314d95a275fd644349
https://github.com/apache/shardingsphere/compare/a67c09f9d4b15e8ac18eab9a0a1026eb0b9ec2ae...215186d381c9c1ead9fb32314d95a275fd644349
diff --git a/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/core/extractor/impl/common/column/ColumnExtractor.java b/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/core/extractor/impl/common/column/ColumnExtractor.java index 55fe9bcbd98..3b660ff2da8 100644 --- a/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/core/extractor/impl/common/column/ColumnExtractor.java +++ b/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/core/extractor/impl/common/column/ColumnExtractor.java @@ -43,7 +43,7 @@ public final class ColumnExtractor implements OptionalSQLSegmentExtractor { private ColumnSegment getColumnSegment(final ParserRuleContext columnNode) { ParserRuleContext nameNode = ExtractorUtils.getFirstChildNode(columnNode, RuleName.NAME); - ColumnSegment result = new ColumnSegment(columnNode.getStart().getStartIndex(), columnNode.getStart().getStopIndex(), nameNode.getText()); + ColumnSegment result = new ColumnSegment(columnNode.getStart().getStartIndex(), columnNode.getStop().getStopIndex(), nameNode.getText()); Optional<ParserRuleContext> ownerNode = ExtractorUtils.findFirstChildNodeNoneRecursive(columnNode, RuleName.OWNER); if (ownerNode.isPresent()) { result.setOwner(new TableSegment(ownerNode.get().getStart().getStartIndex(), ownerNode.get().getStop().getStopIndex(), ownerNode.get().getText())); diff --git a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/SelectEncryptItemTokenGenerator.java b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/SelectEncryptItemTokenGenerator.java index 2b6b87e3e45..78b86870e6a 100644 --- a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/SelectEncryptItemTokenGenerator.java +++ b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/SelectEncryptItemTokenGenerator.java @@ -22,6 +22,7 @@ import org.apache.shardingsphere.core.optimize.api.statement.OptimizedStatement; import org.apache.shardingsphere.core.parse.sql.segment.dml.item.ColumnSelectItemSegment; import org.apache.shardingsphere.core.parse.sql.segment.dml.item.SelectItemSegment; import org.apache.shardingsphere.core.parse.sql.segment.dml.item.SelectItemsSegment; +import org.apache.shardingsphere.core.parse.sql.segment.generic.TableSegment; import org.apache.shardingsphere.core.parse.sql.statement.dml.SelectStatement; import org.apache.shardingsphere.core.rewrite.builder.ParameterBuilder; import org.apache.shardingsphere.core.rewrite.token.pojo.SelectEncryptItemToken; @@ -79,12 +80,21 @@ public final class SelectEncryptItemTokenGenerator implements CollectionSQLToken return each instanceof ColumnSelectItemSegment && logicColumns.contains(((ColumnSelectItemSegment) each).getName()); } - private SelectEncryptItemToken createSelectCipherItemToken(final SelectItemSegment each, final String tableName, final EncryptRule encryptRule, final boolean isQueryWithCipherColumn) { - String columnName = ((ColumnSelectItemSegment) each).getName(); + private SelectEncryptItemToken createSelectCipherItemToken(final SelectItemSegment selectItemSegment, + final String tableName, final EncryptRule encryptRule, final boolean isQueryWithCipherColumn) { + String columnName = ((ColumnSelectItemSegment) selectItemSegment).getName(); Optional<String> plainColumn = encryptRule.getPlainColumn(tableName, columnName); if (!isQueryWithCipherColumn && plainColumn.isPresent()) { - return new SelectEncryptItemToken(each.getStartIndex(), each.getStopIndex(), plainColumn.get()); + return createSelectEncryptItemToken(selectItemSegment, plainColumn.get()); } - return new SelectEncryptItemToken(each.getStartIndex(), each.getStopIndex(), encryptRule.getCipherColumn(tableName, columnName)); + return createSelectEncryptItemToken(selectItemSegment, encryptRule.getCipherColumn(tableName, columnName)); + } + + private SelectEncryptItemToken createSelectEncryptItemToken(final SelectItemSegment selectItemSegment, final String columnName) { + Optional<TableSegment> owner = ((ColumnSelectItemSegment) selectItemSegment).getOwner(); + if (owner.isPresent()) { + return new SelectEncryptItemToken(selectItemSegment.getStartIndex(), selectItemSegment.getStopIndex(), columnName, owner.get().getTableName()); + } + return new SelectEncryptItemToken(selectItemSegment.getStartIndex(), selectItemSegment.getStopIndex(), columnName); } } diff --git a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/pojo/SelectEncryptItemToken.java b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/pojo/SelectEncryptItemToken.java index 89117ebc6fd..fdeecddc1ca 100644 --- a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/pojo/SelectEncryptItemToken.java +++ b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/pojo/SelectEncryptItemToken.java @@ -29,16 +29,23 @@ public final class SelectEncryptItemToken extends SQLToken implements Substituta private final int stopIndex; - private final String selectItemName; + private final String columnName; - public SelectEncryptItemToken(final int startIndex, final int stopIndex, final String selectItemName) { + private final String owner; + + public SelectEncryptItemToken(final int startIndex, final int stopIndex, final String columnName, final String owner) { super(startIndex); this.stopIndex = stopIndex; - this.selectItemName = selectItemName; + this.columnName = columnName; + this.owner = owner; + } + + public SelectEncryptItemToken(final int startIndex, final int stopIndex, final String columnName) { + this(startIndex, stopIndex, columnName, null); } @Override public String toString() { - return selectItemName; + return null == owner ? columnName : String.format("%s.%s", owner, columnName); } }
['sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/SelectEncryptItemTokenGenerator.java', 'sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/core/extractor/impl/common/column/ColumnExtractor.java', 'sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/pojo/SelectEncryptItemToken.java']
{'.java': 3}
3
3
0
0
3
3,064,393
613,668
78,000
1,063
2,777
515
35
3
1,339
124
336
36
1
0
1970-01-01T00:26:05
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,477
apache/shardingsphere/2540/2538
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2538
https://github.com/apache/shardingsphere/pull/2540
https://github.com/apache/shardingsphere/pull/2540
1
fixes
null and pagination question
## Question I am using the sharding-proxy, the PreparedStatement setString, I set the field to be null object not the 'null' string, the sharding-proxy will treat it as a string to be inserted into table,which is not my expected result is also not the same as in jdbc. for the pagination, it is not support the sql like 'limit 20 offset 0' ;only support the 'limit 0,20'. if this limit offset statement can be supported in the future?
a52c6575d18103f1b2dbce21c8939b43fa6c6fbf
b3842463d6809c303bf81f53893e3d89131830f8
https://github.com/apache/shardingsphere/compare/a52c6575d18103f1b2dbce21c8939b43fa6c6fbf...b3842463d6809c303bf81f53893e3d89131830f8
diff --git a/sharding-proxy/sharding-proxy-transport/sharding-proxy-transport-mysql/src/main/java/org/apache/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/protocol/MySQLBinaryProtocolValueFactory.java b/sharding-proxy/sharding-proxy-transport/sharding-proxy-transport-mysql/src/main/java/org/apache/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/protocol/MySQLBinaryProtocolValueFactory.java index 2096db93c05..c761768d170 100644 --- a/sharding-proxy/sharding-proxy-transport/sharding-proxy-transport-mysql/src/main/java/org/apache/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/protocol/MySQLBinaryProtocolValueFactory.java +++ b/sharding-proxy/sharding-proxy-transport/sharding-proxy-transport-mysql/src/main/java/org/apache/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/protocol/MySQLBinaryProtocolValueFactory.java @@ -45,6 +45,7 @@ public final class MySQLBinaryProtocolValueFactory { setFloatBinaryProtocolValue(); setDateBinaryProtocolValue(); setTimeBinaryProtocolValue(); + setNullBinaryProtocolValue(); } private static void setStringLenencBinaryProtocolValue() { @@ -108,6 +109,10 @@ public final class MySQLBinaryProtocolValueFactory { BINARY_PROTOCOL_VALUES.put(MySQLColumnType.MYSQL_TYPE_TIME, binaryProtocolValue); } + private static void setNullBinaryProtocolValue() { + BINARY_PROTOCOL_VALUES.put(MySQLColumnType.MYSQL_TYPE_NULL, null); + } + /** * Get binary protocol value. * diff --git a/sharding-proxy/sharding-proxy-transport/sharding-proxy-transport-mysql/src/test/java/org/apache/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/protocol/MySQLMySQLBinaryProtocolValueFactoryTest.java b/sharding-proxy/sharding-proxy-transport/sharding-proxy-transport-mysql/src/test/java/org/apache/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/protocol/MySQLMySQLBinaryProtocolValueFactoryTest.java index e30d9a3daa4..e2d542a1403 100644 --- a/sharding-proxy/sharding-proxy-transport/sharding-proxy-transport-mysql/src/test/java/org/apache/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/protocol/MySQLMySQLBinaryProtocolValueFactoryTest.java +++ b/sharding-proxy/sharding-proxy-transport/sharding-proxy-transport-mysql/src/test/java/org/apache/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/protocol/MySQLMySQLBinaryProtocolValueFactoryTest.java @@ -21,6 +21,8 @@ import org.apache.shardingsphere.shardingproxy.transport.mysql.constant.MySQLCol import org.junit.Test; import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; public final class MySQLMySQLBinaryProtocolValueFactoryTest { @@ -150,8 +152,13 @@ public final class MySQLMySQLBinaryProtocolValueFactoryTest { assertThat(MySQLBinaryProtocolValueFactory.getBinaryProtocolValue(MySQLColumnType.MYSQL_TYPE_TIME), instanceOf(MySQLTimeBinaryProtocolValue.class)); } + @Test + public void assertGetBinaryProtocolValueWithMySQLTypeNull() { + assertThat(MySQLBinaryProtocolValueFactory.getBinaryProtocolValue(MySQLColumnType.MYSQL_TYPE_NULL), is(nullValue())); + } + @Test(expected = IllegalArgumentException.class) public void assertGetBinaryProtocolValueWithUnsupportedType() { - MySQLBinaryProtocolValueFactory.getBinaryProtocolValue(MySQLColumnType.MYSQL_TYPE_NULL); + MySQLBinaryProtocolValueFactory.getBinaryProtocolValue(null); } }
['sharding-proxy/sharding-proxy-transport/sharding-proxy-transport-mysql/src/test/java/org/apache/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/protocol/MySQLMySQLBinaryProtocolValueFactoryTest.java', 'sharding-proxy/sharding-proxy-transport/sharding-proxy-transport-mysql/src/main/java/org/apache/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/protocol/MySQLBinaryProtocolValueFactory.java']
{'.java': 2}
2
2
0
0
2
2,928,154
588,298
75,107
1,033
183
37
5
1
441
78
105
5
0
0
1970-01-01T00:26:00
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,465
apache/shardingsphere/2983/2972
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2972
https://github.com/apache/shardingsphere/pull/2983
https://github.com/apache/shardingsphere/pull/2983
1
fixes
when using sharding master-slave-rules,the encryptRule is not worked for result,but is wored for param
## 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/apache/incubator-shardingsphere/issues). - Read documentation: [ShardingSphere Doc](https://shardingsphere.apache.org/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-RC2 ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-JDBC ### Expected behavior the query result is decrypt ### Actual behavior the query result is still encrypt ### Reason analyze (If you can) thie query result not use the encryptRule to decrypt **this question is not dupe! I use the master-slave-rules! I want the master-slave-rules and the encrpt can combine use!** ### 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). spring: shardingsphere: datasource: names: master,slave0 master: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: org.h2.Driver url: jdbc:h2:mem:dbtest:public;DB_CLOSE_DELAY=-1;MODE=MySQL slave0: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: org.h2.Driver url: jdbc:h2:mem:dbtest:public;DB_CLOSE_DELAY=-1;MODE=MySQL sharding: defaultDataSourceName: dataSource master-slave-rules: dataSource: master-data-source-name: master slave-data-source-names[0]: slave0 load-balance-algorithm-type: ROUND_ROBIN encryptRule: encryptors: encryptor_aes: type: AES props: aes.key.value: 123456 tables: company: columns: address: cipherColumn: address encryptor: encryptor_aes full_name: cipherColumn: full_name encryptor: encryptor_aes props: sql.show: true
6606964dce1e8a7bda45e5d41116bb58d0f34694
6b5b40162dd87cd4fa66154e92408979144937ca
https://github.com/apache/shardingsphere/compare/6606964dce1e8a7bda45e5d41116bb58d0f34694...6b5b40162dd87cd4fa66154e92408979144937ca
diff --git a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/ShardingPreparedStatement.java b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/ShardingPreparedStatement.java index 734190d36b4..eee2244e640 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/ShardingPreparedStatement.java +++ b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/ShardingPreparedStatement.java @@ -124,10 +124,6 @@ public final class ShardingPreparedStatement extends AbstractShardingPreparedSta if (null != currentResultSet) { return currentResultSet; } - if (1 == preparedStatementExecutor.getStatements().size() && sqlRouteResult.getShardingStatement().getSQLStatement() instanceof SelectStatement) { - currentResultSet = preparedStatementExecutor.getStatements().iterator().next().getResultSet(); - return currentResultSet; - } List<ResultSet> resultSets = new ArrayList<>(preparedStatementExecutor.getStatements().size()); List<QueryResult> queryResults = new ArrayList<>(preparedStatementExecutor.getStatements().size()); for (Statement each : preparedStatementExecutor.getStatements()) { diff --git a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/ShardingStatement.java b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/ShardingStatement.java index 8d2ad8b8677..f6dc80588d5 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/ShardingStatement.java +++ b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/ShardingStatement.java @@ -105,10 +105,6 @@ public final class ShardingStatement extends AbstractStatementAdapter { if (null != currentResultSet) { return currentResultSet; } - if (1 == statementExecutor.getStatements().size() && sqlRouteResult.getShardingStatement().getSQLStatement() instanceof SelectStatement) { - currentResultSet = statementExecutor.getStatements().iterator().next().getResultSet(); - return currentResultSet; - } List<ResultSet> resultSets = new ArrayList<>(statementExecutor.getStatements().size()); List<QueryResult> queryResults = new ArrayList<>(statementExecutor.getStatements().size()); for (Statement each : statementExecutor.getStatements()) {
['sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/ShardingStatement.java', 'sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/ShardingPreparedStatement.java']
{'.java': 2}
2
2
0
0
2
3,078,860
616,545
78,313
1,066
608
106
8
2
2,072
226
507
70
2
0
1970-01-01T00:26:07
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,455
apache/shardingsphere/7468/6643
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/6643
https://github.com/apache/shardingsphere/pull/7468
https://github.com/apache/shardingsphere/pull/7468
1
fix
Rewrite error of derived alias
## 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/apache/shardingsphere/issues). - Read documentation: [ShardingSphere Doc](https://shardingsphere.apache.org/document/current/en/overview). Please pay attention on issues you submitted, because we maybe need more details. If no response anymore 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? 5.0.0-RC1-SNAPSHOT ### Which project did you use? ShardingSphere-JDBC or ShardingSphere-Proxy? Both ### Expected behavior Correctly rewrite the following SQL: ``` SELECT SUM(order_id) AS orders_sum, user_id as `key` FROM t_order GROUP BY `key` ``` ### Actual behavior The logical SQL is rewritten to: ``` Actual SQL: ds_0 ::: SELECT SUM(order_id) AS orders_sum, user_id as `key` , `key` AS GROUP_BY_DERIVED_0 FROM t_order_0 GROUP BY `key` ORDER BY `key` ASC Actual SQL: ds_0 ::: SELECT SUM(order_id) AS orders_sum, user_id as `key` , `key` AS GROUP_BY_DERIVED_0 FROM t_order_1 GROUP BY `key` ORDER BY `key` ASC Actual SQL: ds_1 ::: SELECT SUM(order_id) AS orders_sum, user_id as `key` , `key` AS GROUP_BY_DERIVED_0 FROM t_order_0 GROUP BY `key` ORDER BY `key` ASC Actual SQL: ds_1 ::: SELECT SUM(order_id) AS orders_sum, user_id as `key` , `key` AS GROUP_BY_DERIVED_0 FROM t_order_1 GROUP BY `key` ORDER BY `key` ASC ``` Lead to MySQL server respond error: `ERROR 1054 (42S22): Unknown column 'key' in 'field list'` ### Reason analyze (If you can) Rewrite error of derived alias ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc. Refer to **Actual behavior** ### Example codes for reproduce this issue (such as a github link). Refer to https://github.com/apache/shardingsphere/issues/6603
0b5ee351bad3ce2dbe52003b55d4f9fa52fcaf36
4fb7ea269d59e25a1719ad74e95030bda7ea0744
https://github.com/apache/shardingsphere/compare/0b5ee351bad3ce2dbe52003b55d4f9fa52fcaf36...4fb7ea269d59e25a1719ad74e95030bda7ea0744
diff --git a/shardingsphere-sql-parser/shardingsphere-sql-parser-binder/src/main/java/org/apache/shardingsphere/sql/parser/binder/segment/select/projection/Projection.java b/shardingsphere-sql-parser/shardingsphere-sql-parser-binder/src/main/java/org/apache/shardingsphere/sql/parser/binder/segment/select/projection/Projection.java index 37f06b18d99..b6ababb8c00 100644 --- a/shardingsphere-sql-parser/shardingsphere-sql-parser-binder/src/main/java/org/apache/shardingsphere/sql/parser/binder/segment/select/projection/Projection.java +++ b/shardingsphere-sql-parser/shardingsphere-sql-parser-binder/src/main/java/org/apache/shardingsphere/sql/parser/binder/segment/select/projection/Projection.java @@ -37,7 +37,7 @@ public interface Projection { * @return alias */ Optional<String> getAlias(); - + /** * Get columnLabel. * diff --git a/shardingsphere-sql-parser/shardingsphere-sql-parser-binder/src/main/java/org/apache/shardingsphere/sql/parser/binder/segment/select/projection/engine/ProjectionsContextEngine.java b/shardingsphere-sql-parser/shardingsphere-sql-parser-binder/src/main/java/org/apache/shardingsphere/sql/parser/binder/segment/select/projection/engine/ProjectionsContextEngine.java index 6ecce295937..b282f2ecc23 100644 --- a/shardingsphere-sql-parser/shardingsphere-sql-parser-binder/src/main/java/org/apache/shardingsphere/sql/parser/binder/segment/select/projection/engine/ProjectionsContextEngine.java +++ b/shardingsphere-sql-parser/shardingsphere-sql-parser-binder/src/main/java/org/apache/shardingsphere/sql/parser/binder/segment/select/projection/engine/ProjectionsContextEngine.java @@ -34,6 +34,7 @@ import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.order.item.In import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.order.item.OrderByItemSegment; import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.order.item.TextOrderByItemSegment; import org.apache.shardingsphere.sql.parser.sql.common.segment.generic.table.SimpleTableSegment; +import org.apache.shardingsphere.sql.parser.sql.common.util.SQLUtil; import java.util.Collection; import java.util.LinkedList; @@ -180,7 +181,8 @@ public final class ProjectionsContextEngine { } private boolean isSameAlias(final Projection projection, final TextOrderByItemSegment orderItem) { - return projection.getAlias().isPresent() && (orderItem.getText().equalsIgnoreCase(projection.getAlias().get()) || orderItem.getText().equalsIgnoreCase(projection.getExpression())); + return projection.getAlias().isPresent() + && (SQLUtil.getExactlyValue(orderItem.getText()).equalsIgnoreCase(projection.getAlias().get()) || orderItem.getText().equalsIgnoreCase(projection.getExpression())); } private boolean isSameQualifiedName(final Projection projection, final TextOrderByItemSegment orderItem) {
['shardingsphere-sql-parser/shardingsphere-sql-parser-binder/src/main/java/org/apache/shardingsphere/sql/parser/binder/segment/select/projection/engine/ProjectionsContextEngine.java', 'shardingsphere-sql-parser/shardingsphere-sql-parser-binder/src/main/java/org/apache/shardingsphere/sql/parser/binder/segment/select/projection/Projection.java']
{'.java': 2}
2
2
0
0
2
5,141,202
1,022,790
123,975
1,854
499
91
6
2
2,043
280
524
56
3
2
1970-01-01T00:26:40
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,456
apache/shardingsphere/7449/7200
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/7200
https://github.com/apache/shardingsphere/pull/7449
https://github.com/apache/shardingsphere/pull/7449
1
fixes
LockSegment absent of PostgreSQL parser
## 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/apache/shardingsphere/issues). - Read documentation: [ShardingSphere Doc](https://shardingsphere.apache.org/document/current/en/overview). Please pay attention on issues you submitted, because we maybe need more details. If no response anymore 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? 5.0.0-RC1-SNAPSHOT ### Which project did you use? ShardingSphere-JDBC or ShardingSphere-Proxy? ShardingSphere-JDBC ### Expected behavior Under MasterSlave rule: `SELECT * FROM t_order WHERE user_id = ? FOR UPDATE` should be routed to Master node ### Actual behavior The SQL is routed to Slave node ### Reason analyze (If you can) LockSegment absent of PostgreSQL parser Please refer to the route logic in MasterSlaveDataSourceRouter: ``` private boolean isMasterRoute(final SQLStatement sqlStatement) { return containsLockSegment(sqlStatement) || !(sqlStatement instanceof SelectStatement) || MasterVisitedManager.isMasterVisited() || HintManager.isMasterRouteOnly(); } private boolean containsLockSegment(final SQLStatement sqlStatement) { return sqlStatement instanceof SelectStatement && ((SelectStatement) sqlStatement).getLock().isPresent(); } ``` ### 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).
140e487b8949995a61ec94db68d753cc8b425721
f892a63f058068daef8aed9a3838ec34f6985c2b
https://github.com/apache/shardingsphere/compare/140e487b8949995a61ec94db68d753cc8b425721...f892a63f058068daef8aed9a3838ec34f6985c2b
diff --git a/shardingsphere-sql-parser/shardingsphere-sql-parser-dialect/shardingsphere-sql-parser-postgresql/src/main/java/org/apache/shardingsphere/sql/parser/postgresql/visitor/impl/PostgreSQLDMLVisitor.java b/shardingsphere-sql-parser/shardingsphere-sql-parser-dialect/shardingsphere-sql-parser-postgresql/src/main/java/org/apache/shardingsphere/sql/parser/postgresql/visitor/impl/PostgreSQLDMLVisitor.java index 70d3050dab5..64eb9a8dfd6 100644 --- a/shardingsphere-sql-parser/shardingsphere-sql-parser-dialect/shardingsphere-sql-parser-postgresql/src/main/java/org/apache/shardingsphere/sql/parser/postgresql/visitor/impl/PostgreSQLDMLVisitor.java +++ b/shardingsphere-sql-parser/shardingsphere-sql-parser-dialect/shardingsphere-sql-parser-postgresql/src/main/java/org/apache/shardingsphere/sql/parser/postgresql/visitor/impl/PostgreSQLDMLVisitor.java @@ -28,6 +28,7 @@ import org.apache.shardingsphere.sql.parser.autogen.PostgreSQLStatementParser.Co import org.apache.shardingsphere.sql.parser.autogen.PostgreSQLStatementParser.DeleteContext; import org.apache.shardingsphere.sql.parser.autogen.PostgreSQLStatementParser.DoStatementContext; import org.apache.shardingsphere.sql.parser.autogen.PostgreSQLStatementParser.ExprListContext; +import org.apache.shardingsphere.sql.parser.autogen.PostgreSQLStatementParser.ForLockingClauseContext; import org.apache.shardingsphere.sql.parser.autogen.PostgreSQLStatementParser.FromClauseContext; import org.apache.shardingsphere.sql.parser.autogen.PostgreSQLStatementParser.FromListContext; import org.apache.shardingsphere.sql.parser.autogen.PostgreSQLStatementParser.GroupByItemContext; @@ -326,6 +327,12 @@ public final class PostgreSQLDMLVisitor extends PostgreSQLVisitor implements DML return result; } + @Override + public ASTNode visitForLockingClause(final ForLockingClauseContext ctx) { + LockSegment result = new LockSegment(ctx.start.getStartIndex(), ctx.stop.getStopIndex()); + return result; + } + @Override public ASTNode visitSelectWithParens(final SelectWithParensContext ctx) { if (null != ctx.selectWithParens()) {
['shardingsphere-sql-parser/shardingsphere-sql-parser-dialect/shardingsphere-sql-parser-postgresql/src/main/java/org/apache/shardingsphere/sql/parser/postgresql/visitor/impl/PostgreSQLDMLVisitor.java']
{'.java': 1}
1
1
0
0
1
5,115,597
1,017,826
123,306
1,829
333
69
7
1
1,758
202
366
54
2
1
1970-01-01T00:26:40
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,462
apache/shardingsphere/6349/6324
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/6324
https://github.com/apache/shardingsphere/pull/6349
https://github.com/apache/shardingsphere/pull/6349
1
fixes
ShardingSphere-Proxy will be blocked when query big blob data
### Which version of ShardingSphere did you use? Shardingsphere-ui-4.1.1 Previous version 4.0.0-RC1 also has the same issue. ### Which project did you use? ShardingSphere-JDBC or ShardingSphere-Proxy? ShardingSphere-Proxy ### Expected behavior ShardingSphere-Proxy can receive connection and process sql statements. ### Actual behavior ShardingSphere-Proxy continues to receive connections, and the connections all logined successfully. But it stops here. It doesn't process the following sql statements. Following is part of the outputs(We modified according our purpose). ``` [INFO ] 19:49:41.596 [epollEventLoopGroup-2-1] i.n.handler.logging.LoggingHandler - [id: 0xd66b03e6, L:/0.0.0.0:3307] READ: [id: 0x60558169, L:/192.168.1.46:3307 - R:/192.168.1.46:44510] [INFO ] 19:49:41.597 [epollEventLoopGroup-2-1] i.n.handler.logging.LoggingHandler - [id: 0xd66b03e6, L:/0.0.0.0:3307] READ COMPLETE [INFO ] 19:49:41.601 [epollEventLoopGroup-3-2] o.a.s.s.f.m.a.MySQLAuthenticationEngine - ===Username: amRiYzpteXNxbDovLzE5Mi4xNjguMC4xMDg6MzMwNi90ZXN0P3VzZXI9cm9vdCZwYXNzd29yZD10ZXN0JnNlcnZlclRpbWV6b25lPVVUQyZ1c2VTU0w9ZmFsc2U= [INFO ] 19:49:41.601 [epollEventLoopGroup-3-2] o.a.s.s.f.m.a.MySQLAuthenticationEngine - ===Auth connection url=jdbc:mysql://192.168.0.108:3306/test?user=root&password=test&serverTimezone=UTC&useSSL=false [INFO ] 19:49:41.602 [epollEventLoopGroup-3-2] o.a.s.s.f.m.a.MySQLAuthenticationEngine - ===Login succeed [INFO ] 19:49:44.597 [epollEventLoopGroup-2-1] i.n.handler.logging.LoggingHandler - [id: 0xd66b03e6, L:/0.0.0.0:3307] READ: [id: 0xafd94de4, L:/192.168.1.46:3307 - R:/192.168.1.46:44512] [INFO ] 19:49:44.597 [epollEventLoopGroup-2-1] i.n.handler.logging.LoggingHandler - [id: 0xd66b03e6, L:/0.0.0.0:3307] READ COMPLETE [INFO ] 19:49:44.601 [epollEventLoopGroup-3-3] o.a.s.s.f.m.a.MySQLAuthenticationEngine - ===Username: amRiYzpteXNxbDovLzE5Mi4xNjguMC4xMDg6MzMwNi90ZXN0P3VzZXI9cm9vdCZwYXNzd29yZD10ZXN0JnNlcnZlclRpbWV6b25lPVVUQyZ1c2VTU0w9ZmFsc2U= [INFO ] 19:49:44.602 [epollEventLoopGroup-3-3] o.a.s.s.f.m.a.MySQLAuthenticationEngine - ===Auth connection url=jdbc:mysql://192.168.0.108:3306/test?user=root&password=test&serverTimezone=UTC&useSSL=false [INFO ] 19:49:44.602 [epollEventLoopGroup-3-3] o.a.s.s.f.m.a.MySQLAuthenticationEngine - ===Login succeed ``` After the client application is killed. The blocked sql statement will be processed. ``` [INFO ] 19:50:06.662 [ShardingSphere-Command-1] o.a.s.s.b.c.j.w.StatementExecutorWrapperJustep - ===Modified Sql:SELECT * FROM sa_taskrelation [INFO ] 19:50:06.662 [ShardingSphere-Command-2] o.a.s.s.f.m.c.MySQLCommandExecutorFactory - Execute packet type: COM_QUERY, value: MySQLComQueryPacket(sql=select * from sa_sign) [INFO ] 19:50:06.662 [ShardingSphere-Command-2] o.a.s.s.b.c.j.w.StatementExecutorWrapperJustep - ===Modified Sql:SELECT * FROM sa_sign [INFO ] 19:50:06.662 [ShardingSphere-Command-0] o.a.s.s.f.m.c.MySQLCommandExecutorFactory - Execute packet type: COM_QUERY, value: MySQLComQueryPacket(sql=select * from document_subscriptions) [INFO ] 19:50:06.663 [ShardingSphere-Command-0] o.a.s.s.b.c.j.w.StatementExecutorWrapperJustep - ===Modified Sql:SELECT * FROM document_subscriptions [INFO ] 19:50:06.663 [ShardingSphere-Command-3] o.a.s.s.f.m.c.MySQLCommandExecutorFactory - Execute packet type: COM_QUERY, value: MySQLComQueryPacket(sql=select * from selectionlist_data) [INFO ] 19:50:06.664 [ShardingSphere-Command-1] o.a.s.s.f.m.c.MySQLCommandExecutorFactory - Execute packet type: COM_QUERY, value: MySQLComQueryPacket(sql=select * from sa_remindactionparameter) [INFO ] 19:50:06.664 [ShardingSphere-Command-3] o.a.s.s.b.c.j.w.StatementExecutorWrapperJustep - ===Modified Sql:SELECT * FROM selectionlist_data ``` ### Reason analyze (If you can) ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc. The test client application is a multi-thread application. In a thread, it does following work. 1. connection to shardingsphere-proxy 2. get all table names of the database. 3. for each table, executeQuery("select * from " + tablename) and print the result set, sleep 2 seconds. 4. close the connection 5. goto 1 100 threads are created to test. when shardingsphere-proxy is blocked, part of the client outputs: ``` Fri Jul 10 19:49:27 CST 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. ``` It seems client is connecting to server, but cannot get response. ### Example codes for reproduce this issue (such as a github link).
803611ca626394f1c85e672452c082ecb283da90
98284eade870fa9225b9d7cb6706113f94e282ab
https://github.com/apache/shardingsphere/compare/803611ca626394f1c85e672452c082ecb283da90...98284eade870fa9225b9d7cb6706113f94e282ab
diff --git a/shardingsphere-proxy/shardingsphere-proxy-backend/src/main/java/org/apache/shardingsphere/proxy/backend/communication/jdbc/connection/ResourceSynchronizer.java b/shardingsphere-proxy/shardingsphere-proxy-backend/src/main/java/org/apache/shardingsphere/proxy/backend/communication/jdbc/connection/ResourceSynchronizer.java index 2778c64082d..238197fdd1a 100644 --- a/shardingsphere-proxy/shardingsphere-proxy-backend/src/main/java/org/apache/shardingsphere/proxy/backend/communication/jdbc/connection/ResourceSynchronizer.java +++ b/shardingsphere-proxy/shardingsphere-proxy-backend/src/main/java/org/apache/shardingsphere/proxy/backend/communication/jdbc/connection/ResourceSynchronizer.java @@ -33,26 +33,12 @@ public final class ResourceSynchronizer { private final Condition condition = lock.newCondition(); - /** - * Do await. - * - */ - public void doAwait() { - lock.lock(); - try { - condition.await(); - } catch (final InterruptedException ignore) { - } finally { - lock.unlock(); - } - } - /** * Do await until default timeout milliseconds. * * @throws InterruptedException interrupted exception */ - void doAwaitUntil() throws InterruptedException { + public void doAwaitUntil() throws InterruptedException { lock.lock(); try { condition.await(DEFAULT_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS); diff --git a/shardingsphere-proxy/shardingsphere-proxy-frontend/shardingsphere-proxy-frontend-mysql/src/main/java/org/apache/shardingsphere/proxy/frontend/mysql/command/MySQLCommandExecuteEngine.java b/shardingsphere-proxy/shardingsphere-proxy-frontend/shardingsphere-proxy-frontend-mysql/src/main/java/org/apache/shardingsphere/proxy/frontend/mysql/command/MySQLCommandExecuteEngine.java index f3a7f9035e4..806483fbd94 100644 --- a/shardingsphere-proxy/shardingsphere-proxy-frontend/shardingsphere-proxy-frontend-mysql/src/main/java/org/apache/shardingsphere/proxy/frontend/mysql/command/MySQLCommandExecuteEngine.java +++ b/shardingsphere-proxy/shardingsphere-proxy-frontend/shardingsphere-proxy-frontend-mysql/src/main/java/org/apache/shardingsphere/proxy/frontend/mysql/command/MySQLCommandExecuteEngine.java @@ -18,6 +18,7 @@ package org.apache.shardingsphere.proxy.frontend.mysql.command; import io.netty.channel.ChannelHandlerContext; +import lombok.SneakyThrows; import org.apache.shardingsphere.db.protocol.mysql.packet.command.MySQLCommandPacket; import org.apache.shardingsphere.db.protocol.mysql.packet.command.MySQLCommandPacketFactory; import org.apache.shardingsphere.db.protocol.mysql.packet.command.MySQLCommandPacketType; @@ -70,6 +71,7 @@ public final class MySQLCommandExecuteEngine implements CommandExecuteEngine { } @Override + @SneakyThrows public void writeQueryData(final ChannelHandlerContext context, final BackendConnection backendConnection, final QueryCommandExecutor queryCommandExecutor, final int headerPackagesCount) throws SQLException { if (!queryCommandExecutor.isQuery() || !context.channel().isActive()) { @@ -82,7 +84,7 @@ public final class MySQLCommandExecuteEngine implements CommandExecuteEngine { count++; while (!context.channel().isWritable() && context.channel().isActive()) { context.flush(); - backendConnection.getResourceSynchronizer().doAwait(); + backendConnection.getResourceSynchronizer().doAwaitUntil(); } DatabasePacket dataValue = queryCommandExecutor.getQueryData(); context.write(dataValue); diff --git a/shardingsphere-proxy/shardingsphere-proxy-frontend/shardingsphere-proxy-frontend-postgresql/src/main/java/org/apache/shardingsphere/proxy/frontend/postgresql/command/PostgreSQLCommandExecuteEngine.java b/shardingsphere-proxy/shardingsphere-proxy-frontend/shardingsphere-proxy-frontend-postgresql/src/main/java/org/apache/shardingsphere/proxy/frontend/postgresql/command/PostgreSQLCommandExecuteEngine.java index dc1673316db..f9888f9b7c3 100644 --- a/shardingsphere-proxy/shardingsphere-proxy-frontend/shardingsphere-proxy-frontend-postgresql/src/main/java/org/apache/shardingsphere/proxy/frontend/postgresql/command/PostgreSQLCommandExecuteEngine.java +++ b/shardingsphere-proxy/shardingsphere-proxy-frontend/shardingsphere-proxy-frontend-postgresql/src/main/java/org/apache/shardingsphere/proxy/frontend/postgresql/command/PostgreSQLCommandExecuteEngine.java @@ -18,6 +18,7 @@ package org.apache.shardingsphere.proxy.frontend.postgresql.command; import io.netty.channel.ChannelHandlerContext; +import lombok.SneakyThrows; import org.apache.shardingsphere.db.protocol.packet.CommandPacket; import org.apache.shardingsphere.db.protocol.packet.CommandPacketType; import org.apache.shardingsphere.db.protocol.packet.DatabasePacket; @@ -73,6 +74,7 @@ public final class PostgreSQLCommandExecuteEngine implements CommandExecuteEngin } @Override + @SneakyThrows public void writeQueryData(final ChannelHandlerContext context, final BackendConnection backendConnection, final QueryCommandExecutor queryCommandExecutor, final int headerPackagesCount) throws SQLException { if (queryCommandExecutor.isQuery() && !context.channel().isActive()) { @@ -90,7 +92,7 @@ public final class PostgreSQLCommandExecuteEngine implements CommandExecuteEngin count++; while (!context.channel().isWritable() && context.channel().isActive()) { context.flush(); - backendConnection.getResourceSynchronizer().doAwait(); + backendConnection.getResourceSynchronizer().doAwaitUntil(); } DatabasePacket resultValue = queryCommandExecutor.getQueryData(); context.write(resultValue);
['shardingsphere-proxy/shardingsphere-proxy-backend/src/main/java/org/apache/shardingsphere/proxy/backend/communication/jdbc/connection/ResourceSynchronizer.java', 'shardingsphere-proxy/shardingsphere-proxy-frontend/shardingsphere-proxy-frontend-mysql/src/main/java/org/apache/shardingsphere/proxy/frontend/mysql/command/MySQLCommandExecuteEngine.java', 'shardingsphere-proxy/shardingsphere-proxy-frontend/shardingsphere-proxy-frontend-postgresql/src/main/java/org/apache/shardingsphere/proxy/frontend/postgresql/command/PostgreSQLCommandExecuteEngine.java']
{'.java': 3}
3
3
0
0
3
4,883,872
970,843
118,877
1,699
778
145
24
3
4,998
484
1,618
55
0
3
1970-01-01T00:26:34
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,463
apache/shardingsphere/3052/3013
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/3013
https://github.com/apache/shardingsphere/pull/3052
https://github.com/apache/shardingsphere/pull/3052
1
fixes
4.0.0-RC2 sharding-proxy use zookeeper can not start
i can use zookeeper in sharding-proxy, but can not start. server.xml: orchestration: name: orchestration_ds overwrite: false registry: type: zookeeper serverLists: localhost:2181 namespace: orchestration error: [INFO ] 09:54:56.858 [main] o.a.c.f.imps.CuratorFrameworkImpl - Starting [INFO ] 09:54:56.863 [main] org.apache.zookeeper.ZooKeeper - Client environment:zookeeper.version=3.4.10-39d3a4f269333c922ed3db283be479f9deacaa0f, built on 03/23/2017 10:13 GMT [INFO ] 09:54:56.863 [main] org.apache.zookeeper.ZooKeeper - Client environment:host.name=server02 [INFO ] 09:54:56.863 [main] org.apache.zookeeper.ZooKeeper - Client environment:java.version=1.8.0_171 [INFO ] 09:54:56.863 [main] org.apache.zookeeper.ZooKeeper - Client environment:java.vendor=Oracle Corporation [INFO ] 09:54:56.863 [main] org.apache.zookeeper.ZooKeeper - Client environment:java.home=/usr/java/jdk1.8.0_171/jre [INFO ] 09:54:56.863 [main] org.apache.zookeeper.ZooKeeper - Client environment:java.class.path=.:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/conf:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-proxy-bootstrap-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-proxy-common-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-core-entry-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-core-api-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/guava-18.0.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/slf4j-api-1.7.7.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/jcl-over-slf4j-1.7.7.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-core-common-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/groovy-2.4.5-indy.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/snakeyaml-1.16.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/commons-codec-1.10.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-core-parse-common-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-core-parse-spi-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/antlr4-runtime-4.7.1.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/commons-collections4-4.2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-core-parse-mysql-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-core-parse-postgresql-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-core-parse-oracle-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-core-parse-sqlserver-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-core-optimize-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-core-route-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-core-rewrite-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-core-execute-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-core-merge-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-orchestration-core-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-orchestration-reg-api-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/HikariCP-java7-2.4.11.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-proxy-transport-core-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/netty-all-4.1.16.Final.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-proxy-transport-mysql-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-transaction-core-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-proxy-transport-postgresql-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-proxy-frontend-core-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-proxy-frontend-spi-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-proxy-backend-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-transaction-xa-core-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-transaction-xa-spi-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/jta-1.1.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-transaction-xa-atomikos-manager-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/transactions-4.0.6.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/transactions-api-4.0.6.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/atomikos-util-4.0.6.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/transactions-jta-4.0.6.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/transactions-jdbc-4.0.6.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/postgresql-42.2.5.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-proxy-frontend-mysql-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-proxy-frontend-postgresql-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-orchestration-reg-zookeeper-curator-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/curator-framework-2.10.0.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/curator-client-2.10.0.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/log4j-1.2.16.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/jline-0.9.94.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/curator-recipes-2.10.0.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-opentracing-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/opentracing-util-0.30.0.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/opentracing-api-0.30.0.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/opentracing-noop-0.30.0.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/logback-classic-1.2.0.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/logback-core-1.2.0.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/sharding-proxy-distribution-4.0.0-RC2.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/mysql-connector-java-5.1.47.jar:/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin/lib/zookeeper-3.4.10.jar [INFO ] 09:54:56.863 [main] org.apache.zookeeper.ZooKeeper - Client environment:java.library.path=/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib [INFO ] 09:54:56.863 [main] org.apache.zookeeper.ZooKeeper - Client environment:java.io.tmpdir=/tmp [INFO ] 09:54:56.863 [main] org.apache.zookeeper.ZooKeeper - Client environment:java.compiler=<NA> [INFO ] 09:54:56.863 [main] org.apache.zookeeper.ZooKeeper - Client environment:os.name=Linux [INFO ] 09:54:56.863 [main] org.apache.zookeeper.ZooKeeper - Client environment:os.arch=amd64 [INFO ] 09:54:56.863 [main] org.apache.zookeeper.ZooKeeper - Client environment:os.version=3.10.0-862.el7.x86_64 [INFO ] 09:54:56.863 [main] org.apache.zookeeper.ZooKeeper - Client environment:user.name=root [INFO ] 09:54:56.863 [main] org.apache.zookeeper.ZooKeeper - Client environment:user.home=/root [INFO ] 09:54:56.863 [main] org.apache.zookeeper.ZooKeeper - Client environment:user.dir=/root/apache-shardingsphere-incubating-4.0.0-RC2-sharding-proxy-bin [INFO ] 09:54:56.864 [main] org.apache.zookeeper.ZooKeeper - Initiating client connection, connectString=localhost:2181 sessionTimeout=60000 watcher=org.apache.curator.ConnectionState@67c33749 [INFO ] 09:54:56.874 [main-SendThread(localhost:2181)] org.apache.zookeeper.ClientCnxn - Opening socket connection to server localhost/127.0.0.1:2181. Will not attempt to authenticate using SASL (unknown error) [INFO ] 09:54:56.904 [main-SendThread(localhost:2181)] org.apache.zookeeper.ClientCnxn - Socket connection established to localhost/127.0.0.1:2181, initiating session [INFO ] 09:54:56.922 [main-SendThread(localhost:2181)] org.apache.zookeeper.ClientCnxn - Session establishment complete on server localhost/127.0.0.1:2181, sessionid = 0x16d18c861d00003, negotiated timeout = 40000 [INFO ] 09:54:56.924 [main-EventThread] o.a.c.f.state.ConnectionStateManager - State change: CONNECTED [INFO ] 09:54:57.457 [Curator-Framework-0] o.a.c.f.imps.CuratorFrameworkImpl - backgroundOperationsLoop exiting [INFO ] 09:54:57.466 [main] org.apache.zookeeper.ZooKeeper - Session: 0x16d18c861d00003 closed [INFO ] 09:54:57.466 [main-EventThread] org.apache.zookeeper.ClientCnxn - EventThread shut down for session: 0x16d18c861d00003 Exception in thread "main" java.lang.NullPointerException at java.util.regex.Matcher.getTextLength(Matcher.java:1283) at java.util.regex.Matcher.reset(Matcher.java:309) at java.util.regex.Matcher.<init>(Matcher.java:229) at java.util.regex.Pattern.matcher(Pattern.java:1093) at org.yaml.snakeyaml.reader.StreamReader.checkPrintable(StreamReader.java:64) at org.yaml.snakeyaml.reader.StreamReader.<init>(StreamReader.java:47) at org.yaml.snakeyaml.Yaml.loadAs(Yaml.java:427) at org.apache.shardingsphere.core.yaml.engine.YamlEngine.unmarshal(YamlEngine.java:87) at org.apache.shardingsphere.orchestration.internal.registry.config.service.ConfigurationService.loadAuthentication(ConfigurationService.java:244) at org.apache.shardingsphere.shardingproxy.Bootstrap.startWithRegistryCenter(Bootstrap.java:110) at org.apache.shardingsphere.shardingproxy.Bootstrap.main(Bootstrap.java:80) Does anyone know how to solve this problem?
adc33c4c01d4cfbacfdcadf7bc8c39443614ecd3
66599fcb1d7fecfdffe9b4c7a2a3ffe2eb7a2223
https://github.com/apache/shardingsphere/compare/adc33c4c01d4cfbacfdcadf7bc8c39443614ecd3...66599fcb1d7fecfdffe9b4c7a2a3ffe2eb7a2223
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 5e9b767ddfd..9b60f4813c6 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 @@ -109,11 +109,11 @@ public final class Bootstrap { final Collection<String> shardingSchemaNames, final Map<String, YamlProxyRuleConfiguration> ruleConfigs, final int port) { try (ShardingOrchestrationFacade shardingOrchestrationFacade = new ShardingOrchestrationFacade( new OrchestrationConfigurationYamlSwapper().swap(serverConfig.getOrchestration()), shardingSchemaNames)) { + initShardingOrchestrationFacade(serverConfig, ruleConfigs, shardingOrchestrationFacade); Authentication authentication = shardingOrchestrationFacade.getConfigService().loadAuthentication(); Properties properties = shardingOrchestrationFacade.getConfigService().loadProperties(); ConfigurationLogger.log(authentication); ConfigurationLogger.log(properties); - initShardingOrchestrationFacade(serverConfig, ruleConfigs, shardingOrchestrationFacade); ShardingProxyContext.getInstance().init(authentication, properties); LogicSchemas.getInstance().init(shardingSchemaNames, getSchemaDataSourceParameterMap(shardingOrchestrationFacade), getSchemaRules(shardingOrchestrationFacade), true); initOpenTracing();
['sharding-proxy/sharding-proxy-bootstrap/src/main/java/org/apache/shardingsphere/shardingproxy/Bootstrap.java']
{'.java': 1}
1
1
0
0
1
3,214,984
643,606
82,036
1,118
203
42
2
1
10,815
295
3,588
50
0
0
1970-01-01T00:26:08
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,464
apache/shardingsphere/2999/2981
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2981
https://github.com/apache/shardingsphere/pull/2999
https://github.com/apache/shardingsphere/pull/2999
1
fixes
It doesn't work when set properties for ShardingPreparedStatement.
## 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/apache/incubator-shardingsphere/issues). - Read documentation: [ShardingSphere Doc](https://shardingsphere.apache.org/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.RC3 ### Which project did you use? Sharding-JDBC or Sharding-Proxy? > Sharding-JDBC ### Expected behavior ### Actual behavior > When set queryTimeout property for ShardingPreparedStatement, it doesn't work. ### Reason analyze (If you can) > Because when ShardingPreparedStatement is created, there is no actual PreparedStatement in ShardingPreparedStatement. Only when you call execute() or executeQuery(), PreparedStatement is created. So before execute() is called, any assignment for PreparedStatement will not work. ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc. > One solution is to create PreparedStatement once ShardingPreparedStatement is created. You need to split function of initPreparedStatementExecutor() in ShardingPreparedStatement. Here are related codes in ShardingPreparedStatement: ``` public ShardingPreparedStatement(final ShardingConnection connection, final String sql) { this(connection, sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT, false); } --- @Override public ResultSet executeQuery() throws SQLException { ResultSet result; try { clearPrevious(); shard(); initPreparedStatementExecutor(); MergeEngine mergeEngine = MergeEngineFactory.newInstance(connection.getRuntimeContext().getDatabaseType(), connection.getRuntimeContext().getRule(), sqlRouteResult, connection.getRuntimeContext().getMetaData().getTables(), preparedStatementExecutor.executeQuery()); result = getResultSet(mergeEngine); } finally { clearBatch(); } currentResultSet = result; return result; } --- private void initPreparedStatementExecutor() throws SQLException { preparedStatementExecutor.init(sqlRouteResult); setParametersForStatements(); } --- In PreparedStatementExecutor.java public void init(final SQLRouteResult routeResult) throws SQLException { setOptimizedStatement(routeResult.getShardingStatement()); getExecuteGroups().addAll(obtainExecuteGroups(routeResult.getRouteUnits())); cacheStatements(); } ``` ### Example codes for reproduce this issue (such as a github link).
0c0e2713a8aa272881713aebb9a2229432913040
ff587fe073514654dda8bbedc134984a1c50b611
https://github.com/apache/shardingsphere/compare/0c0e2713a8aa272881713aebb9a2229432913040...ff587fe073514654dda8bbedc134984a1c50b611
diff --git a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/ShardingPreparedStatement.java b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/ShardingPreparedStatement.java index 734190d36b4..7f3707ca987 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/ShardingPreparedStatement.java +++ b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/ShardingPreparedStatement.java @@ -197,6 +197,7 @@ public final class ShardingPreparedStatement extends AbstractShardingPreparedSta private void initPreparedStatementExecutor() throws SQLException { preparedStatementExecutor.init(sqlRouteResult); setParametersForStatements(); + replayMethodForStatements(); } private void setParametersForStatements() { @@ -205,6 +206,12 @@ public final class ShardingPreparedStatement extends AbstractShardingPreparedSta } } + private void replayMethodForStatements() { + for (Statement each : preparedStatementExecutor.getStatements()) { + replayMethodsInvocation(each); + } + } + private void clearPrevious() throws SQLException { preparedStatementExecutor.clear(); } 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 c3ffeadb672..eb97ad4706f 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 @@ -219,4 +219,16 @@ public final class ShardingPreparedStatementTest extends AbstractShardingJDBCDat assertThat(result.length, is(0)); } } + + @Test + public void assertInitPreparedStatementExecutorWithReplayMethod() throws SQLException { + String sql = "SELECT item_id from t_order_item where user_id = ? and order_id= ? and status = 'BATCH'"; + try (PreparedStatement preparedStatement = getShardingDataSource().getConnection().prepareStatement(sql)) { + preparedStatement.setQueryTimeout(1); + preparedStatement.setInt(1, 11); + preparedStatement.setInt(2, 11); + preparedStatement.executeQuery(); + assertThat(preparedStatement.getQueryTimeout(), is(1)); + } + } }
['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/ShardingPreparedStatement.java']
{'.java': 2}
2
2
0
0
2
3,082,673
617,403
78,464
1,071
229
38
7
1
3,027
285
566
65
2
1
1970-01-01T00:26:07
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,503
apache/shardingsphere/1727/1715
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1715
https://github.com/apache/shardingsphere/pull/1727
https://github.com/apache/shardingsphere/pull/1727
1
fixes
error when Logic table have the same name as Actual table .
### update it looks like a driver compatibility problem with `mysql-connector-java` of 6.0.6 or above the issue title should updated in some days --- i just use database sharding not table sharding, but when Logic table have the same name as Actual table, some error occurs ``` Caused by: java.sql.SQLException: Column name pattern can not be NULL or empty. ``` here is my config of yaml ```yaml shardingRule: tables: # same name as Actual table, but when i use ms_ds${1..2}.t_user1, it will be ok # but when i change table name in mysql to t_user1,then ms_ds${1..2}.t_user1 does not work either t_user: actualDataNodes: ms_ds${1..2}.t_user databaseStrategy: inline: shardingColumn: id algorithmExpression: ms_ds${id % 2 + 1} keyGeneratorColumnName: id ``` i think it may be a bug
c19f40f8c15571a6c2a7784985e34cc9f37f211e
ba3b92287556ae99825f67e04ff75223d429beba
https://github.com/apache/shardingsphere/compare/c19f40f8c15571a6c2a7784985e34cc9f37f211e...ba3b92287556ae99825f67e04ff75223d429beba
diff --git a/sharding-core/src/main/java/io/shardingsphere/core/metadata/table/executor/TableMetaDataLoader.java b/sharding-core/src/main/java/io/shardingsphere/core/metadata/table/executor/TableMetaDataLoader.java index db34b6f2696..19cda450549 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/metadata/table/executor/TableMetaDataLoader.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/metadata/table/executor/TableMetaDataLoader.java @@ -133,7 +133,7 @@ public final class TableMetaDataLoader { private List<ColumnMetaData> getColumnMetaDataList(final Connection connection, final String catalog, final String actualTableName) throws SQLException { List<ColumnMetaData> result = new LinkedList<>(); Collection<String> primaryKeys = getPrimaryKeys(connection, catalog, actualTableName); - try (ResultSet resultSet = connection.getMetaData().getColumns(catalog, null, actualTableName, null)) { + try (ResultSet resultSet = connection.getMetaData().getColumns(catalog, null, actualTableName, "%")) { while (resultSet.next()) { String columnName = resultSet.getString("COLUMN_NAME"); String columnType = resultSet.getString("TYPE_NAME");
['sharding-core/src/main/java/io/shardingsphere/core/metadata/table/executor/TableMetaDataLoader.java']
{'.java': 1}
1
1
0
0
1
2,399,845
499,639
66,532
871
224
46
2
1
869
123
227
27
0
2
1970-01-01T00:25:47
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,476
apache/shardingsphere/2541/2142
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2142
https://github.com/apache/shardingsphere/pull/2541
https://github.com/apache/shardingsphere/pull/2541
1
fixes
OpenTracingSQLExecutionHook.toStringList NullPointerException
## 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.0.1 ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-JDBC ### Expected behavior sharding-opentracing log trace without effect main execute ### Actual behavior log trace throw NullPointerException effect sql execute ### Reason analyze (If you can) OpenTracingSQLExecutionHook.toStringList method, when params has null, such as insert, call guava Joiner.toString throw NullPointerException ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc. As above ### Example codes for reproduce this issue (such as a github link). As above
a52c6575d18103f1b2dbce21c8939b43fa6c6fbf
c2f4425ee749a288078c5c3045fc984e691ae6c8
https://github.com/apache/shardingsphere/compare/a52c6575d18103f1b2dbce21c8939b43fa6c6fbf...c2f4425ee749a288078c5c3045fc984e691ae6c8
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 0e2589543c7..edd0ad6018a 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 @@ -64,7 +64,7 @@ public final class OpenTracingSQLExecutionHook implements SQLExecutionHook { if (null == parameterSets || parameterSets.isEmpty()) { return ""; } - return String.format("[%s]", Joiner.on(", ").join(parameterSets)); + return String.format("[%s]", Joiner.on(", ").useForNull("Null").join(parameterSets)); } @Override
['sharding-opentracing/src/main/java/org/apache/shardingsphere/opentracing/hook/OpenTracingSQLExecutionHook.java']
{'.java': 1}
1
1
0
0
1
2,928,154
588,298
75,107
1,033
170
38
2
1
1,272
165
275
28
2
0
1970-01-01T00:26:00
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,466
apache/shardingsphere/2937/2919
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2919
https://github.com/apache/shardingsphere/pull/2937
https://github.com/apache/shardingsphere/pull/2937
1
fixes
When the application restarts,LEAF_SEGMENT Distributed Primary Key Generation Not working properly in RC2
## Bug Report ### Which version of ShardingSphere did you use? sharding-orchestration:4.0.0-RC2 ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-JDBC ### Expected behavior When the program restarts, the primary key of LEAF_SEGMENT distribution can be generated normally. ### Actual behavior When the program restarts, the program throws a null pointer exception, ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc. Caused by: java.lang.NullPointerException at org.apache.shardingsphere.orchestration.reg.zookeeper.curator.CuratorZookeeperRegistryCenter.tryLock(CuratorZookeeperRegistryCenter.java:306) at org.apache.shardingsphere.orchestration.internal.keygen.LeafSegmentKeyGenerator.incrementCacheId(LeafSegmentKeyGenerator.java:136) ### Reason analyze (If you can) When the program restarts, **CuratorZookeeperRegistryCenter leafLock is not initialized properly,** related code: 1. [LeafSegmentKeyGenerator.java#L95](https://github.com/apache/incubator-shardingsphere/blob/dev/sharding-orchestration/sharding-orchestration-core/src/main/java/org/apache/shardingsphere/orchestration/internal/keygen/LeafSegmentKeyGenerator.java#L95) 2. [CuratorZookeeperRegistryCenter.java:#306](https://github.com/apache/incubator-shardingsphere/blob/dev/sharding-orchestration/sharding-orchestration-reg/sharding-orchestration-reg-zookeeper-curator/src/main/java/org/apache/shardingsphere/orchestration/reg/zookeeper/curator/CuratorZookeeperRegistryCenter.java#L306)
f7c5a50a2f3b79d9569b4a418475f74609769c0f
9fc2e9160b65d44a1d0c162a8d95ba9721117e07
https://github.com/apache/shardingsphere/compare/f7c5a50a2f3b79d9569b4a418475f74609769c0f...9fc2e9160b65d44a1d0c162a8d95ba9721117e07
diff --git a/sharding-orchestration/sharding-orchestration-core/src/main/java/org/apache/shardingsphere/orchestration/internal/keygen/LeafSegmentKeyGenerator.java b/sharding-orchestration/sharding-orchestration-core/src/main/java/org/apache/shardingsphere/orchestration/internal/keygen/LeafSegmentKeyGenerator.java index c0257790749..8352d22f5ba 100644 --- a/sharding-orchestration/sharding-orchestration-core/src/main/java/org/apache/shardingsphere/orchestration/internal/keygen/LeafSegmentKeyGenerator.java +++ b/sharding-orchestration/sharding-orchestration-core/src/main/java/org/apache/shardingsphere/orchestration/internal/keygen/LeafSegmentKeyGenerator.java @@ -38,119 +38,125 @@ import java.util.concurrent.SynchronousQueue; * @author wangguangyuan */ public final class LeafSegmentKeyGenerator implements ShardingKeyGenerator { - + private static final String DEFAULT_NAMESPACE = "leaf_segment"; - + private static final String DEFAULT_STEP = "10000"; - + private static final String DEFAULT_INITIAL_VALUE = "1"; - + private static final String DEFAULT_REGISTRY_CENTER = "zookeeper"; - - private static final float DEFAULT_THRESHOLD = 0.5F; - + private static final String SLANTING_BAR = "/"; - + private static final String REGULAR_PATTERN = "^((?!/).)*$"; - + private final ExecutorService incrementCacheIdExecutor; - + private final SynchronousQueue<Long> cacheIdQueue; - + private RegistryCenter leafRegistryCenter; - + private long id; - + private long step; - + @Getter @Setter private Properties properties = new Properties(); - + public LeafSegmentKeyGenerator() { incrementCacheIdExecutor = Executors.newSingleThreadExecutor(); cacheIdQueue = new SynchronousQueue<>(); } - + @Override public String getType() { return "LEAF_SEGMENT"; } - + @Override public synchronized Comparable<?> generateKey() { String leafKey = getLeafKey(); if (null == leafRegistryCenter) { initLeafSegmentKeyGenerator(leafKey); - return id; + }else{ + increaseIdWhenLeafKeyStoredInCenter(leafKey); } - increaseIdWhenLeafKeyStoredInCenter(leafKey); return id; } - + private void initLeafSegmentKeyGenerator(final String leafKey) { RegistryCenterConfiguration leafConfiguration = getRegistryCenterConfiguration(); leafRegistryCenter = new RegistryCenterServiceLoader().load(leafConfiguration); - if (leafRegistryCenter.isExisted(leafKey)) { - id = incrementCacheId(leafKey, getStep()); - } else { - id = getInitialValue(); - leafRegistryCenter.persist(leafKey, String.valueOf(id)); - leafRegistryCenter.initLock(leafKey); - } step = getStep(); + id = initializeId(leafKey); + initializeLeafKeyInCenter(leafKey, id, step); + initializeCacheIdAsynchronous(id, step); } - + private void increaseIdWhenLeafKeyStoredInCenter(final String leafKey) { + if ((id % step) == 0) { + id = tryTakeCacheId(); + incrementCacheIdAsynchronous(leafKey, step - (id % step)); + } ++id; - if (((id % step) >= (step * DEFAULT_THRESHOLD - 1)) && cacheIdQueue.isEmpty()) { - incrementCacheIdAsynchronous(leafKey, step); + } + + private long initializeId(final String leafKey){ + if (leafRegistryCenter.isExisted(leafKey)) { + return Long.parseLong(leafRegistryCenter.getDirectly(leafKey))+1; + } else { + return getInitialValue(); } - if ((id % step) == (step - 1)) { - id = tryTakeCacheId(); + } + + private void initializeLeafKeyInCenter(final String leafKey, final long id, final long step){ + leafRegistryCenter.initLock(leafKey); + while(!leafRegistryCenter.tryLock()){ } + leafRegistryCenter.persist(leafKey, String.valueOf(id + step - id % step)); + leafRegistryCenter.tryRelease(); } - private RegistryCenterConfiguration getRegistryCenterConfiguration() { - RegistryCenterConfiguration result = new RegistryCenterConfiguration(getRegistryCenterType(), properties); - result.setNamespace(DEFAULT_NAMESPACE); - result.setServerLists(getServerList()); - result.setDigest(getDigest()); - return result; - } + private void initializeCacheIdAsynchronous(final long id, final long step){ + incrementCacheIdExecutor.execute(new Runnable() { + @Override + public void run() { + tryPutCacheId(id + step - id % step); + } + }); + } + private void incrementCacheIdAsynchronous(final String leafKey, final long step) { incrementCacheIdExecutor.execute(new Runnable() { @Override public void run() { - long id = incrementCacheId(leafKey, step); - tryPutCacheId(id); + long newId = incrementCacheId(leafKey, step); + tryPutCacheId(newId); } }); } - + + private RegistryCenterConfiguration getRegistryCenterConfiguration() { + RegistryCenterConfiguration result = new RegistryCenterConfiguration(getRegistryCenterType(), properties); + result.setNamespace(DEFAULT_NAMESPACE); + result.setServerLists(getServerList()); + result.setDigest(getDigest()); + return result; + } + @SneakyThrows private long incrementCacheId(final String leafKey, final long step) { - long result = Long.MIN_VALUE; - boolean lockIsAcquired = leafRegistryCenter.tryLock(); - if (lockIsAcquired) { - result = updateCacheIdInCenter(leafKey, step); - leafRegistryCenter.tryRelease(); + while(!leafRegistryCenter.tryLock()){ } + long result = updateCacheIdInCenter(leafKey, step); + leafRegistryCenter.tryRelease(); return result; } - - @SneakyThrows - private void tryPutCacheId(final long id) { - cacheIdQueue.put(id); - } - - @SneakyThrows - private long tryTakeCacheId() { - return cacheIdQueue.take(); - } - + private long updateCacheIdInCenter(final String leafKey, final long step) { String cacheIdInString = leafRegistryCenter.getDirectly(leafKey); if (Strings.isNullOrEmpty(cacheIdInString)) { @@ -161,36 +167,46 @@ public final class LeafSegmentKeyGenerator implements ShardingKeyGenerator { leafRegistryCenter.update(leafKey, String.valueOf(result)); return result; } - + + @SneakyThrows + private void tryPutCacheId(final long id) { + cacheIdQueue.put(id); + } + + @SneakyThrows + private long tryTakeCacheId() { + return cacheIdQueue.take(); + } + private long getStep() { long result = Long.parseLong(properties.getProperty("step", DEFAULT_STEP)); Preconditions.checkArgument(result > 0L && result < Long.MAX_VALUE); return result; } - + private long getInitialValue() { long result = Long.parseLong(properties.getProperty("initialValue", DEFAULT_INITIAL_VALUE)); Preconditions.checkArgument(result >= 0L && result < Long.MAX_VALUE); return result; } - + private String getLeafKey() { String leafKey = properties.getProperty("leafKey"); Preconditions.checkArgument(!Strings.isNullOrEmpty(leafKey)); Preconditions.checkArgument(leafKey.matches(REGULAR_PATTERN)); return SLANTING_BAR + leafKey; } - + private String getServerList() { String result = properties.getProperty("serverList"); Preconditions.checkArgument(!Strings.isNullOrEmpty(result)); return result; } - + private String getDigest() { return properties.getProperty("digest"); } - + private String getRegistryCenterType() { return properties.getProperty("registryCenterType", DEFAULT_REGISTRY_CENTER); } diff --git a/sharding-orchestration/sharding-orchestration-core/src/test/java/org/apache/shardingsphere/orchestration/internal/keygen/LeafSegmentKeyGeneratorTest.java b/sharding-orchestration/sharding-orchestration-core/src/test/java/org/apache/shardingsphere/orchestration/internal/keygen/LeafSegmentKeyGeneratorTest.java index 789248c9ee9..fafca66265c 100644 --- a/sharding-orchestration/sharding-orchestration-core/src/test/java/org/apache/shardingsphere/orchestration/internal/keygen/LeafSegmentKeyGeneratorTest.java +++ b/sharding-orchestration/sharding-orchestration-core/src/test/java/org/apache/shardingsphere/orchestration/internal/keygen/LeafSegmentKeyGeneratorTest.java @@ -17,7 +17,9 @@ package org.apache.shardingsphere.orchestration.internal.keygen; +import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.runners.MethodSorters; import java.util.ArrayList; import java.util.Arrays; @@ -32,6 +34,7 @@ import java.util.concurrent.Executors; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; +@FixMethodOrder(value = MethodSorters.NAME_ASCENDING) public final class LeafSegmentKeyGeneratorTest { private final LeafSegmentKeyGenerator leafSegmentKeyGenerator = new LeafSegmentKeyGenerator(); @@ -54,7 +57,7 @@ public final class LeafSegmentKeyGeneratorTest { Properties properties = new Properties(); properties.setProperty("serverList", "127.0.0.1:2181"); properties.setProperty("initialValue", "100001"); - properties.setProperty("step", "3"); + properties.setProperty("step", "5"); properties.setProperty("digest", ""); properties.setProperty("leafKey", "test_table_1"); properties.setProperty("registryCenterType", "ThirdTestRegistryCenter"); @@ -67,6 +70,42 @@ public final class LeafSegmentKeyGeneratorTest { assertThat(actual, is(expected)); } + @Test + public void assertGenerateKeyWithFirstSpecialStep() { + Properties properties = new Properties(); + properties.setProperty("serverList", "127.0.0.1:2181"); + properties.setProperty("initialValue", "100001"); + properties.setProperty("step", "3"); + properties.setProperty("digest", ""); + properties.setProperty("leafKey", "test_table_6"); + properties.setProperty("registryCenterType", "ThirdTestRegistryCenter"); + leafSegmentKeyGenerator.setProperties(properties); + List<Comparable<?>> expected = Arrays.<Comparable<?>>asList(100001L, 100002L, 100003L, 100004L, 100005L, 100006L, 100007L, 100008L, 100009L, 100010L); + List<Comparable<?>> actual = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + actual.add(leafSegmentKeyGenerator.generateKey()); + } + assertThat(actual, is(expected)); + } + + @Test + public void assertGenerateKeyWithSecondSpecialStep() { + Properties properties = new Properties(); + properties.setProperty("serverList", "127.0.0.1:2181"); + properties.setProperty("initialValue", "100001"); + properties.setProperty("step", "7"); + properties.setProperty("digest", ""); + properties.setProperty("leafKey", "test_table_7"); + properties.setProperty("registryCenterType", "ThirdTestRegistryCenter"); + leafSegmentKeyGenerator.setProperties(properties); + List<Comparable<?>> expected = Arrays.<Comparable<?>>asList(100001L, 100002L, 100003L, 100004L, 100005L, 100006L, 100007L, 100008L, 100009L, 100010L); + List<Comparable<?>> actual = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + actual.add(leafSegmentKeyGenerator.generateKey()); + } + assertThat(actual, is(expected)); + } + @Test public void assertGenerateKeyWithMultipleThreads() throws Exception { int threadNumber = Runtime.getRuntime().availableProcessors() << 1; @@ -127,7 +166,7 @@ public final class LeafSegmentKeyGeneratorTest { properties.setProperty("serverList", "127.0.0.1:2181"); properties.setProperty("initialValue", "100001"); properties.setProperty("digest", ""); - properties.setProperty("leafKey", "test_table_6"); + properties.setProperty("leafKey", "test_table_4"); properties.setProperty("registryCenterType", "ThirdTestRegistryCenter"); leafSegmentKeyGenerator.setProperties(properties); Set<Comparable<?>> actual = new HashSet<>(); @@ -152,7 +191,7 @@ public final class LeafSegmentKeyGeneratorTest { properties.setProperty("serverList", "127.0.0.1:2181"); properties.setProperty("step", "3"); properties.setProperty("digest", ""); - properties.setProperty("leafKey", "test_table_7"); + properties.setProperty("leafKey", "test_table_5"); properties.setProperty("registryCenterType", "ThirdTestRegistryCenter"); leafSegmentKeyGenerator.setProperties(properties); int taskNumber = threadNumber << 2; diff --git a/sharding-orchestration/sharding-orchestration-zookeeper-curator-integration-test/src/test/java/org/apache/shardingsphere/orchestration/zookeeper/curator/integration/test/LeafSegmentKeyGeneratorIT.java b/sharding-orchestration/sharding-orchestration-zookeeper-curator-integration-test/src/test/java/org/apache/shardingsphere/orchestration/zookeeper/curator/integration/test/LeafSegmentKeyGeneratorIT.java index 6ce4c1023c5..5186d979c3f 100644 --- a/sharding-orchestration/sharding-orchestration-zookeeper-curator-integration-test/src/test/java/org/apache/shardingsphere/orchestration/zookeeper/curator/integration/test/LeafSegmentKeyGeneratorIT.java +++ b/sharding-orchestration/sharding-orchestration-zookeeper-curator-integration-test/src/test/java/org/apache/shardingsphere/orchestration/zookeeper/curator/integration/test/LeafSegmentKeyGeneratorIT.java @@ -20,7 +20,9 @@ package org.apache.shardingsphere.orchestration.zookeeper.curator.integration.te import org.apache.shardingsphere.orchestration.internal.keygen.LeafSegmentKeyGenerator; import org.apache.shardingsphere.orchestration.zookeeper.curator.integration.util.EmbedTestingServer; import org.junit.BeforeClass; +import org.junit.FixMethodOrder; import org.junit.Test; +import org.junit.runners.MethodSorters; import java.util.ArrayList; import java.util.Arrays; @@ -40,6 +42,7 @@ import static org.junit.Assert.assertThat; * * @author wangguangyuan */ +@FixMethodOrder(value = MethodSorters.NAME_ASCENDING) public final class LeafSegmentKeyGeneratorIT { private final LeafSegmentKeyGenerator leafSegmentKeyGenerator = new LeafSegmentKeyGenerator(); @@ -67,6 +70,78 @@ public final class LeafSegmentKeyGeneratorIT { assertThat(actual, is(expected)); } + @Test + public void assertGenerateKeyWithFirstSpecialStep() { + Properties properties = new Properties(); + properties.setProperty("serverList", "127.0.0.1:3181"); + properties.setProperty("initialValue", "100001"); + properties.setProperty("step", "5"); + properties.setProperty("digest", ""); + properties.setProperty("leafKey", "test_table_6"); + properties.setProperty("registryCenterType", "zookeeper"); + leafSegmentKeyGenerator.setProperties(properties); + List<Comparable<?>> expected = Arrays.<Comparable<?>>asList(100001L, 100002L, 100003L, 100004L, 100005L, 100006L, 100007L, 100008L, 100009L, 100010L); + List<Comparable<?>> actual = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + actual.add(leafSegmentKeyGenerator.generateKey()); + } + assertThat(actual, is(expected)); + } + + @Test + public void assertGenerateKeyWithFirstSpecialStepAgain() { + Properties properties = new Properties(); + properties.setProperty("serverList", "127.0.0.1:3181"); + properties.setProperty("initialValue", "100001"); + properties.setProperty("step", "5"); + properties.setProperty("digest", ""); + properties.setProperty("leafKey", "test_table_6"); + properties.setProperty("registryCenterType", "zookeeper"); + leafSegmentKeyGenerator.setProperties(properties); + List<Comparable<?>> expected = Arrays.<Comparable<?>>asList(100011L, 100012L, 100013L, 100014L, 100015L, 100016L, 100017L, 100018L, 100019L, 100020L); + List<Comparable<?>> actual = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + actual.add(leafSegmentKeyGenerator.generateKey()); + } + assertThat(actual, is(expected)); + } + + @Test + public void assertGenerateKeyWithSecondSpecialStep() { + Properties properties = new Properties(); + properties.setProperty("serverList", "127.0.0.1:3181"); + properties.setProperty("initialValue", "100001"); + properties.setProperty("step", "7"); + properties.setProperty("digest", ""); + properties.setProperty("leafKey", "test_table_7"); + properties.setProperty("registryCenterType", "zookeeper"); + leafSegmentKeyGenerator.setProperties(properties); + List<Comparable<?>> expected = Arrays.<Comparable<?>>asList(100001L, 100002L, 100003L, 100004L, 100005L, 100006L, 100007L, 100008L, 100009L, 100010L); + List<Comparable<?>> actual = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + actual.add(leafSegmentKeyGenerator.generateKey()); + } + assertThat(actual, is(expected)); + } + + @Test + public void assertGenerateKeyWithSecondSpecialStepAgain() { + Properties properties = new Properties(); + properties.setProperty("serverList", "127.0.0.1:3181"); + properties.setProperty("initialValue", "100001"); + properties.setProperty("step", "7"); + properties.setProperty("digest", ""); + properties.setProperty("leafKey", "test_table_7"); + properties.setProperty("registryCenterType", "zookeeper"); + leafSegmentKeyGenerator.setProperties(properties); + List<Comparable<?>> expected = Arrays.<Comparable<?>>asList(100017L, 100018L, 100019L, 100020L, 100021L, 100022L, 100023L, 100024L, 100025L, 100026L); + List<Comparable<?>> actual = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + actual.add(leafSegmentKeyGenerator.generateKey()); + } + assertThat(actual, is(expected)); + } + @Test public void assertGenerateKeyWithMultipleThreads() throws Exception { int threadNumber = Runtime.getRuntime().availableProcessors() << 1; @@ -127,7 +202,7 @@ public final class LeafSegmentKeyGeneratorIT { properties.setProperty("serverList", "127.0.0.1:3181"); properties.setProperty("initialValue", "100001"); properties.setProperty("digest", ""); - properties.setProperty("leafKey", "test_table_6"); + properties.setProperty("leafKey", "test_table_4"); properties.setProperty("registryCenterType", "zookeeper"); leafSegmentKeyGenerator.setProperties(properties); Set<Comparable<?>> actual = new HashSet<>(); @@ -152,7 +227,7 @@ public final class LeafSegmentKeyGeneratorIT { properties.setProperty("serverList", "127.0.0.1:3181"); properties.setProperty("step", "3"); properties.setProperty("digest", ""); - properties.setProperty("leafKey", "test_table_7"); + properties.setProperty("leafKey", "test_table_5"); properties.setProperty("registryCenterType", "zookeeper"); leafSegmentKeyGenerator.setProperties(properties); int taskNumber = threadNumber << 2;
['sharding-orchestration/sharding-orchestration-zookeeper-curator-integration-test/src/test/java/org/apache/shardingsphere/orchestration/zookeeper/curator/integration/test/LeafSegmentKeyGeneratorIT.java', 'sharding-orchestration/sharding-orchestration-core/src/main/java/org/apache/shardingsphere/orchestration/internal/keygen/LeafSegmentKeyGenerator.java', 'sharding-orchestration/sharding-orchestration-core/src/test/java/org/apache/shardingsphere/orchestration/internal/keygen/LeafSegmentKeyGeneratorTest.java']
{'.java': 3}
3
3
0
0
3
3,091,686
619,085
78,612
1,069
3,867
819
144
1
1,573
100
369
23
2
0
1970-01-01T00:26:06
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,467
apache/shardingsphere/2918/2917
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2917
https://github.com/apache/shardingsphere/pull/2918
https://github.com/apache/shardingsphere/pull/2918
1
fixes
NullPointerException will occur when bindingtable have no tablerule but have a default datasource
## 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/apache/incubator-shardingsphere/issues). - Read documentation: [ShardingSphere Doc](https://shardingsphere.apache.org/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? the dev branch ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-JDBC ### Expected behavior can work and not occur NullPointerException ### Actual behavior occur a NullPointerException ### Reason analyze (If you can) the initialization of bindingTableRules of ShardingRule use broadcastTables when broadcastTables have not been initialized ### 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). > Map<String, DataSource> dataSourceMap = new HashMap<>(); dataSourceMap.put("master_0", getMysqlDatasource("demo_ds_master_0")); ShardingRuleConfiguration configuration = new ShardingRuleConfiguration(); configuration.setBindingTableGroups(Arrays.asList("user","user_detail")); configuration.setDefaultDataSourceName("master_0"); ShardingDataSourceFactory.createDataSource(dataSourceMap,configuration,new Properties());
f666b5782b779ca1bfb993494755c6611e895ae8
9a1631487270a3c95a1daea0263e8b051b96f419
https://github.com/apache/shardingsphere/compare/f666b5782b779ca1bfb993494755c6611e895ae8...9a1631487270a3c95a1daea0263e8b051b96f419
diff --git a/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingRule.java b/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingRule.java index 149c18a9763..a8a9d46b2bb 100644 --- a/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingRule.java +++ b/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingRule.java @@ -78,8 +78,8 @@ public class ShardingRule implements BaseRule { this.ruleConfiguration = shardingRuleConfig; shardingDataSourceNames = new ShardingDataSourceNames(shardingRuleConfig, dataSourceNames); tableRules = createTableRules(shardingRuleConfig); - bindingTableRules = createBindingTableRules(shardingRuleConfig.getBindingTableGroups()); broadcastTables = shardingRuleConfig.getBroadcastTables(); + bindingTableRules = createBindingTableRules(shardingRuleConfig.getBindingTableGroups()); defaultDatabaseShardingStrategy = createDefaultShardingStrategy(shardingRuleConfig.getDefaultDatabaseShardingStrategyConfig()); defaultTableShardingStrategy = createDefaultShardingStrategy(shardingRuleConfig.getDefaultTableShardingStrategyConfig()); defaultShardingKeyGenerator = createDefaultKeyGenerator(shardingRuleConfig.getDefaultKeyGeneratorConfig());
['sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingRule.java']
{'.java': 1}
1
1
0
0
1
3,090,436
618,873
78,577
1,069
195
36
2
1
1,684
176
338
36
2
0
1970-01-01T00:26:06
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,490
apache/shardingsphere/2240/2142
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2142
https://github.com/apache/shardingsphere/pull/2240
https://github.com/apache/shardingsphere/pull/2240
1
fixes
OpenTracingSQLExecutionHook.toStringList NullPointerException
## 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.0.1 ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-JDBC ### Expected behavior sharding-opentracing log trace without effect main execute ### Actual behavior log trace throw NullPointerException effect sql execute ### Reason analyze (If you can) OpenTracingSQLExecutionHook.toStringList method, when params has null, such as insert, call guava Joiner.toString throw NullPointerException ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc. As above ### Example codes for reproduce this issue (such as a github link). As above
dc02d36496e86f000d0def17d1bc2470a33788dc
dfa064cd1ee866ac99ad1f0fd9869456ea242c3f
https://github.com/apache/shardingsphere/compare/dc02d36496e86f000d0def17d1bc2470a33788dc...dfa064cd1ee866ac99ad1f0fd9869456ea242c3f
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 97f835d130f..62e6c4c52b4 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 @@ -61,7 +61,10 @@ public final class OpenTracingSQLExecutionHook implements SQLExecutionHook { } private String toString(final List<Object> parameterSets) { - return parameterSets.isEmpty() ? "" : String.format("[%s]", Joiner.on(", ").join(parameterSets)); + if (null == parameterSets || parameterSets.isEmpty()) { + return ""; + } + return 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 bdfd04af0f5..3e953d72b7a 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 @@ -95,6 +95,29 @@ public final class OpenTracingSQLExecutionHookTest extends BaseOpenTracingHookTe assertThat(actualTags.get(Tags.DB_STATEMENT.getKey()), CoreMatchers.<Object>is("SELECT * FROM success_tbl;")); assertThat(actualTags.get(ShardingTags.DB_BIND_VARIABLES.getKey()), CoreMatchers.<Object>is("[1, 2]")); verify(activeSpan, times(0)).deactivate(); + sqlExecutionHook.start(createRouteUnit("success_ds", "SELECT * FROM success_tbl;", null), dataSourceMetaData, true, null); + sqlExecutionHook.finishSuccess(); + } + + @Test + public void assertExecuteSuccessForTrunkThreadWhenParamsIsNull() { + DataSourceMetaData dataSourceMetaData = mock(DataSourceMetaData.class); + when(dataSourceMetaData.getHostName()).thenReturn("localhost"); + when(dataSourceMetaData.getPort()).thenReturn(8888); + sqlExecutionHook.start(createRouteUnit("success_ds", "SELECT * FROM success_tbl;", null), dataSourceMetaData, true, null); + sqlExecutionHook.finishSuccess(); + MockSpan actual = getActualSpan(); + assertThat(actual.operationName(), is("/Sharding-Sphere/executeSQL/")); + Map<String, Object> actualTags = actual.tags(); + assertThat(actualTags.get(Tags.COMPONENT.getKey()), CoreMatchers.<Object>is(ShardingTags.COMPONENT_NAME)); + assertThat(actualTags.get(Tags.SPAN_KIND.getKey()), CoreMatchers.<Object>is(Tags.SPAN_KIND_CLIENT)); + assertThat(actualTags.get(Tags.PEER_HOSTNAME.getKey()), CoreMatchers.<Object>is("localhost")); + assertThat(actualTags.get(Tags.PEER_PORT.getKey()), CoreMatchers.<Object>is(8888)); + assertThat(actualTags.get(Tags.DB_TYPE.getKey()), CoreMatchers.<Object>is("sql")); + assertThat(actualTags.get(Tags.DB_INSTANCE.getKey()), CoreMatchers.<Object>is("success_ds")); + assertThat(actualTags.get(Tags.DB_STATEMENT.getKey()), CoreMatchers.<Object>is("SELECT * FROM success_tbl;")); + assertThat(actualTags.get(ShardingTags.DB_BIND_VARIABLES.getKey()), CoreMatchers.<Object>is("")); + verify(activeSpan, times(0)).deactivate(); } @Test
['sharding-opentracing/src/main/java/org/apache/shardingsphere/opentracing/hook/OpenTracingSQLExecutionHook.java', 'sharding-opentracing/src/test/java/org/apache/shardingsphere/opentracing/hook/OpenTracingSQLExecutionHookTest.java']
{'.java': 2}
2
2
0
0
2
3,239,881
654,669
81,986
1,106
282
57
5
1
1,272
165
275
28
2
0
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,469
apache/shardingsphere/2861/2862
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2862
https://github.com/apache/shardingsphere/pull/2861
https://github.com/apache/shardingsphere/pull/2861
1
fixes
Wring rewritten SQL in mulitiple threads
## 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/apache/incubator-shardingsphere/issues). - Read documentation: [ShardingSphere Doc](https://shardingsphere.apache.org/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? ### Which project did you use? Sharding-JDBC or Sharding-Proxy? ### Expected behavior ### Actual behavior ### 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).
9d0af952810e2a102c21b20032d8b91fc82c60c2
cdd3781ea29438775d1c9ee7a747d694417ead59
https://github.com/apache/shardingsphere/compare/9d0af952810e2a102c21b20032d8b91fc82c60c2...cdd3781ea29438775d1c9ee7a747d694417ead59
diff --git a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/SelectEncryptItemTokenGenerator.java b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/SelectEncryptItemTokenGenerator.java index 24e42660d43..174edb4ddf9 100644 --- a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/SelectEncryptItemTokenGenerator.java +++ b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/SelectEncryptItemTokenGenerator.java @@ -38,20 +38,13 @@ import java.util.LinkedList; */ public final class SelectEncryptItemTokenGenerator implements CollectionSQLTokenGenerator<EncryptRule> { - private EncryptRule encryptRule; - - private OptimizedStatement optimizedStatement; - - private boolean isQueryWithCipherColumn; - @Override public Collection<SelectEncryptItemToken> generateSQLTokens(final OptimizedStatement optimizedStatement, final ParameterBuilder parameterBuilder, final EncryptRule rule, final boolean isQueryWithCipherColumn) { if (!isNeedToGenerateSQLToken(optimizedStatement)) { return Collections.emptyList(); } - initParameters(rule, optimizedStatement, isQueryWithCipherColumn); - return createSelectCipherItemTokens(); + return createSelectCipherItemTokens(rule, optimizedStatement, isQueryWithCipherColumn); } private boolean isNeedToGenerateSQLToken(final OptimizedStatement optimizedStatement) { @@ -66,20 +59,14 @@ public final class SelectEncryptItemTokenGenerator implements CollectionSQLToken return optimizedStatement.getSQLStatement() instanceof SelectStatement && !optimizedStatement.getTables().isEmpty(); } - private void initParameters(final EncryptRule rule, final OptimizedStatement optimizedStatement, final boolean isQueryWithCipherColumn) { - encryptRule = rule; - this.optimizedStatement = optimizedStatement; - this.isQueryWithCipherColumn = isQueryWithCipherColumn; - } - - private Collection<SelectEncryptItemToken> createSelectCipherItemTokens() { + private Collection<SelectEncryptItemToken> createSelectCipherItemTokens(final EncryptRule encryptRule, final OptimizedStatement optimizedStatement, final boolean isQueryWithCipherColumn) { Collection<SelectEncryptItemToken> result = new LinkedList<>(); SelectItemsSegment selectItemsSegment = optimizedStatement.getSQLStatement().findSQLSegment(SelectItemsSegment.class).get(); String tableName = optimizedStatement.getTables().getSingleTableName(); Collection<String> logicColumns = encryptRule.getLogicColumns(tableName); for (SelectItemSegment each : selectItemsSegment.getSelectItems()) { if (isLogicColumn(each, logicColumns)) { - result.add(createSelectCipherItemToken(each, tableName)); + result.add(createSelectCipherItemToken(each, tableName, encryptRule, isQueryWithCipherColumn)); } } return result; @@ -89,7 +76,7 @@ public final class SelectEncryptItemTokenGenerator implements CollectionSQLToken return each instanceof ColumnSelectItemSegment && logicColumns.contains(((ColumnSelectItemSegment) each).getName()); } - private SelectEncryptItemToken createSelectCipherItemToken(final SelectItemSegment each, final String tableName) { + private SelectEncryptItemToken createSelectCipherItemToken(final SelectItemSegment each, final String tableName, final EncryptRule encryptRule, final boolean isQueryWithCipherColumn) { String columnName = ((ColumnSelectItemSegment) each).getName(); Optional<String> plainColumn = encryptRule.getPlainColumn(tableName, columnName); if (!isQueryWithCipherColumn && plainColumn.isPresent()) { diff --git a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/UpdateEncryptColumnTokenGenerator.java b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/UpdateEncryptColumnTokenGenerator.java index 56844b8f9ea..7799091aaa3 100644 --- a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/UpdateEncryptColumnTokenGenerator.java +++ b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/UpdateEncryptColumnTokenGenerator.java @@ -41,54 +41,48 @@ import java.util.LinkedList; */ public final class UpdateEncryptColumnTokenGenerator implements CollectionSQLTokenGenerator<EncryptRule> { - private EncryptRule encryptRule; - - private ParameterBuilder parameterBuilder; - @Override public Collection<EncryptColumnToken> generateSQLTokens( final OptimizedStatement optimizedStatement, final ParameterBuilder parameterBuilder, final EncryptRule encryptRule, final boolean isQueryWithCipherColumn) { - initParameter(parameterBuilder, encryptRule); - return optimizedStatement.getSQLStatement() instanceof UpdateStatement ? createUpdateEncryptColumnTokens(optimizedStatement) : Collections.<EncryptColumnToken>emptyList(); - } - - private void initParameter(final ParameterBuilder parameterBuilder, final EncryptRule encryptRule) { - this.parameterBuilder = parameterBuilder; - this.encryptRule = encryptRule; + return optimizedStatement.getSQLStatement() instanceof UpdateStatement + ? createUpdateEncryptColumnTokens(parameterBuilder, encryptRule, optimizedStatement) : Collections.<EncryptColumnToken>emptyList(); } - private Collection<EncryptColumnToken> createUpdateEncryptColumnTokens(final OptimizedStatement optimizedStatement) { + private Collection<EncryptColumnToken> createUpdateEncryptColumnTokens(final ParameterBuilder parameterBuilder, final EncryptRule encryptRule, final OptimizedStatement optimizedStatement) { Collection<EncryptColumnToken> result = new LinkedList<>(); String tableName = optimizedStatement.getTables().getSingleTableName(); for (AssignmentSegment each : ((UpdateStatement) optimizedStatement.getSQLStatement()).getSetAssignment().getAssignments()) { if (encryptRule.getShardingEncryptor(tableName, each.getColumn().getName()).isPresent()) { - result.add(createUpdateEncryptColumnToken(tableName, each)); + result.add(createUpdateEncryptColumnToken(parameterBuilder, encryptRule, tableName, each)); } } return result; } - private EncryptColumnToken createUpdateEncryptColumnToken(final String tableName, final AssignmentSegment assignmentSegment) { + private EncryptColumnToken createUpdateEncryptColumnToken(final ParameterBuilder parameterBuilder, + final EncryptRule encryptRule, final String tableName, final AssignmentSegment assignmentSegment) { return assignmentSegment.getValue() instanceof ParameterMarkerExpressionSegment - ? createUpdateEncryptParameterColumnToken(tableName, assignmentSegment) : createUpdateEncryptLiteralColumnToken(tableName, assignmentSegment); + ? createUpdateEncryptParameterColumnToken(parameterBuilder, encryptRule, tableName, assignmentSegment) + : createUpdateEncryptLiteralColumnToken(encryptRule, tableName, assignmentSegment); } - private EncryptColumnToken createUpdateEncryptParameterColumnToken(final String tableName, final AssignmentSegment assignmentSegment) { + private EncryptColumnToken createUpdateEncryptParameterColumnToken(final ParameterBuilder parameterBuilder, + final EncryptRule encryptRule, final String tableName, final AssignmentSegment assignmentSegment) { UpdateEncryptParameterColumnToken result = new UpdateEncryptParameterColumnToken(assignmentSegment.getColumn().getStartIndex(), assignmentSegment.getStopIndex()); Optional<String> plainColumn = encryptRule.getPlainColumn(tableName, assignmentSegment.getColumn().getName()); if (plainColumn.isPresent()) { result.addUpdateColumn(plainColumn.get()); result.addUpdateColumn(encryptRule.getCipherColumn(tableName, assignmentSegment.getColumn().getName())); - addCipherColumnValueToParameterBuilder(tableName, assignmentSegment); + addCipherColumnValueToParameterBuilder(parameterBuilder, encryptRule, tableName, assignmentSegment); } else { result.addUpdateColumn(encryptRule.getCipherColumn(tableName, assignmentSegment.getColumn().getName())); - setCipherColumnValueToParameterBuilder(tableName, assignmentSegment); + setCipherColumnValueToParameterBuilder(parameterBuilder, encryptRule, tableName, assignmentSegment); } - addAssistedQueryUpdateColumn(tableName, assignmentSegment, result); + addAssistedQueryUpdateColumn(parameterBuilder, encryptRule, tableName, assignmentSegment, result); return result; } - private void addCipherColumnValueToParameterBuilder(final String tableName, final AssignmentSegment assignmentSegment) { + private void addCipherColumnValueToParameterBuilder(final ParameterBuilder parameterBuilder, final EncryptRule encryptRule, final String tableName, final AssignmentSegment assignmentSegment) { int logicColumnValueIndex = ((ParameterMarkerExpressionSegment) assignmentSegment.getValue()).getParameterMarkerIndex(); Object originalColumnValue = parameterBuilder.getOriginalParameters().get(logicColumnValueIndex); Object cipherColumnValue = encryptRule.getEncryptColumnValues( @@ -96,7 +90,7 @@ public final class UpdateEncryptColumnTokenGenerator implements CollectionSQLTok ((BaseParameterBuilder) parameterBuilder).getAddedIndexAndParameters().put(logicColumnValueIndex + 1, cipherColumnValue); } - private void setCipherColumnValueToParameterBuilder(final String tableName, final AssignmentSegment assignmentSegment) { + private void setCipherColumnValueToParameterBuilder(final ParameterBuilder parameterBuilder, final EncryptRule encryptRule, final String tableName, final AssignmentSegment assignmentSegment) { int logicColumnValueIndex = ((ParameterMarkerExpressionSegment) assignmentSegment.getValue()).getParameterMarkerIndex(); Object originalColumnValue = parameterBuilder.getOriginalParameters().get(logicColumnValueIndex); Object cipherColumnValue = encryptRule.getEncryptColumnValues( @@ -104,15 +98,17 @@ public final class UpdateEncryptColumnTokenGenerator implements CollectionSQLTok ((BaseParameterBuilder) parameterBuilder).getReplacedIndexAndParameters().put(logicColumnValueIndex, cipherColumnValue); } - private void addAssistedQueryUpdateColumn(final String tableName, final AssignmentSegment assignmentSegment, final UpdateEncryptParameterColumnToken result) { + private void addAssistedQueryUpdateColumn(final ParameterBuilder parameterBuilder, final EncryptRule encryptRule, + final String tableName, final AssignmentSegment assignmentSegment, final UpdateEncryptParameterColumnToken result) { Optional<String> assistedQueryColumn = encryptRule.getAssistedQueryColumn(tableName, assignmentSegment.getColumn().getName()); if (assistedQueryColumn.isPresent()) { result.addUpdateColumn(assistedQueryColumn.get()); - addAssistedQueryColumnValueToParameterBuilder(tableName, assignmentSegment); + addAssistedQueryColumnValueToParameterBuilder(parameterBuilder, encryptRule, tableName, assignmentSegment); } } - private void addAssistedQueryColumnValueToParameterBuilder(final String tableName, final AssignmentSegment assignmentSegment) { + private void addAssistedQueryColumnValueToParameterBuilder(final ParameterBuilder parameterBuilder, + final EncryptRule encryptRule, final String tableName, final AssignmentSegment assignmentSegment) { int logicColumnValueIndex = ((ParameterMarkerExpressionSegment) assignmentSegment.getValue()).getParameterMarkerIndex(); Object originalColumnValue = parameterBuilder.getOriginalParameters().get(logicColumnValueIndex); Object assistedQueryColumnValue = encryptRule.getEncryptAssistedColumnValues( @@ -120,15 +116,15 @@ public final class UpdateEncryptColumnTokenGenerator implements CollectionSQLTok ((BaseParameterBuilder) parameterBuilder).getAddedIndexAndParameters().put(logicColumnValueIndex + 2, assistedQueryColumnValue); } - private EncryptColumnToken createUpdateEncryptLiteralColumnToken(final String tableName, final AssignmentSegment assignmentSegment) { + private EncryptColumnToken createUpdateEncryptLiteralColumnToken(final EncryptRule encryptRule, final String tableName, final AssignmentSegment assignmentSegment) { UpdateEncryptLiteralColumnToken result = new UpdateEncryptLiteralColumnToken(assignmentSegment.getColumn().getStartIndex(), assignmentSegment.getStopIndex()); - addPlainUpdateColumn(tableName, assignmentSegment, result); - addCipherUpdateColumn(tableName, assignmentSegment, result); - addAssistedQueryUpdateColumn(tableName, assignmentSegment, result); + addPlainUpdateColumn(encryptRule, tableName, assignmentSegment, result); + addCipherUpdateColumn(encryptRule, tableName, assignmentSegment, result); + addAssistedQueryUpdateColumn(encryptRule, tableName, assignmentSegment, result); return result; } - private void addPlainUpdateColumn(final String tableName, final AssignmentSegment assignmentSegment, final UpdateEncryptLiteralColumnToken result) { + private void addPlainUpdateColumn(final EncryptRule encryptRule, final String tableName, final AssignmentSegment assignmentSegment, final UpdateEncryptLiteralColumnToken result) { Object originalColumnValue = ((LiteralExpressionSegment) assignmentSegment.getValue()).getLiterals(); Optional<String> plainColumn = encryptRule.getPlainColumn(tableName, assignmentSegment.getColumn().getName()); if (plainColumn.isPresent()) { @@ -136,14 +132,14 @@ public final class UpdateEncryptColumnTokenGenerator implements CollectionSQLTok } } - private void addCipherUpdateColumn(final String tableName, final AssignmentSegment assignmentSegment, final UpdateEncryptLiteralColumnToken result) { + private void addCipherUpdateColumn(final EncryptRule encryptRule, final String tableName, final AssignmentSegment assignmentSegment, final UpdateEncryptLiteralColumnToken result) { Object originalColumnValue = ((LiteralExpressionSegment) assignmentSegment.getValue()).getLiterals(); Object cipherColumnValue = encryptRule.getEncryptColumnValues( tableName, assignmentSegment.getColumn().getName(), Collections.singletonList(originalColumnValue)).iterator().next(); result.addUpdateColumn(encryptRule.getCipherColumn(tableName, assignmentSegment.getColumn().getName()), cipherColumnValue); } - private void addAssistedQueryUpdateColumn(final String tableName, final AssignmentSegment assignmentSegment, final UpdateEncryptLiteralColumnToken result) { + private void addAssistedQueryUpdateColumn(final EncryptRule encryptRule, final String tableName, final AssignmentSegment assignmentSegment, final UpdateEncryptLiteralColumnToken result) { Object originalColumnValue = ((LiteralExpressionSegment) assignmentSegment.getValue()).getLiterals(); Optional<String> assistedQueryColumn = encryptRule.getAssistedQueryColumn(tableName, assignmentSegment.getColumn().getName()); if (assistedQueryColumn.isPresent()) { diff --git a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/WhereEncryptColumnTokenGenerator.java b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/WhereEncryptColumnTokenGenerator.java index 42ccc261adc..ca88827e730 100644 --- a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/WhereEncryptColumnTokenGenerator.java +++ b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/WhereEncryptColumnTokenGenerator.java @@ -42,58 +42,49 @@ import java.util.Map.Entry; */ public final class WhereEncryptColumnTokenGenerator implements CollectionSQLTokenGenerator<EncryptRule> { - private EncryptRule encryptRule; - - private ParameterBuilder parameterBuilder; - - private boolean isQueryWithCipherColumn; - @Override public Collection<EncryptColumnToken> generateSQLTokens( final OptimizedStatement optimizedStatement, final ParameterBuilder parameterBuilder, final EncryptRule encryptRule, final boolean isQueryWithCipherColumn) { - initParameters(parameterBuilder, encryptRule, isQueryWithCipherColumn); return optimizedStatement instanceof ConditionOptimizedStatement - ? createWhereEncryptColumnTokens((ConditionOptimizedStatement) optimizedStatement) : Collections.<EncryptColumnToken>emptyList(); - } - - private void initParameters(final ParameterBuilder parameterBuilder, final EncryptRule encryptRule, final boolean isQueryWithCipherColumn) { - this.parameterBuilder = parameterBuilder; - this.encryptRule = encryptRule; - this.isQueryWithCipherColumn = isQueryWithCipherColumn; + ? createWhereEncryptColumnTokens(parameterBuilder, encryptRule, isQueryWithCipherColumn, (ConditionOptimizedStatement) optimizedStatement) + : Collections.<EncryptColumnToken>emptyList(); } - private Collection<EncryptColumnToken> createWhereEncryptColumnTokens(final ConditionOptimizedStatement optimizedStatement) { + private Collection<EncryptColumnToken> createWhereEncryptColumnTokens(final ParameterBuilder parameterBuilder, + final EncryptRule encryptRule, final boolean isQueryWithCipherColumn, final ConditionOptimizedStatement optimizedStatement) { Collection<EncryptColumnToken> result = new LinkedList<>(); for (EncryptCondition each : optimizedStatement.getEncryptConditions().getConditions()) { - result.add(createWhereEncryptColumnToken(each)); + result.add(createWhereEncryptColumnToken(parameterBuilder, encryptRule, isQueryWithCipherColumn, each)); } return result; } - private WhereEncryptColumnToken createWhereEncryptColumnToken(final EncryptCondition encryptCondition) { + private WhereEncryptColumnToken createWhereEncryptColumnToken(final ParameterBuilder parameterBuilder, + final EncryptRule encryptRule, final boolean isQueryWithCipherColumn, final EncryptCondition encryptCondition) { List<Object> originalColumnValues = encryptCondition.getValues(parameterBuilder.getOriginalParameters()); if (isQueryWithCipherColumn) { - return createWhereEncryptColumnToken(encryptCondition, originalColumnValues); + return createWhereEncryptColumnToken(parameterBuilder, encryptRule, encryptCondition, originalColumnValues); } - return new WhereEncryptColumnToken(encryptCondition.getStartIndex(), encryptCondition.getStopIndex(), getPlainColumn(encryptCondition, encryptRule), + return new WhereEncryptColumnToken(encryptCondition.getStartIndex(), encryptCondition.getStopIndex(), getPlainColumn(encryptRule, encryptCondition), getPositionValues(encryptCondition.getPositionValueMap().keySet(), originalColumnValues), encryptCondition.getPositionIndexMap().keySet(), encryptCondition.getOperator()); } - private WhereEncryptColumnToken createWhereEncryptColumnToken(final EncryptCondition encryptCondition, final List<Object> originalValues) { - String encryptedColumnName = getEncryptedColumnName(encryptCondition); - List<Object> encryptedColumnValues = getEncryptedColumnValues(encryptCondition, originalValues); + private WhereEncryptColumnToken createWhereEncryptColumnToken(final ParameterBuilder parameterBuilder, + final EncryptRule encryptRule, final EncryptCondition encryptCondition, final List<Object> originalValues) { + String encryptedColumnName = getEncryptedColumnName(encryptRule, encryptCondition); + List<Object> encryptedColumnValues = getEncryptedColumnValues(encryptRule, encryptCondition, originalValues); encryptParameters(encryptCondition.getPositionIndexMap(), encryptedColumnValues, parameterBuilder); return new WhereEncryptColumnToken(encryptCondition.getStartIndex(), encryptCondition.getStopIndex(), encryptedColumnName, getPositionValues(encryptCondition.getPositionValueMap().keySet(), encryptedColumnValues), encryptCondition.getPositionIndexMap().keySet(), encryptCondition.getOperator()); } - private String getEncryptedColumnName(final EncryptCondition encryptCondition) { + private String getEncryptedColumnName(final EncryptRule encryptRule, final EncryptCondition encryptCondition) { Optional<String> assistedQueryColumn = encryptRule.getAssistedQueryColumn(encryptCondition.getTableName(), encryptCondition.getColumnName()); return assistedQueryColumn.isPresent() ? assistedQueryColumn.get() : encryptRule.getCipherColumn(encryptCondition.getTableName(), encryptCondition.getColumnName()); } - private List<Object> getEncryptedColumnValues(final EncryptCondition encryptCondition, final List<Object> originalValues) { + private List<Object> getEncryptedColumnValues(final EncryptRule encryptRule, final EncryptCondition encryptCondition, final List<Object> originalValues) { Optional<String> assistedQueryColumn = encryptRule.getAssistedQueryColumn(encryptCondition.getTableName(), encryptCondition.getColumnName()); return assistedQueryColumn.isPresent() ? encryptRule.getEncryptAssistedColumnValues(encryptCondition.getTableName(), encryptCondition.getColumnName(), originalValues) @@ -116,7 +107,7 @@ public final class WhereEncryptColumnTokenGenerator implements CollectionSQLToke return result; } - private String getPlainColumn(final EncryptCondition encryptCondition, final EncryptRule encryptRule) { + private String getPlainColumn(final EncryptRule encryptRule, final EncryptCondition encryptCondition) { Optional<String> result = encryptRule.getPlainColumn(encryptCondition.getTableName(), encryptCondition.getColumnName()); if (result.isPresent()) { return result.get();
['sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/UpdateEncryptColumnTokenGenerator.java', 'sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/SelectEncryptItemTokenGenerator.java', 'sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/WhereEncryptColumnTokenGenerator.java']
{'.java': 3}
3
3
0
0
3
3,062,612
613,671
78,117
1,063
12,052
2,021
120
3
992
131
213
28
2
0
1970-01-01T00:26:05
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,470
apache/shardingsphere/2824/2823
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2823
https://github.com/apache/shardingsphere/pull/2824
https://github.com/apache/shardingsphere/pull/2824
1
fixes
Can not rewrite correctly when use plainColumn
## 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/apache/incubator-shardingsphere/issues). - Read documentation: [ShardingSphere Doc](https://shardingsphere.apache.org/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.RC2 ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-JDBC ### Expected behavior When use plainColumn, The SQL will be rewritten to Select plainColumn from tb. ### Actual behavior When use plainColumn, The SQL will be rewritten to Select cipherColumn from tb. ### 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).
db5780bb8081744f7d5603503896ebc708e89d60
3eb8c5d51be11ce4b08d845fd14c8c2629a64ec6
https://github.com/apache/shardingsphere/compare/db5780bb8081744f7d5603503896ebc708e89d60...3eb8c5d51be11ce4b08d845fd14c8c2629a64ec6
diff --git a/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/EncryptRule.java b/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/EncryptRule.java index f0d7cd4b10a..6944d756e57 100644 --- a/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/EncryptRule.java +++ b/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/EncryptRule.java @@ -266,6 +266,19 @@ public final class EncryptRule implements BaseRule { return tables.get(logicTable).getLogicAndCipherColumns(); } + /** + * Get logic and plain columns. + * + * @param logicTable logic table + * @return logic and plain columns + */ + public Map<String, String> getLogicAndPlainColumns(final String logicTable) { + if (!tables.containsKey(logicTable)) { + return Collections.emptyMap(); + } + return tables.get(logicTable).getLogicAndPlainColumns(); + } + /** * Get encrypt assisted column values. * diff --git a/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/strategy/encrypt/EncryptTable.java b/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/strategy/encrypt/EncryptTable.java index afc4f4e61bf..a68973c4de5 100644 --- a/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/strategy/encrypt/EncryptTable.java +++ b/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/strategy/encrypt/EncryptTable.java @@ -198,4 +198,22 @@ public final class EncryptTable { } }); } + + /** + * Get logic and plain columns. + * + * @return logic and plain columns + */ + public Map<String, String> getLogicAndPlainColumns() { + return Maps.transformValues(columns, new Function<EncryptColumn, String>() { + + @Override + public String apply(final EncryptColumn input) { + if (input.getPlainColumn().isPresent()) { + return input.getPlainColumn().get(); + } + throw new ShardingException("Plain column is null."); + } + }); + } } diff --git a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/EncryptTokenGenerateEngine.java b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/EncryptTokenGenerateEngine.java index 447debc09c8..decd14ba02d 100644 --- a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/EncryptTokenGenerateEngine.java +++ b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/EncryptTokenGenerateEngine.java @@ -23,7 +23,7 @@ import org.apache.shardingsphere.core.rewrite.token.generator.InsertSetCipherCol import org.apache.shardingsphere.core.rewrite.token.generator.InsertSetQueryAndPlainColumnsTokenGenerator; import org.apache.shardingsphere.core.rewrite.token.generator.InsertValuesTokenGenerator; import org.apache.shardingsphere.core.rewrite.token.generator.SQLTokenGenerator; -import org.apache.shardingsphere.core.rewrite.token.generator.SelectCipherItemTokenGenerator; +import org.apache.shardingsphere.core.rewrite.token.generator.SelectEncryptItemTokenGenerator; import org.apache.shardingsphere.core.rewrite.token.generator.UpdateEncryptColumnTokenGenerator; import org.apache.shardingsphere.core.rewrite.token.generator.WhereEncryptColumnTokenGenerator; import org.apache.shardingsphere.core.rule.EncryptRule; @@ -41,7 +41,7 @@ public final class EncryptTokenGenerateEngine extends SQLTokenGenerateEngine<Enc private static final Collection<SQLTokenGenerator> SQL_TOKEN_GENERATORS = new LinkedList<>(); static { - SQL_TOKEN_GENERATORS.add(new SelectCipherItemTokenGenerator()); + SQL_TOKEN_GENERATORS.add(new SelectEncryptItemTokenGenerator()); SQL_TOKEN_GENERATORS.add(new UpdateEncryptColumnTokenGenerator()); SQL_TOKEN_GENERATORS.add(new WhereEncryptColumnTokenGenerator()); SQL_TOKEN_GENERATORS.add(new InsertCipherNameTokenGenerator()); diff --git a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/SelectCipherItemTokenGenerator.java b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/SelectEncryptItemTokenGenerator.java similarity index 70% rename from sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/SelectCipherItemTokenGenerator.java rename to sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/SelectEncryptItemTokenGenerator.java index 45f1ff485ca..24e42660d43 100644 --- a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/SelectCipherItemTokenGenerator.java +++ b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/SelectEncryptItemTokenGenerator.java @@ -24,7 +24,7 @@ import org.apache.shardingsphere.core.parse.sql.segment.dml.item.SelectItemSegme import org.apache.shardingsphere.core.parse.sql.segment.dml.item.SelectItemsSegment; import org.apache.shardingsphere.core.parse.sql.statement.dml.SelectStatement; import org.apache.shardingsphere.core.rewrite.builder.ParameterBuilder; -import org.apache.shardingsphere.core.rewrite.token.pojo.SelectCipherItemToken; +import org.apache.shardingsphere.core.rewrite.token.pojo.SelectEncryptItemToken; import org.apache.shardingsphere.core.rule.EncryptRule; import java.util.Collection; @@ -36,19 +36,21 @@ import java.util.LinkedList; * * @author panjuan */ -public final class SelectCipherItemTokenGenerator implements CollectionSQLTokenGenerator<EncryptRule> { +public final class SelectEncryptItemTokenGenerator implements CollectionSQLTokenGenerator<EncryptRule> { private EncryptRule encryptRule; private OptimizedStatement optimizedStatement; + private boolean isQueryWithCipherColumn; + @Override - public Collection<SelectCipherItemToken> generateSQLTokens(final OptimizedStatement optimizedStatement, - final ParameterBuilder parameterBuilder, final EncryptRule rule, final boolean isQueryWithCipherColumn) { + public Collection<SelectEncryptItemToken> generateSQLTokens(final OptimizedStatement optimizedStatement, + final ParameterBuilder parameterBuilder, final EncryptRule rule, final boolean isQueryWithCipherColumn) { if (!isNeedToGenerateSQLToken(optimizedStatement)) { return Collections.emptyList(); } - initParameters(rule, optimizedStatement); + initParameters(rule, optimizedStatement, isQueryWithCipherColumn); return createSelectCipherItemTokens(); } @@ -64,13 +66,14 @@ public final class SelectCipherItemTokenGenerator implements CollectionSQLTokenG return optimizedStatement.getSQLStatement() instanceof SelectStatement && !optimizedStatement.getTables().isEmpty(); } - private void initParameters(final EncryptRule rule, final OptimizedStatement optimizedStatement) { + private void initParameters(final EncryptRule rule, final OptimizedStatement optimizedStatement, final boolean isQueryWithCipherColumn) { encryptRule = rule; this.optimizedStatement = optimizedStatement; + this.isQueryWithCipherColumn = isQueryWithCipherColumn; } - private Collection<SelectCipherItemToken> createSelectCipherItemTokens() { - Collection<SelectCipherItemToken> result = new LinkedList<>(); + private Collection<SelectEncryptItemToken> createSelectCipherItemTokens() { + Collection<SelectEncryptItemToken> result = new LinkedList<>(); SelectItemsSegment selectItemsSegment = optimizedStatement.getSQLStatement().findSQLSegment(SelectItemsSegment.class).get(); String tableName = optimizedStatement.getTables().getSingleTableName(); Collection<String> logicColumns = encryptRule.getLogicColumns(tableName); @@ -86,8 +89,12 @@ public final class SelectCipherItemTokenGenerator implements CollectionSQLTokenG return each instanceof ColumnSelectItemSegment && logicColumns.contains(((ColumnSelectItemSegment) each).getName()); } - private SelectCipherItemToken createSelectCipherItemToken(final SelectItemSegment each, final String tableName) { - return new SelectCipherItemToken(each.getStartIndex(), - each.getStopIndex(), encryptRule.getCipherColumn(tableName, ((ColumnSelectItemSegment) each).getName())); + private SelectEncryptItemToken createSelectCipherItemToken(final SelectItemSegment each, final String tableName) { + String columnName = ((ColumnSelectItemSegment) each).getName(); + Optional<String> plainColumn = encryptRule.getPlainColumn(tableName, columnName); + if (!isQueryWithCipherColumn && plainColumn.isPresent()) { + return new SelectEncryptItemToken(each.getStartIndex(), each.getStopIndex(), plainColumn.get()); + } + return new SelectEncryptItemToken(each.getStartIndex(), each.getStopIndex(), encryptRule.getCipherColumn(tableName, columnName)); } } diff --git a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/pojo/SelectCipherItemToken.java b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/pojo/SelectEncryptItemToken.java similarity index 86% rename from sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/pojo/SelectCipherItemToken.java rename to sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/pojo/SelectEncryptItemToken.java index 8202e68b27f..89117ebc6fd 100644 --- a/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/pojo/SelectCipherItemToken.java +++ b/sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/pojo/SelectEncryptItemToken.java @@ -25,13 +25,13 @@ import lombok.Getter; * @author panjuan */ @Getter -public final class SelectCipherItemToken extends SQLToken implements Substitutable { +public final class SelectEncryptItemToken extends SQLToken implements Substitutable { private final int stopIndex; private final String selectItemName; - public SelectCipherItemToken(final int startIndex, final int stopIndex, final String selectItemName) { + public SelectEncryptItemToken(final int startIndex, final int stopIndex, final String selectItemName) { super(startIndex); this.stopIndex = stopIndex; this.selectItemName = selectItemName; diff --git a/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/rewriter/ShardingSQLRewriteEngineTest.java b/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/rewriter/ShardingSQLRewriteEngineTest.java index aa33067941b..75fae0b4c9e 100644 --- a/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/rewriter/ShardingSQLRewriteEngineTest.java +++ b/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/rewriter/ShardingSQLRewriteEngineTest.java @@ -901,7 +901,7 @@ public final class ShardingSQLRewriteEngineTest { @Test public void assertRewriteSelectInWithShardingEncryptorWithPlain() { SQLRewriteEngine rewriteEngine = createSQLRewriteEngine(createSQLRouteResultForSelectInWithShardingEncryptor(), "SELECT id FROM table_z WHERE id in (3,5)", Collections.emptyList(), false); - assertThat(rewriteEngine.generateSQL(null, logicTableAndActualTables).getSql(), is("SELECT cipher FROM table_z WHERE plain IN ('3', '5')")); + assertThat(rewriteEngine.generateSQL(null, logicTableAndActualTables).getSql(), is("SELECT plain FROM table_z WHERE plain IN ('3', '5')")); } private SQLRouteResult createSQLRouteResultForSelectInWithShardingEncryptor() { @@ -1030,7 +1030,7 @@ public final class ShardingSQLRewriteEngineTest { public void assertRewriteSelectEqualWithShardingEncryptorWithPlain() { SQLRewriteEngine rewriteEngine = createSQLRewriteEngine( createSQLRouteResultForSelectEqualWithShardingEncryptor(), "SELECT id FROM table_z WHERE id=? AND name=?", Arrays.<Object>asList(1, "x"), false); - assertThat(rewriteEngine.generateSQL().getSql(), is("SELECT cipher FROM table_z WHERE plain = ? AND name=?")); + assertThat(rewriteEngine.generateSQL().getSql(), is("SELECT plain FROM table_z WHERE plain = ? AND name=?")); assertThat(getParameterBuilder(rewriteEngine).getParameters().get(0), is((Object) 1)); } @@ -1062,7 +1062,7 @@ public final class ShardingSQLRewriteEngineTest { public void assertRewriteSelectInWithShardingEncryptorWithParameterWithPlain() { SQLRewriteEngine rewriteEngine = createSQLRewriteEngine( createSQLRouteResultForSelectInWithShardingEncryptorWithParameter(), "SELECT id FROM table_z WHERE id in (?, ?) or id = 3", Arrays.<Object>asList(1, 2), false); - assertThat(rewriteEngine.generateSQL(null, logicTableAndActualTables).getSql(), is("SELECT cipher FROM table_z WHERE plain IN (?, ?) or plain = '3'")); + assertThat(rewriteEngine.generateSQL(null, logicTableAndActualTables).getSql(), is("SELECT plain FROM table_z WHERE plain IN (?, ?) or plain = '3'")); assertThat(getParameterBuilder(rewriteEngine).getParameters().get(0), is((Object) 1)); assertThat(getParameterBuilder(rewriteEngine).getParameters().get(1), is((Object) 2)); } diff --git a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/adapter/AbstractResultSetAdapter.java b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/adapter/AbstractResultSetAdapter.java index 0110b8cdb8b..46cc402d947 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/adapter/AbstractResultSetAdapter.java +++ b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/adapter/AbstractResultSetAdapter.java @@ -20,6 +20,7 @@ package org.apache.shardingsphere.shardingjdbc.jdbc.adapter; import com.google.common.base.Preconditions; import lombok.AccessLevel; import lombok.Getter; +import org.apache.shardingsphere.core.constant.properties.ShardingPropertiesConstant; import org.apache.shardingsphere.core.route.SQLRouteResult; import org.apache.shardingsphere.core.rule.ShardingRule; import org.apache.shardingsphere.shardingjdbc.jdbc.adapter.executor.ForceExecuteCallback; @@ -42,6 +43,7 @@ import java.util.Map; * Adapter for {@code ResultSet}. * * @author zhangliang + * @author panjuan */ public abstract class AbstractResultSetAdapter extends AbstractUnsupportedOperationResultSet { @@ -70,10 +72,14 @@ public abstract class AbstractResultSetAdapter extends AbstractUnsupportedOperat @Override public final ResultSetMetaData getMetaData() throws SQLException { - return new ShardingResultSetMetaData(resultSets.get(0).getMetaData(), getShardingRule(), sqlRouteResult.getOptimizedStatement()); + return new ShardingResultSetMetaData(resultSets.get(0).getMetaData(), getShardingRule(), sqlRouteResult.getOptimizedStatement(), logicAndActualColumns); } private Map<String, String> createLogicAndActualColumns() { + return isQueryWithCipherColumn() ? createLogicAndCipherColumns() : createLogicAndPlainColumns(); + } + + private Map<String, String> createLogicAndCipherColumns() { Map<String, String> result = new LinkedHashMap<>(); for (String each : sqlRouteResult.getOptimizedStatement().getTables().getTableNames()) { result.putAll(getShardingRule().getEncryptRule().getLogicAndCipherColumns(each)); @@ -81,12 +87,26 @@ public abstract class AbstractResultSetAdapter extends AbstractUnsupportedOperat return result; } + private Map<String, String> createLogicAndPlainColumns() { + Map<String, String> result = new LinkedHashMap<>(); + for (String each : sqlRouteResult.getOptimizedStatement().getTables().getTableNames()) { + result.putAll(getShardingRule().getEncryptRule().getLogicAndPlainColumns(each)); + } + return result; + } + private ShardingRule getShardingRule() { return statement instanceof ShardingPreparedStatement ? ((ShardingPreparedStatement) statement).getConnection().getRuntimeContext().getRule() : ((ShardingStatement) statement).getConnection().getRuntimeContext().getRule(); } + private boolean isQueryWithCipherColumn() { + return statement instanceof ShardingPreparedStatement + ? ((ShardingPreparedStatement) statement).getConnection().getRuntimeContext().getProps().<Boolean>getValue(ShardingPropertiesConstant.QUERY_WITH_CIPHER_COLUMN) + : ((ShardingStatement) statement).getConnection().getRuntimeContext().getProps().<Boolean>getValue(ShardingPropertiesConstant.QUERY_WITH_CIPHER_COLUMN); + } + @Override public final int findColumn(final String columnLabel) throws SQLException { return resultSets.get(0).findColumn(getActualColumnLabel(columnLabel)); diff --git a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/EncryptResultSet.java b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/EncryptResultSet.java index 50345dbbb8b..a2c4f4c4fdb 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/EncryptResultSet.java +++ b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/EncryptResultSet.java @@ -17,11 +17,13 @@ package org.apache.shardingsphere.shardingjdbc.jdbc.core.resultset; +import org.apache.shardingsphere.core.constant.properties.ShardingPropertiesConstant; import org.apache.shardingsphere.core.execute.sql.execute.result.QueryResult; import org.apache.shardingsphere.core.execute.sql.execute.result.StreamQueryResult; import org.apache.shardingsphere.core.merge.dql.iterator.IteratorStreamMergedResult; import org.apache.shardingsphere.core.optimize.api.statement.OptimizedStatement; import org.apache.shardingsphere.core.rule.EncryptRule; +import org.apache.shardingsphere.shardingjdbc.jdbc.core.context.EncryptRuntimeContext; import org.apache.shardingsphere.shardingjdbc.jdbc.unsupported.AbstractUnsupportedOperationResultSet; import java.io.InputStream; @@ -63,17 +65,21 @@ public final class EncryptResultSet extends AbstractUnsupportedOperationResultSe private final Map<String, String> logicAndActualColumns; - public EncryptResultSet(final EncryptRule encryptRule, final OptimizedStatement optimizedStatement, final Statement encryptStatement, final ResultSet resultSet) { - this.encryptRule = encryptRule; + public EncryptResultSet(final EncryptRuntimeContext encryptRuntimeContext, final OptimizedStatement optimizedStatement, final Statement encryptStatement, final ResultSet resultSet) { + this.encryptRule = encryptRuntimeContext.getRule(); this.optimizedStatement = optimizedStatement; this.encryptStatement = encryptStatement; originalResultSet = resultSet; QueryResult queryResult = new StreamQueryResult(resultSet, encryptRule); this.resultSet = new IteratorStreamMergedResult(Collections.singletonList(queryResult)); - logicAndActualColumns = createLogicAndActualColumns(); + logicAndActualColumns = createLogicAndActualColumns(encryptRuntimeContext.getProps().<Boolean>getValue(ShardingPropertiesConstant.QUERY_WITH_CIPHER_COLUMN)); } - private Map<String, String> createLogicAndActualColumns() { + private Map<String, String> createLogicAndActualColumns(final boolean isQueryWithCipherColumn) { + return isQueryWithCipherColumn ? createLogicAndCipherColumns() : createLogicAndPlainColumns(); + } + + private Map<String, String> createLogicAndCipherColumns() { Map<String, String> result = new LinkedHashMap<>(); for (String each : optimizedStatement.getTables().getTableNames()) { result.putAll(encryptRule.getLogicAndCipherColumns(each)); @@ -81,6 +87,14 @@ public final class EncryptResultSet extends AbstractUnsupportedOperationResultSe return result; } + private Map<String, String> createLogicAndPlainColumns() { + Map<String, String> result = new LinkedHashMap<>(); + for (String each : optimizedStatement.getTables().getTableNames()) { + result.putAll(encryptRule.getLogicAndPlainColumns(each)); + } + return result; + } + @Override public boolean next() throws SQLException { return resultSet.next(); @@ -357,7 +371,7 @@ public final class EncryptResultSet extends AbstractUnsupportedOperationResultSe @Override public ResultSetMetaData getMetaData() throws SQLException { - return new EncryptResultSetMetaData(originalResultSet.getMetaData(), encryptRule, optimizedStatement); + return new EncryptResultSetMetaData(originalResultSet.getMetaData(), encryptRule, optimizedStatement, logicAndActualColumns); } @Override diff --git a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/EncryptResultSetMetaData.java b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/EncryptResultSetMetaData.java index 4313e77dd94..31fea0591a7 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/EncryptResultSetMetaData.java +++ b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/EncryptResultSetMetaData.java @@ -25,7 +25,6 @@ import org.apache.shardingsphere.shardingjdbc.jdbc.adapter.WrapperAdapter; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.Collection; -import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; @@ -45,19 +44,12 @@ public final class EncryptResultSetMetaData extends WrapperAdapter implements Re private final Map<String, String> logicAndActualColumns; - public EncryptResultSetMetaData(final ResultSetMetaData resultSetMetaData, final EncryptRule encryptRule, final OptimizedStatement optimizedStatement) { + public EncryptResultSetMetaData(final ResultSetMetaData resultSetMetaData, + final EncryptRule encryptRule, final OptimizedStatement optimizedStatement, final Map<String, String> logicAndActualColumns) { this.resultSetMetaData = resultSetMetaData; this.encryptRule = encryptRule; this.optimizedStatement = optimizedStatement; - logicAndActualColumns = createLogicAndActualColumns(); - } - - private Map<String, String> createLogicAndActualColumns() { - Map<String, String> result = new LinkedHashMap<>(); - for (String each : optimizedStatement.getTables().getTableNames()) { - result.putAll(encryptRule.getLogicAndCipherColumns(each)); - } - return result; + this.logicAndActualColumns = logicAndActualColumns; } @Override diff --git a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/ShardingResultSetMetaData.java b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/ShardingResultSetMetaData.java index 4f6d3cfb94b..fd7439e2b51 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/ShardingResultSetMetaData.java +++ b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/ShardingResultSetMetaData.java @@ -26,7 +26,6 @@ import org.apache.shardingsphere.shardingjdbc.jdbc.adapter.WrapperAdapter; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.Collection; -import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; @@ -47,19 +46,12 @@ public final class ShardingResultSetMetaData extends WrapperAdapter implements R private final Map<String, String> logicAndActualColumns; - public ShardingResultSetMetaData(final ResultSetMetaData resultSetMetaData, final ShardingRule shardingRule, final OptimizedStatement optimizedStatement) { + public ShardingResultSetMetaData(final ResultSetMetaData resultSetMetaData, + final ShardingRule shardingRule, final OptimizedStatement optimizedStatement, final Map<String, String> logicAndActualColumns) { this.resultSetMetaData = resultSetMetaData; this.shardingRule = shardingRule; this.optimizedStatement = optimizedStatement; - logicAndActualColumns = createLogicAndActualColumns(); - } - - private Map<String, String> createLogicAndActualColumns() { - Map<String, String> result = new LinkedHashMap<>(); - for (String each : optimizedStatement.getTables().getTableNames()) { - result.putAll(shardingRule.getEncryptRule().getLogicAndCipherColumns(each)); - } - return result; + this.logicAndActualColumns = logicAndActualColumns; } @Override 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 f8fe3a17fda..3fe351cd428 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 @@ -99,7 +99,7 @@ public final class EncryptPreparedStatement extends AbstractShardingPreparedStat SQLUnit sqlUnit = getSQLUnit(sql); preparedStatement = preparedStatementGenerator.createPreparedStatement(sqlUnit.getSql()); replaySetParameter(preparedStatement, sqlUnit.getParameters()); - this.resultSet = new EncryptResultSet(preparedStatementGenerator.connection.getRuntimeContext().getRule(), optimizedStatement, this, preparedStatement.executeQuery()); + this.resultSet = new EncryptResultSet(preparedStatementGenerator.connection.getRuntimeContext(), optimizedStatement, this, preparedStatement.executeQuery()); return resultSet; } finally { clearParameters(); @@ -139,7 +139,7 @@ public final class EncryptPreparedStatement extends AbstractShardingPreparedStat private EncryptResultSet createEncryptResultSet(final PreparedStatement preparedStatement) throws SQLException { return null == preparedStatement.getResultSet() - ? null : new EncryptResultSet(preparedStatementGenerator.connection.getRuntimeContext().getRule(), optimizedStatement, this, preparedStatement.getResultSet()); + ? null : new EncryptResultSet(preparedStatementGenerator.connection.getRuntimeContext(), optimizedStatement, this, preparedStatement.getResultSet()); } @Override diff --git a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/EncryptStatement.java b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/EncryptStatement.java index 13ae8d13994..61120e9d079 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/EncryptStatement.java +++ b/sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/EncryptStatement.java @@ -71,7 +71,7 @@ public final class EncryptStatement extends AbstractUnsupportedOperationStatemen @Override public ResultSet executeQuery(final String sql) throws SQLException { ResultSet resultSet = statement.executeQuery(getRewriteSQL(sql)); - this.resultSet = new EncryptResultSet(connection.getRuntimeContext().getRule(), optimizedStatement, this, resultSet); + this.resultSet = new EncryptResultSet(connection.getRuntimeContext(), optimizedStatement, this, resultSet); return this.resultSet; } @@ -148,7 +148,7 @@ public final class EncryptStatement extends AbstractUnsupportedOperationStatemen } private EncryptResultSet createEncryptResultSet(final Statement statement) throws SQLException { - return null == statement.getResultSet() ? null : new EncryptResultSet(connection.getRuntimeContext().getRule(), optimizedStatement, this, statement.getResultSet()); + return null == statement.getResultSet() ? null : new EncryptResultSet(connection.getRuntimeContext(), optimizedStatement, this, statement.getResultSet()); } @Override diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/common/base/AbstractEncryptJDBCDatabaseAndTableTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/common/base/AbstractEncryptJDBCDatabaseAndTableTest.java index beb2ccc4766..9eef55c4331 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/common/base/AbstractEncryptJDBCDatabaseAndTableTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/common/base/AbstractEncryptJDBCDatabaseAndTableTest.java @@ -61,7 +61,7 @@ public abstract class AbstractEncryptJDBCDatabaseAndTableTest extends AbstractSQ private static Properties createProperties() { Properties result = new Properties(); result.put(ShardingPropertiesConstant.SQL_SHOW.getKey(), true); - result.put(ShardingPropertiesConstant.QUERY_WITH_CIPHER_COLUMN, false); + result.put(ShardingPropertiesConstant.QUERY_WITH_CIPHER_COLUMN.getKey(), false); return result; } diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/ShardingResultSetTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/ShardingResultSetTest.java index df7d28df671..904a06ec236 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/ShardingResultSetTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/ShardingResultSetTest.java @@ -19,6 +19,7 @@ package org.apache.shardingsphere.shardingjdbc.jdbc.core.resultset; import com.google.common.base.Optional; import lombok.SneakyThrows; +import org.apache.shardingsphere.core.constant.properties.ShardingProperties; import org.apache.shardingsphere.core.merge.MergedResult; import org.apache.shardingsphere.core.optimize.api.segment.Tables; import org.apache.shardingsphere.core.optimize.api.statement.OptimizedStatement; @@ -49,6 +50,7 @@ import java.sql.Timestamp; import java.util.Calendar; import java.util.Collections; import java.util.List; +import java.util.Properties; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; @@ -101,6 +103,7 @@ public final class ShardingResultSetTest { when(encryptRule.getShardingEncryptor(anyString(), anyString())).thenReturn(Optional.<ShardingEncryptor>absent()); when(shardingRule.getEncryptRule()).thenReturn(encryptRule); when(runtimeContext.getRule()).thenReturn(shardingRule); + when(runtimeContext.getProps()).thenReturn(new ShardingProperties(new Properties())); when(shardingConnection.getRuntimeContext()).thenReturn(runtimeContext); ShardingStatement statement = mock(ShardingStatement.class); when(statement.getConnection()).thenReturn(shardingConnection); diff --git a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/EncryptStatementTest.java b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/EncryptStatementTest.java index 776398d4b50..b8f020851b0 100644 --- a/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/EncryptStatementTest.java +++ b/sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/EncryptStatementTest.java @@ -50,6 +50,8 @@ public final class EncryptStatementTest extends AbstractEncryptJDBCDatabaseAndTa private static final String SELECT_SQL_WITH_PLAIN = "select id, pwd from t_encrypt where pwd = 'plainValue'"; + private static final String SELECT_SQL_WITH_CIPHER = "select id, pwd from t_encrypt where pwd = 'plainValue'"; + private static final String SELECT_SQL_TO_ASSERT = "select id, cipher_pwd, plain_pwd from t_encrypt"; @Test @@ -122,17 +124,32 @@ public final class EncryptStatementTest extends AbstractEncryptJDBCDatabaseAndTa @Test public void assertSelectWithMetaData() throws SQLException { - try (Statement statement = getEncryptConnection().createStatement()) { + try (Statement statement = getEncryptConnectionWithProps().createStatement()) { ResultSetMetaData metaData = statement.executeQuery(SELECT_SQL_WITH_STAR).getMetaData(); assertThat(metaData.getColumnCount(), is(3)); for (int i = 0; i < metaData.getColumnCount(); i++) { assertThat(metaData.getColumnLabel(1), is("id")); - assertThat(metaData.getColumnLabel(2), is("pwd")); - assertThat(metaData.getColumnLabel(3), is("plain_pwd")); + assertThat(metaData.getColumnLabel(2), is("cipher_pwd")); + assertThat(metaData.getColumnLabel(3), is("pwd")); } } } + @Test + public void assertSelectWithCipherColumn() throws SQLException { + try (Statement statement = getEncryptConnection().createStatement()) { + ResultSet resultSet = statement.executeQuery(SELECT_SQL_WITH_CIPHER); + int count = 1; + List<Object> ids = Arrays.asList((Object) 1, 5); + while (resultSet.next()) { + assertThat(resultSet.getObject("id"), is(ids.get(count - 1))); + assertThat(resultSet.getObject("pwd"), is((Object) "decryptValue")); + count += 1; + } + assertThat(count - 1, is(ids.size())); + } + } + @Test public void assertSelectWithPlainColumn() throws SQLException { try (Statement statement = getEncryptConnectionWithProps().createStatement()) { @@ -141,7 +158,7 @@ public final class EncryptStatementTest extends AbstractEncryptJDBCDatabaseAndTa List<Object> ids = Arrays.asList((Object) 1, 5); while (resultSet.next()) { assertThat(resultSet.getObject("id"), is(ids.get(count - 1))); - assertThat(resultSet.getObject("pwd"), is((Object) "decryptValue")); + assertThat(resultSet.getObject("pwd"), is((Object) "plainValue")); count += 1; } assertThat(count - 1, is(ids.size()));
['sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/EncryptTokenGenerateEngine.java', 'sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/ShardingResultSetTest.java', 'sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/EncryptResultSet.java', 'sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/EncryptRule.java', 'sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/pojo/SelectCipherItemToken.java', 'sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/EncryptStatementTest.java', 'sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/EncryptStatement.java', 'sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/EncryptResultSetMetaData.java', 'sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/strategy/encrypt/EncryptTable.java', 'sharding-jdbc/sharding-jdbc-core/src/test/java/org/apache/shardingsphere/shardingjdbc/common/base/AbstractEncryptJDBCDatabaseAndTableTest.java', 'sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/resultset/ShardingResultSetMetaData.java', 'sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/adapter/AbstractResultSetAdapter.java', 'sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/rewriter/ShardingSQLRewriteEngineTest.java', 'sharding-jdbc/sharding-jdbc-core/src/main/java/org/apache/shardingsphere/shardingjdbc/jdbc/core/statement/EncryptPreparedStatement.java', 'sharding-core/sharding-core-rewrite/src/main/java/org/apache/shardingsphere/core/rewrite/token/generator/SelectCipherItemTokenGenerator.java']
{'.java': 15}
15
15
0
0
15
3,060,147
613,241
78,070
1,063
7,616
1,390
117
11
1,171
159
259
28
2
0
1970-01-01T00:26:05
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,471
apache/shardingsphere/2771/2768
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2768
https://github.com/apache/shardingsphere/pull/2771
https://github.com/apache/shardingsphere/pull/2771
1
fixes
Get ShardingException when use `NSERT INTO t_plain_encrypt(col3, col4) VALUES (?, ?), (3, 4)`
## 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/apache/incubator-shardingsphere/issues). - Read documentation: [ShardingSphere Doc](https://shardingsphere.apache.org/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.rc2 ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-JDBC ### Expected behavior ### Actual behavior throw new ShardingException("Index Out Of Bounds For InsertOptimizeResultUnit.") ### 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).
09e132e7a98d6d41c811e7c9dad41a1e3f8ae6e2
950008dfcc101d3237724cd83030f3f408b5f546
https://github.com/apache/shardingsphere/compare/09e132e7a98d6d41c811e7c9dad41a1e3f8ae6e2...950008dfcc101d3237724cd83030f3f408b5f546
diff --git a/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/encrypt/engine/dml/EncryptInsertOptimizeEngine.java b/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/encrypt/engine/dml/EncryptInsertOptimizeEngine.java index 163e766057a..b53b37d6e09 100644 --- a/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/encrypt/engine/dml/EncryptInsertOptimizeEngine.java +++ b/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/encrypt/engine/dml/EncryptInsertOptimizeEngine.java @@ -27,6 +27,7 @@ import org.apache.shardingsphere.core.optimize.sharding.segment.insert.value.Ins import org.apache.shardingsphere.core.parse.sql.statement.dml.InsertStatement; import org.apache.shardingsphere.core.rule.EncryptRule; +import java.util.Arrays; import java.util.Collection; import java.util.List; @@ -46,12 +47,13 @@ public final class EncryptInsertOptimizeEngine implements EncryptOptimizeEngine< int derivedColumnsCount = encryptRule.getAssistedQueryAndPlainColumnCount(sqlStatement.getTable().getTableName()); int parametersCount = 0; for (InsertValue each : result.getValues()) { - InsertOptimizeResultUnit unit = result.addUnit(each.getValues(derivedColumnsCount), each.getParameters(parameters, parametersCount, derivedColumnsCount), each.getParametersCount()); + Object[] currentParameters = each.getParameters(parameters, parametersCount, derivedColumnsCount); + InsertOptimizeResultUnit unit = result.addUnit(each.getValues(derivedColumnsCount), currentParameters, each.getParametersCount()); if (encryptRule.isHasQueryAssistedColumn(sqlStatement.getTable().getTableName())) { - fillAssistedQueryUnit(encryptRule, parameters, sqlStatement.getTable().getTableName(), result.getInsertColumns().getRegularColumnNames(), unit); + fillAssistedQueryUnit(encryptRule, Arrays.asList(currentParameters), sqlStatement.getTable().getTableName(), result.getInsertColumns().getRegularColumnNames(), unit); } if (encryptRule.isHasPlainColumn(sqlStatement.getTable().getTableName())) { - fillPlainUnit(encryptRule, parameters, sqlStatement.getTable().getTableName(), result.getInsertColumns().getRegularColumnNames(), unit); + fillPlainUnit(encryptRule, Arrays.asList(currentParameters), sqlStatement.getTable().getTableName(), result.getInsertColumns().getRegularColumnNames(), unit); } parametersCount += each.getParametersCount(); } diff --git a/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/sharding/engnie/dml/ShardingInsertOptimizeEngine.java b/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/sharding/engnie/dml/ShardingInsertOptimizeEngine.java index 6f891b349f9..4b2fe326558 100644 --- a/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/sharding/engnie/dml/ShardingInsertOptimizeEngine.java +++ b/sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/sharding/engnie/dml/ShardingInsertOptimizeEngine.java @@ -34,6 +34,7 @@ import org.apache.shardingsphere.core.parse.sql.segment.dml.column.OnDuplicateKe import org.apache.shardingsphere.core.parse.sql.statement.dml.InsertStatement; import org.apache.shardingsphere.core.rule.ShardingRule; +import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; @@ -66,16 +67,17 @@ public final class ShardingInsertOptimizeEngine implements ShardingOptimizeEngin int derivedColumnsCount = getDerivedColumnsCount(shardingRule, tableName, isGeneratedValue); int parametersCount = 0; for (InsertValue each : result.getValues()) { - InsertOptimizeResultUnit unit = result.createUnit(each.getValues(derivedColumnsCount), each.getParameters(parameters, parametersCount, derivedColumnsCount), each.getParametersCount()); + Object[] currentParameters = each.getParameters(parameters, parametersCount, derivedColumnsCount); + InsertOptimizeResultUnit unit = result.createUnit(each.getValues(derivedColumnsCount), currentParameters, each.getParametersCount()); result.addUnit(unit); if (isGeneratedValue) { - unit.addInsertValue(generatedValues.next(), parameters); + unit.addInsertValue(generatedValues.next(), Arrays.asList(currentParameters)); } if (shardingRule.getEncryptRule().isHasQueryAssistedColumn(tableName)) { - fillAssistedQueryUnit(shardingRule, tableName, insertColumns.getRegularColumnNames(), unit, parameters); + fillAssistedQueryUnit(shardingRule, tableName, insertColumns.getRegularColumnNames(), unit, Arrays.asList(currentParameters)); } if (shardingRule.getEncryptRule().isHasPlainColumn(tableName)) { - fillPlainUnit(shardingRule, tableName, insertColumns.getRegularColumnNames(), unit, parameters); + fillPlainUnit(shardingRule, tableName, insertColumns.getRegularColumnNames(), unit, Arrays.asList(currentParameters)); } parametersCount += each.getParametersCount(); } diff --git a/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/rewriter/EncryptSQLRewriteEngineTest.java b/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/rewriter/EncryptSQLRewriteEngineTest.java index c6ae4d3b898..48f78c6c7a8 100644 --- a/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/rewriter/EncryptSQLRewriteEngineTest.java +++ b/sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/rewriter/EncryptSQLRewriteEngineTest.java @@ -238,6 +238,18 @@ public final class EncryptSQLRewriteEngineTest { assertThat(actual.getParameters().get(1), is((Object) "encryptValue")); } + @Test + public void assertInsertWithValuesWithPlaceholderWithPlainEncrypt() { + String sql = "INSERT INTO t_plain_encrypt(col3, col4) VALUES (?, ?), (3, 4)"; + SQLUnit actual = getSQLUnit(sql, parametersOfEqual, true); + assertThat(actual.getSql(), is("INSERT INTO t_plain_encrypt(col1, col2, plain1, plain2) VALUES (?, ?, ?, ?), ('encryptValue', 'encryptValue', 3, 4)")); + assertThat(actual.getParameters().size(), is(4)); + assertThat(actual.getParameters().get(0), is((Object) "encryptValue")); + assertThat(actual.getParameters().get(1), is((Object) "encryptValue")); + assertThat(actual.getParameters().get(2), is((Object) 1)); + assertThat(actual.getParameters().get(3), is((Object) 2)); + } + @Test public void assertInsertWithValuesWithoutPlaceholderWithQueryEncrypt() { String sql = "INSERT INTO t_query_encrypt(col1, col2) VALUES (1, 2), (3, 4)";
['sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/encrypt/engine/dml/EncryptInsertOptimizeEngine.java', 'sharding-core/sharding-core-rewrite/src/test/java/org/apache/shardingsphere/core/rewrite/rewriter/EncryptSQLRewriteEngineTest.java', 'sharding-core/sharding-core-optimize/src/main/java/org/apache/shardingsphere/core/optimize/sharding/engnie/dml/ShardingInsertOptimizeEngine.java']
{'.java': 3}
3
3
0
0
3
3,032,602
607,785
77,361
1,059
2,320
419
18
2
1,094
141
241
28
2
0
1970-01-01T00:26:04
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,472
apache/shardingsphere/2710/2613
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2613
https://github.com/apache/shardingsphere/pull/2710
https://github.com/apache/shardingsphere/pull/2710
1
fix
recieve ClassCastException while testing ComplexKeysShardingAlgorithm
## 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/apache/incubator-shardingsphere-example/issues). - Read documentation: [ShardingSphere Doc](https://shardingsphere.apache.org/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? - sharding-jdbc-core:4.0.0-RC1 ### Which project did you use? Sharding-JDBC or Sharding-Proxy? - Sharding-JDBC ### Expected behavior - return the right type of RouteValue ### Actual behavior - java.lang.ClassCastException ### Reason analyze (If you can) - just BetweenRouteValue cast to ListRouteValue error. - i think it`s no need to cast to ListRouteValue, just let us to deal with it - at org.apache.shardingsphere.core.strategy.route.complex.ComplexShardingStrategy ```java line 61: columnShardingValues.put(each.getColumnName(), ((ListRouteValue) each).getValues()); ``` ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc. - i am trying to test the ComplexKeysShardingAlgorithm, but before it come into my code, it occur a java.lang.ClassCastException, - the table configuration ```java public static TableRuleConfiguration defaultCreateTimeTableRuleConfiguration(String datasourceName, String tableName) { TableRuleConfiguration tableRule = new TableRuleConfiguration(tableName, String.format("%s.%s_$->{19..19}0$->{1..6}", datasourceName, tableName)); tableRule.setTableShardingStrategyConfig( new ComplexShardingStrategyConfiguration("id,create_time", new BaseComplexKeysShardingAlgorithm())); return tableRule; } ``` - my algorithm -- yes, it do nothing but log ```java @Slf4j(topic = "sharding") public class BaseComplexKeysShardingAlgorithm implements ComplexKeysShardingAlgorithm { @Override public Collection<String> doSharding(Collection availableTargetNames, ComplexKeysShardingValue shardingValue) { log.info("availableTargetNames: {}\\nshardingValue: {}", availableTargetNames, shardingValue); return availableTargetNames; } } ``` - sql ```sql select * from t_order order0_ where order0_.create_time between ? and ? ``` ```sql create table sharding.t_order ( create_time timestamp default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP, id varchar(255) not null primary key, update_time datetime null, name varchar(255) null, test_id int null ) ``` - JDK ``` java 11.0.3 2019-04-16 LTS ``` - framework ```xml spring-boot-starter-data-jpa:2.1.4RELEASE <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version> ``` - the full trace is here ```java Caused by: java.lang.ClassCastException: class org.apache.shardingsphere.core.strategy.route.value.BetweenRouteValue cannot be cast to class org.apache.shardingsphere.core.strategy.route.value.ListRouteValue (org.apache.shardingsphere.core.strategy.route.value.BetweenRouteValue and org.apache.shardingsphere.core.strategy.route.value.ListRouteValue are in unnamed module of loader 'app') at org.apache.shardingsphere.core.strategy.route.complex.ComplexShardingStrategy.doSharding(ComplexShardingStrategy.java:61) ~[sharding-core-common-4.0.0-RC1.jar:4.0.0-RC1] at org.apache.shardingsphere.core.route.type.standard.StandardRoutingEngine.routeTables(StandardRoutingEngine.java:199) ~[sharding-core-route-4.0.0-RC1.jar:4.0.0-RC1] at org.apache.shardingsphere.core.route.type.standard.StandardRoutingEngine.route(StandardRoutingEngine.java:181) ~[sharding-core-route-4.0.0-RC1.jar:4.0.0-RC1] at org.apache.shardingsphere.core.route.type.standard.StandardRoutingEngine.routeByShardingConditionsWithCondition(StandardRoutingEngine.java:108) ~[sharding-core-route-4.0.0-RC1.jar:4.0.0-RC1] at org.apache.shardingsphere.core.route.type.standard.StandardRoutingEngine.routeByShardingConditions(StandardRoutingEngine.java:102) ~[sharding-core-route-4.0.0-RC1.jar:4.0.0-RC1] at org.apache.shardingsphere.core.route.type.standard.StandardRoutingEngine.getDataNodes(StandardRoutingEngine.java:87) ~[sharding-core-route-4.0.0-RC1.jar:4.0.0-RC1] at org.apache.shardingsphere.core.route.type.standard.StandardRoutingEngine.route(StandardRoutingEngine.java:69) ~[sharding-core-route-4.0.0-RC1.jar:4.0.0-RC1] at org.apache.shardingsphere.core.route.router.sharding.ParsingSQLRouter.route(ParsingSQLRouter.java:106) ~[sharding-core-route-4.0.0-RC1.jar:4.0.0-RC1] at org.apache.shardingsphere.core.route.PreparedStatementRoutingEngine.route(PreparedStatementRoutingEngine.java:66) ~[sharding-core-route-4.0.0-RC1.jar:4.0.0-RC1] at org.apache.shardingsphere.core.PreparedQueryShardingEngine.route(PreparedQueryShardingEngine.java:60) ~[sharding-core-entry-4.0.0-RC1.jar:4.0.0-RC1] at org.apache.shardingsphere.core.BaseShardingEngine.shard(BaseShardingEngine.java:64) ~[sharding-core-entry-4.0.0-RC1.jar:4.0.0-RC1] at org.apache.shardingsphere.shardingjdbc.jdbc.core.statement.ShardingPreparedStatement.shard(ShardingPreparedStatement.java:224) ~[sharding-jdbc-core-4.0.0-RC1.jar:4.0.0-RC1] at org.apache.shardingsphere.shardingjdbc.jdbc.core.statement.ShardingPreparedStatement.executeQuery(ShardingPreparedStatement.java:109) ~[sharding-jdbc-core-4.0.0-RC1.jar:4.0.0-RC1] at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:60) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final] at org.hibernate.loader.Loader.getResultSet(Loader.java:2167) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final] at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1930) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final] at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1892) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final] at org.hibernate.loader.Loader.doQuery(Loader.java:937) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final] at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:340) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final] at org.hibernate.loader.Loader.doList(Loader.java:2689) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final] at org.hibernate.loader.Loader.doList(Loader.java:2672) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final] at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2506) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final] at org.hibernate.loader.Loader.list(Loader.java:2501) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final] at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:504) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final] at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:395) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final] at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:220) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final] at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1507) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final] at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1537) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final] at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1505) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final] at org.hibernate.query.Query.getResultList(Query.java:132) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final] at com.querydsl.jpa.impl.AbstractJPAQuery.getResultList(AbstractJPAQuery.java:160) ~[querydsl-jpa-4.2.1.jar:na] at com.querydsl.jpa.impl.AbstractJPAQuery.fetch(AbstractJPAQuery.java:202) ~[querydsl-jpa-4.2.1.jar:na] at com.f5futurestore.cloud.demo.service.OrderServiceImpl.test(OrderServiceImpl.java:103) ~[classes/:na] at com.f5futurestore.cloud.demo.service.OrderServiceImpl$$FastClassBySpringCGLIB$$d3d4b7a6.invoke(<generated>) ~[classes/:na] at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.1.6.RELEASE.jar:5.1.6.RELEASE] at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:749) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE] at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294) ~[spring-tx-5.1.6.RELEASE.jar:5.1.6.RELEASE] at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.1.6.RELEASE.jar:5.1.6.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE] at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE] at com.f5futurestore.cloud.demo.service.OrderServiceImpl$$EnhancerBySpringCGLIB$$4987f585.test(<generated>) ~[classes/:na] at com.f5futurestore.cloud.demo.controller.DemoController.test(DemoController.java:39) ~[classes/:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na] at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:363) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE] at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:307) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE] at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:136) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE] ``` ### Example codes for reproduce this issue (such as a github link). i will post it to github later
3a8bab2453ca12e1783e19bf57ade7a1a8dd4725
a25b6fbfb1419cd927bb71eacf6866f0abbdb644
https://github.com/apache/shardingsphere/compare/3a8bab2453ca12e1783e19bf57ade7a1a8dd4725...a25b6fbfb1419cd927bb71eacf6866f0abbdb644
diff --git a/sharding-core/sharding-core-api/src/main/java/org/apache/shardingsphere/api/sharding/complex/ComplexKeysShardingValue.java b/sharding-core/sharding-core-api/src/main/java/org/apache/shardingsphere/api/sharding/complex/ComplexKeysShardingValue.java index faaa06e0076..3a4dade7640 100644 --- a/sharding-core/sharding-core-api/src/main/java/org/apache/shardingsphere/api/sharding/complex/ComplexKeysShardingValue.java +++ b/sharding-core/sharding-core-api/src/main/java/org/apache/shardingsphere/api/sharding/complex/ComplexKeysShardingValue.java @@ -17,6 +17,7 @@ package org.apache.shardingsphere.api.sharding.complex; +import com.google.common.collect.Range; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.ToString; @@ -38,4 +39,6 @@ public final class ComplexKeysShardingValue<T extends Comparable<?>> implements private final String logicTableName; private final Map<String, Collection<T>> columnNameAndShardingValuesMap; + + private final Map<String, Range<T>> columnNameAndRangeValuesMap; } diff --git a/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/strategy/route/complex/ComplexShardingStrategy.java b/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/strategy/route/complex/ComplexShardingStrategy.java index 618e080d54c..723b147c46e 100644 --- a/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/strategy/route/complex/ComplexShardingStrategy.java +++ b/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/strategy/route/complex/ComplexShardingStrategy.java @@ -19,12 +19,15 @@ package org.apache.shardingsphere.core.strategy.route.complex; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; +import com.google.common.collect.Range; + import lombok.Getter; import org.apache.shardingsphere.api.config.sharding.strategy.ComplexShardingStrategyConfiguration; import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm; import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue; import org.apache.shardingsphere.core.strategy.route.ShardingStrategy; import org.apache.shardingsphere.core.strategy.route.value.ListRouteValue; +import org.apache.shardingsphere.core.strategy.route.value.RangeRouteValue; import org.apache.shardingsphere.core.strategy.route.value.RouteValue; import java.util.Collection; @@ -56,12 +59,17 @@ public final class ComplexShardingStrategy implements ShardingStrategy { @Override public Collection<String> doSharding(final Collection<String> availableTargetNames, final Collection<RouteValue> shardingValues) { Map<String, Collection<Comparable<?>>> columnShardingValues = new HashMap<>(shardingValues.size(), 1); + Map<String, Range<Comparable<?>>> columnRangeValues = new HashMap<>(shardingValues.size(), 1); String logicTableName = ""; for (RouteValue each : shardingValues) { - columnShardingValues.put(each.getColumnName(), ((ListRouteValue) each).getValues()); + if (each instanceof ListRouteValue) { + columnShardingValues.put(each.getColumnName(), ((ListRouteValue) each).getValues()); + } else if (each instanceof RangeRouteValue) { + columnRangeValues.put(each.getColumnName(), ((RangeRouteValue) each).getValueRange()); + } logicTableName = each.getTableName(); } - Collection<String> shardingResult = shardingAlgorithm.doSharding(availableTargetNames, new ComplexKeysShardingValue(logicTableName, columnShardingValues)); + Collection<String> shardingResult = shardingAlgorithm.doSharding(availableTargetNames, new ComplexKeysShardingValue(logicTableName, columnShardingValues, columnRangeValues)); Collection<String> result = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); result.addAll(shardingResult); return result; diff --git a/sharding-core/sharding-core-common/src/test/java/org/apache/shardingsphere/core/strategy/route/ShardingStrategyTest.java b/sharding-core/sharding-core-common/src/test/java/org/apache/shardingsphere/core/strategy/route/ShardingStrategyTest.java index 0ac1045f183..2ccdb4eb30a 100644 --- a/sharding-core/sharding-core-common/src/test/java/org/apache/shardingsphere/core/strategy/route/ShardingStrategyTest.java +++ b/sharding-core/sharding-core-common/src/test/java/org/apache/shardingsphere/core/strategy/route/ShardingStrategyTest.java @@ -17,6 +17,7 @@ package org.apache.shardingsphere.core.strategy.route; +import com.google.common.collect.Lists; import com.google.common.collect.Range; import com.google.common.collect.Sets; import org.apache.shardingsphere.api.config.sharding.strategy.ComplexShardingStrategyConfiguration; @@ -34,6 +35,7 @@ import org.junit.Test; import java.util.Collection; import java.util.Collections; +import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; @@ -58,8 +60,11 @@ public final class ShardingStrategyTest { @Test public void assertDoShardingForMultipleKeys() { - ComplexShardingStrategy strategy = new ComplexShardingStrategy(new ComplexShardingStrategyConfiguration("column", new ComplexKeysShardingAlgorithmFixture())); - assertThat(strategy.doSharding(targets, Collections.<RouteValue>singletonList(new ListRouteValue<>("column", "logicTable", Collections.singletonList(1)))), - is((Collection<String>) Sets.newHashSet("1", "2", "3"))); + ComplexShardingStrategy strategy = new ComplexShardingStrategy(new ComplexShardingStrategyConfiguration("column1, column2", new ComplexKeysShardingAlgorithmFixture())); + List<RouteValue> routeValues = Lists.<RouteValue>newArrayList( + new ListRouteValue<>("column1", "logicTable", Collections.singletonList(1)), + new RangeRouteValue<>("column2", "logicTable", Range.open(1, 3)) + ); + assertThat(strategy.doSharding(targets, routeValues), is((Collection<String>) Sets.newHashSet("1", "2", "3"))); } }
['sharding-core/sharding-core-api/src/main/java/org/apache/shardingsphere/api/sharding/complex/ComplexKeysShardingValue.java', 'sharding-core/sharding-core-common/src/test/java/org/apache/shardingsphere/core/strategy/route/ShardingStrategyTest.java', 'sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/strategy/route/complex/ComplexShardingStrategy.java']
{'.java': 3}
3
3
0
0
3
3,006,306
603,181
76,729
1,052
1,117
224
15
2
10,734
512
2,938
163
2
8
1970-01-01T00:26:03
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,473
apache/shardingsphere/2708/2687
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2687
https://github.com/apache/shardingsphere/pull/2708
https://github.com/apache/shardingsphere/pull/2708
1
fixes
"select code from t group by code" got duplicate records
## Bug Report ### Which version of ShardingSphere did you use? 3.0.0 ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-Proxy ### Expected behavior I have a logic table 't' with 2 shards, actual table are 't_0' and 't_1'. When I excute "select code from t group by code" on Sharding-Proxy-3.0.0, it should returns code without duplicate. ### Actual behavior but in fact, it returns duplicate records. ### Reason analyze (If you can) My backend db is mysql5.7. COLLATE is 'utf8mb4_unicode_ci'. The group-by merger may add 'order by code' clause for using stream merge, and the result set is sorted by case insensitive. But the merger compares value with case sensitive(because use java compareTo method). ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc. #### sharding rule: ``` tables: t: actualDataNodes: ds_${0}.t_${0..1} tableStrategy: inline: shardingColumn: id algorithmExpression: t_${id % 2} ``` #### prepare sql script: ``` CREATE TABLE `t_0` ( `id` INT NOT NULL, `code` VARCHAR(40) NOT NULL, PRIMARY KEY (`id`) ) COLLATE='utf8mb4_unicode_ci' ; CREATE TABLE `t_1` ( `id` INT NOT NULL, `code` VARCHAR(40) NOT NULL, PRIMARY KEY (`id`) ) COLLATE='utf8mb4_unicode_ci' ; insert into t values (11, '11035801128253'); insert into t values (13, '110358011282f5'); insert into t values (15, '110358011282G1'); insert into t values (17, '110358011282H5'); insert into t values (19, '110358011282T4'); insert into t values (21, '110358011282U5'); insert into t values (23, '110358011282z1'); insert into t values (22, '110358011282D4'); insert into t values (24, '110358011282E9'); insert into t values (26, '110358011282h8'); insert into t values (28, '110358011282I0'); insert into t values (30, '110358011282l1'); insert into t values (32, '110358011282O7'); insert into t values (34, '110358011282P0'); insert into t values (36, '110358011282T4'); insert into t values (38, '110358011282w6'); mysql> select 't_0' as tab, code from t_0; +------+----------------+ | tab | code | +------+----------------+ | t_0 | 110358011282D4 | | t_0 | 110358011282E9 | | t_0 | 110358011282h8 | | t_0 | 110358011282I0 | | t_0 | 110358011282l1 | | t_0 | 110358011282O7 | | t_0 | 110358011282P0 | | t_0 | 110358011282T4 | | t_0 | 110358011282w6 | +------+----------------+ 9 rows in set (0.00 sec) mysql> select 't_1' as tab, code from t_1; +------+----------------+ | tab | code | +------+----------------+ | t_1 | 11035801128253 | | t_1 | 110358011282f5 | | t_1 | 110358011282G1 | | t_1 | 110358011282H5 | | t_1 | 110358011282T4 | | t_1 | 110358011282U5 | | t_1 | 110358011282z1 | +------+----------------+ 7 rows in set (0.00 sec) ``` #### execute result ( duplicate code is 110358011282T4 .) ``` mysql> select code from t group by code; +----------------+ | code | +----------------+ | 11035801128253 | | 110358011282D4 | | 110358011282E9 | | 110358011282f5 | | 110358011282G1 | | 110358011282H5 | | 110358011282T4 | | 110358011282U5 | | 110358011282h8 | | 110358011282I0 | | 110358011282l1 | | 110358011282O7 | | 110358011282P0 | | 110358011282T4 | | 110358011282w6 | | 110358011282z1 | +----------------+ 16 rows in set (0.01 sec) ``` I tried following SQL then I got right result. ``` mysql> select max(code) from t group by upper(code); +----------------+ | max(code) | +----------------+ | 11035801128253 | | 110358011282D4 | | 110358011282E9 | | 110358011282f5 | | 110358011282G1 | | 110358011282H5 | | 110358011282h8 | | 110358011282I0 | | 110358011282l1 | | 110358011282O7 | | 110358011282P0 | | 110358011282T4 | | 110358011282U5 | | 110358011282w6 | | 110358011282z1 | +----------------+ 15 rows in set (0.01 sec) ``` ### Example codes for reproduce this issue (such as a github link).
e93dc9cc810e83990054840f790a3529b703f272
3ce7f45572e8584cf18869bb9b458789446371bf
https://github.com/apache/shardingsphere/compare/e93dc9cc810e83990054840f790a3529b703f272...3ce7f45572e8584cf18869bb9b458789446371bf
diff --git a/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/AggregationDistinctQueryResult.java b/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/AggregationDistinctQueryResult.java index 21aa167a257..c41132d2dc8 100644 --- a/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/AggregationDistinctQueryResult.java +++ b/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/AggregationDistinctQueryResult.java @@ -45,8 +45,9 @@ public final class AggregationDistinctQueryResult extends DistinctQueryResult { private final AggregationDistinctQueryMetaData metaData; - private AggregationDistinctQueryResult(final Multimap<String, Integer> columnLabelAndIndexMap, final Iterator<QueryRow> resultData, final AggregationDistinctQueryMetaData distinctQueryMetaData) { - super(columnLabelAndIndexMap, resultData); + private AggregationDistinctQueryResult(final Multimap<String, Integer> columnLabelAndIndexMap, final List<Boolean> columnCaseSensitive, final Iterator<QueryRow> resultData, + final AggregationDistinctQueryMetaData distinctQueryMetaData) { + super(columnLabelAndIndexMap, columnCaseSensitive, resultData); metaData = distinctQueryMetaData; } @@ -75,7 +76,7 @@ public final class AggregationDistinctQueryResult extends DistinctQueryResult { public DistinctQueryResult apply(final QueryRow input) { Set<QueryRow> resultData = new LinkedHashSet<>(); resultData.add(input); - return new AggregationDistinctQueryResult(getColumnLabelAndIndexMap(), resultData.iterator(), metaData); + return new AggregationDistinctQueryResult(getColumnLabelAndIndexMap(), getColumnCaseSensitive(), resultData.iterator(), metaData); } })); } diff --git a/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/DistinctQueryResult.java b/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/DistinctQueryResult.java index 340995edd4e..4ea938bbfad 100644 --- a/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/DistinctQueryResult.java +++ b/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/DistinctQueryResult.java @@ -46,6 +46,7 @@ import java.util.Set; * Distinct query result. * * @author panjuan + * @author yangyi */ @RequiredArgsConstructor @Getter(AccessLevel.PROTECTED) @@ -53,6 +54,8 @@ public class DistinctQueryResult implements QueryResult { private final Multimap<String, Integer> columnLabelAndIndexMap; + private final List<Boolean> columnCaseSensitive; + private final Iterator<QueryRow> resultData; private QueryRow currentRow; @@ -60,6 +63,7 @@ public class DistinctQueryResult implements QueryResult { @SneakyThrows public DistinctQueryResult(final Collection<QueryResult> queryResults, final List<String> distinctColumnLabels) { this.columnLabelAndIndexMap = getColumnLabelAndIndexMap(queryResults.iterator().next()); + this.columnCaseSensitive = getColumnCaseSensitive(queryResults.iterator().next()); resultData = getResultData(queryResults, distinctColumnLabels); } @@ -72,6 +76,15 @@ public class DistinctQueryResult implements QueryResult { return result; } + @SneakyThrows + private List<Boolean> getColumnCaseSensitive(final QueryResult queryResult) { + List<Boolean> result = Lists.newArrayList(false); + for (int columnIndex = 1; columnIndex <= queryResult.getColumnCount(); columnIndex++) { + result.add(queryResult.isCaseSensitive(columnIndex)); + } + return result; + } + @SneakyThrows private Iterator<QueryRow> getResultData(final Collection<QueryResult> queryResults, final List<String> distinctColumnLabels) { Set<QueryRow> result = new LinkedHashSet<>(); @@ -111,7 +124,7 @@ public class DistinctQueryResult implements QueryResult { public DistinctQueryResult apply(final QueryRow row) { Set<QueryRow> resultData = new LinkedHashSet<>(); resultData.add(row); - return new DistinctQueryResult(columnLabelAndIndexMap, resultData.iterator()); + return new DistinctQueryResult(columnLabelAndIndexMap, columnCaseSensitive, resultData.iterator()); } })); } @@ -171,6 +184,11 @@ public class DistinctQueryResult implements QueryResult { return null == currentRow; } + @Override + public boolean isCaseSensitive(final int columnIndex) { + return columnCaseSensitive.get(columnIndex); + } + @Override public int getColumnCount() { return columnLabelAndIndexMap.size(); diff --git a/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/MemoryQueryResult.java b/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/MemoryQueryResult.java index 78ad276831d..5ba4b6d9eee 100644 --- a/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/MemoryQueryResult.java +++ b/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/MemoryQueryResult.java @@ -41,6 +41,7 @@ import java.util.List; * * @author zhangliang * @author panjuan + * @author yangyi */ public final class MemoryQueryResult implements QueryResult { @@ -136,6 +137,11 @@ public final class MemoryQueryResult implements QueryResult { return null == currentRow; } + @Override + public boolean isCaseSensitive(final int columnIndex) { + return metaData.isCaseSensitive(columnIndex); + } + @Override public int getColumnCount() { return metaData.getColumnCount(); diff --git a/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResult.java b/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResult.java index 2e1b277b39e..11248cad0fa 100644 --- a/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResult.java +++ b/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResult.java @@ -25,6 +25,7 @@ import java.util.Calendar; * Query result form database. * * @author zhangliang + * @author yangyi */ public interface QueryResult { @@ -122,4 +123,13 @@ public interface QueryResult { * @throws SQLException SQL Exception */ boolean wasNull() throws SQLException; + + /** + * Whether the column value is case sensitive. + * + * @param columnIndex column index + * @return true if column is case sensitive, otherwise false + * @throws SQLException SQL Exception + */ + boolean isCaseSensitive(int columnIndex) throws SQLException; } 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 62e9a65241e..3f928bba4d6 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 @@ -34,6 +34,7 @@ import java.util.TreeMap; * Query result meta data. * * @author panjuan + * @author yangyi */ public final class QueryResultMetaData { @@ -120,6 +121,17 @@ public final class QueryResultMetaData { return columnLabelAndIndexes.get(columnLabel); } + /** + * Whether the column value is case sensitive. + * + * @param columnIndex column index + * @return true if column is case sensitive, otherwise false + */ + @SneakyThrows + public boolean isCaseSensitive(final int columnIndex) { + return resultSetMetaData.isCaseSensitive(columnIndex); + } + /** * Get sharding encryptor. * diff --git a/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java b/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java index ee8d6833be1..0163fc69f11 100644 --- a/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java +++ b/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java @@ -36,6 +36,7 @@ import java.util.Calendar; * * @author zhangliang * @author panjuan + * @author yangyi */ public final class StreamQueryResult implements QueryResult { @@ -139,6 +140,11 @@ public final class StreamQueryResult implements QueryResult { return resultSet.wasNull(); } + @Override + public boolean isCaseSensitive(final int columnIndex) { + return metaData.isCaseSensitive(columnIndex); + } + @Override public int getColumnCount() { return metaData.getColumnCount(); diff --git a/sharding-core/sharding-core-execute/src/test/java/org/apache/shardingsphere/core/execute/sql/execute/result/DistinctQueryResultTest.java b/sharding-core/sharding-core-execute/src/test/java/org/apache/shardingsphere/core/execute/sql/execute/result/DistinctQueryResultTest.java index 98b295b4e3e..45e6b048578 100644 --- a/sharding-core/sharding-core-execute/src/test/java/org/apache/shardingsphere/core/execute/sql/execute/result/DistinctQueryResultTest.java +++ b/sharding-core/sharding-core-execute/src/test/java/org/apache/shardingsphere/core/execute/sql/execute/result/DistinctQueryResultTest.java @@ -18,6 +18,7 @@ package org.apache.shardingsphere.core.execute.sql.execute.result; import com.google.common.collect.HashMultimap; +import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import lombok.SneakyThrows; import org.junit.Before; @@ -61,6 +62,7 @@ public class DistinctQueryResultTest { when(queryResult.getColumnCount()).thenReturn(1); when(queryResult.getColumnLabel(1)).thenReturn("order_id"); when(queryResult.getValue(1, Object.class)).thenReturn(10 * i); + when(queryResult.isCaseSensitive(1)).thenReturn(true); result.add(queryResult); result.add(queryResult); } @@ -134,6 +136,11 @@ public class DistinctQueryResultTest { assertTrue(distinctQueryResult.wasNull()); } + @Test + public void assertIsCaseSensitive() { + assertTrue(distinctQueryResult.isCaseSensitive(1)); + } + @Test public void assertGetColumnCount() { assertThat(distinctQueryResult.getColumnCount(), is(1)); @@ -163,6 +170,12 @@ public class DistinctQueryResultTest { assertThat(distinctQueryResult.getColumnLabelAndIndexMap(), is(expected)); } + @Test + public void assertGetColumnCaseSensitive() { + List<Boolean> expected = Lists.newArrayList(false, true); + assertThat(distinctQueryResult.getColumnCaseSensitive(), is(expected)); + } + @Test public void assertGetResultData() { assertThat(distinctQueryResult.getResultData().next().getColumnValue(1), is((Object) 10)); diff --git a/sharding-core/sharding-core-execute/src/test/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultMetaDataTest.java b/sharding-core/sharding-core-execute/src/test/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultMetaDataTest.java index aa02d1aec22..e3fa7d72944 100644 --- a/sharding-core/sharding-core-execute/src/test/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultMetaDataTest.java +++ b/sharding-core/sharding-core-execute/src/test/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultMetaDataTest.java @@ -32,6 +32,7 @@ import java.sql.SQLException; import java.util.Collections; import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; @@ -72,6 +73,7 @@ public class QueryResultMetaDataTest { when(result.getColumnName(anyInt())).thenReturn("column"); when(result.getColumnLabel(anyInt())).thenReturn("label"); when(result.getTableName(anyInt())).thenReturn("table"); + when(result.isCaseSensitive(anyInt())).thenReturn(false); return result; } @@ -95,6 +97,11 @@ public class QueryResultMetaDataTest { assertThat(queryResultMetaData.getColumnIndex("label"), is(1)); } + @Test + public void assertIsCaseSensitive() { + assertFalse(queryResultMetaData.isCaseSensitive(1)); + } + @Test public void assertGetShardingEncryptor() { assertThat(queryResultMetaData.getShardingEncryptor(1).get(), is(shardingEncryptor)); diff --git a/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/groupby/GroupByMemoryMergedResult.java b/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/groupby/GroupByMemoryMergedResult.java index f1f29386bdb..af78132eea0 100644 --- a/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/groupby/GroupByMemoryMergedResult.java +++ b/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/groupby/GroupByMemoryMergedResult.java @@ -19,6 +19,7 @@ package org.apache.shardingsphere.core.merge.dql.groupby; import com.google.common.base.Function; import com.google.common.base.Preconditions; +import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.shardingsphere.core.execute.sql.execute.result.QueryResult; import org.apache.shardingsphere.core.merge.dql.common.MemoryMergedResult; @@ -41,6 +42,7 @@ import java.util.Map.Entry; * Memory merged result for group by. * * @author zhangliang + * @author yangyi */ public final class GroupByMemoryMergedResult extends MemoryMergedResult { @@ -66,7 +68,8 @@ public final class GroupByMemoryMergedResult extends MemoryMergedResult { } } setAggregationValueToMemoryRow(dataMap, aggregationMap); - List<MemoryQueryResultRow> result = getMemoryResultSetRows(dataMap); + List<Boolean> valueCaseSensitive = queryResults.isEmpty() ? Collections.<Boolean>emptyList() : getValueCaseSensitive(queryResults.iterator().next()); + List<MemoryQueryResultRow> result = getMemoryResultSetRows(dataMap, valueCaseSensitive); if (!result.isEmpty()) { setCurrentResultSetRow(result.get(0)); } @@ -118,9 +121,17 @@ public final class GroupByMemoryMergedResult extends MemoryMergedResult { } } - private List<MemoryQueryResultRow> getMemoryResultSetRows(final Map<GroupByValue, MemoryQueryResultRow> dataMap) { + private List<Boolean> getValueCaseSensitive(final QueryResult queryResult) throws SQLException { + List<Boolean> result = Lists.newArrayList(false); + for (int columnIndex = 1; columnIndex <= queryResult.getColumnCount(); columnIndex++) { + result.add(queryResult.isCaseSensitive(columnIndex)); + } + return result; + } + + private List<MemoryQueryResultRow> getMemoryResultSetRows(final Map<GroupByValue, MemoryQueryResultRow> dataMap, final List<Boolean> valueCaseSensitive) { List<MemoryQueryResultRow> result = new ArrayList<>(dataMap.values()); - Collections.sort(result, new GroupByRowComparator(optimizedStatement)); + Collections.sort(result, new GroupByRowComparator(optimizedStatement, valueCaseSensitive)); return result; } diff --git a/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/groupby/GroupByRowComparator.java b/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/groupby/GroupByRowComparator.java index 78e42f09090..dc1d50327cf 100644 --- a/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/groupby/GroupByRowComparator.java +++ b/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/groupby/GroupByRowComparator.java @@ -26,17 +26,21 @@ import org.apache.shardingsphere.core.optimize.statement.sharding.dml.select.ord import java.util.Collection; import java.util.Comparator; +import java.util.List; /** * Group by row comparator. * * @author zhangliang + * @author yangyi */ @RequiredArgsConstructor public final class GroupByRowComparator implements Comparator<MemoryQueryResultRow> { private final ShardingSelectOptimizedStatement optimizedStatement; + private final List<Boolean> valueCaseSensitive; + @Override public int compare(final MemoryQueryResultRow o1, final MemoryQueryResultRow o2) { if (!optimizedStatement.getOrderBy().getItems().isEmpty()) { @@ -51,7 +55,8 @@ public final class GroupByRowComparator implements Comparator<MemoryQueryResultR Preconditions.checkState(null == orderValue1 || orderValue1 instanceof Comparable, "Order by value must implements Comparable"); Object orderValue2 = o2.getCell(each.getIndex()); Preconditions.checkState(null == orderValue2 || orderValue2 instanceof Comparable, "Order by value must implements Comparable"); - int result = CompareUtil.compareTo((Comparable) orderValue1, (Comparable) orderValue2, each.getSegment().getOrderDirection(), each.getSegment().getNullOrderDirection()); + int result = CompareUtil.compareTo((Comparable) orderValue1, (Comparable) orderValue2, each.getSegment().getOrderDirection(), + each.getSegment().getNullOrderDirection(), valueCaseSensitive.get(each.getIndex())); if (0 != result) { return result; } diff --git a/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/orderby/CompareUtil.java b/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/orderby/CompareUtil.java index 6157cf8f740..85a2322d013 100644 --- a/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/orderby/CompareUtil.java +++ b/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/orderby/CompareUtil.java @@ -25,6 +25,7 @@ import org.apache.shardingsphere.core.constant.OrderDirection; * Compare util. * * @author zhangliang + * @author yangyi */ @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public final class CompareUtil { @@ -36,10 +37,11 @@ public final class CompareUtil { * @param otherValue other value * @param orderDirection order direction * @param nullOrderDirection order direction for null value + * @param caseSensitive case sensitive * @return compare result */ @SuppressWarnings({ "rawtypes", "unchecked" }) - public static int compareTo(final Comparable thisValue, final Comparable otherValue, final OrderDirection orderDirection, final OrderDirection nullOrderDirection) { + public static int compareTo(final Comparable thisValue, final Comparable otherValue, final OrderDirection orderDirection, final OrderDirection nullOrderDirection, final boolean caseSensitive) { if (null == thisValue && null == otherValue) { return 0; } @@ -49,6 +51,14 @@ public final class CompareUtil { if (null == otherValue) { return orderDirection == nullOrderDirection ? 1 : -1; } + if (!caseSensitive && thisValue instanceof String && otherValue instanceof String) { + return compareToCaseInsensitiveString((String) thisValue, (String) otherValue, orderDirection); + } return OrderDirection.ASC == orderDirection ? thisValue.compareTo(otherValue) : -thisValue.compareTo(otherValue); } + + private static int compareToCaseInsensitiveString(final String thisValue, final String otherValue, final OrderDirection orderDirection) { + int result = thisValue.toUpperCase().compareTo(otherValue.toUpperCase()); + return OrderDirection.ASC == orderDirection ? result : -result; + } } diff --git a/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/orderby/OrderByValue.java b/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/orderby/OrderByValue.java index 182d0dfd288..75307dc3c9a 100644 --- a/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/orderby/OrderByValue.java +++ b/sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/orderby/OrderByValue.java @@ -19,7 +19,7 @@ package org.apache.shardingsphere.core.merge.dql.orderby; import com.google.common.base.Preconditions; import lombok.Getter; -import lombok.RequiredArgsConstructor; +import lombok.SneakyThrows; import org.apache.shardingsphere.core.execute.sql.execute.result.QueryResult; import org.apache.shardingsphere.core.optimize.statement.sharding.dml.select.orderby.OrderByItem; @@ -33,8 +33,8 @@ import java.util.List; * Order by value. * * @author zhangliang + * @author yangyi */ -@RequiredArgsConstructor public final class OrderByValue implements Comparable<OrderByValue> { @Getter @@ -42,8 +42,25 @@ public final class OrderByValue implements Comparable<OrderByValue> { private final Collection<OrderByItem> orderByItems; + private final List<Boolean> orderValuesCaseSensitive; + private List<Comparable<?>> orderValues; + public OrderByValue(final QueryResult queryResult, final Collection<OrderByItem> orderByItems) { + this.queryResult = queryResult; + this.orderByItems = orderByItems; + this.orderValuesCaseSensitive = getOrderValuesCaseSensitive(); + } + + @SneakyThrows + private List<Boolean> getOrderValuesCaseSensitive() { + List<Boolean> result = new ArrayList<>(orderByItems.size()); + for (OrderByItem each : orderByItems) { + result.add(queryResult.isCaseSensitive(each.getIndex())); + } + return result; + } + /** * iterate next data. * @@ -70,7 +87,8 @@ public final class OrderByValue implements Comparable<OrderByValue> { public int compareTo(final OrderByValue o) { int i = 0; for (OrderByItem each : orderByItems) { - int result = CompareUtil.compareTo(orderValues.get(i), o.orderValues.get(i), each.getSegment().getOrderDirection(), each.getSegment().getNullOrderDirection()); + int result = CompareUtil.compareTo(orderValues.get(i), o.orderValues.get(i), each.getSegment().getOrderDirection(), + each.getSegment().getNullOrderDirection(), orderValuesCaseSensitive.get(i)); if (0 != result) { return result; } diff --git a/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/DQLMergeEngineTest.java b/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/DQLMergeEngineTest.java index b40e8290262..402b317b421 100644 --- a/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/DQLMergeEngineTest.java +++ b/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/DQLMergeEngineTest.java @@ -80,13 +80,20 @@ public final class DQLMergeEngineTest { when(resultSetMetaData.getColumnCount()).thenReturn(1); when(resultSetMetaData.getColumnLabel(1)).thenReturn("count(*)"); singleQueryResult = Collections.<QueryResult>singletonList(new TestQueryResult(resultSet)); - List<ResultSet> resultSets = Lists.newArrayList(resultSet, mock(ResultSet.class), mock(ResultSet.class), mock(ResultSet.class)); + List<ResultSet> resultSets = Lists.newArrayList(resultSet, mockResultSet(), mockResultSet(), mockResultSet()); queryResults = new ArrayList<>(resultSets.size()); for (ResultSet each : resultSets) { queryResults.add(new TestQueryResult(each)); } } + private ResultSet mockResultSet() throws SQLException { + ResultSet result = mock(ResultSet.class); + ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class); + when(result.getMetaData()).thenReturn(resultSetMetaData); + return result; + } + @Test public void assertBuildIteratorStreamMergedResult() throws SQLException { OptimizedStatement optimizedStatement = new ShardingSelectOptimizedStatement(new SelectStatement(), Collections.<ShardingCondition>emptyList(), new AndCondition(), diff --git a/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/groupby/GroupByRowComparatorTest.java b/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/groupby/GroupByRowComparatorTest.java index 3a220a51f09..c0f3d69ca51 100644 --- a/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/groupby/GroupByRowComparatorTest.java +++ b/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/groupby/GroupByRowComparatorTest.java @@ -17,6 +17,7 @@ package org.apache.shardingsphere.core.merge.dql.groupby; +import com.google.common.collect.Lists; import org.apache.shardingsphere.core.constant.OrderDirection; import org.apache.shardingsphere.core.execute.sql.execute.result.QueryResult; import org.apache.shardingsphere.core.merge.dql.common.MemoryQueryResultRow; @@ -39,6 +40,7 @@ import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.Arrays; import java.util.Collections; +import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; @@ -48,6 +50,8 @@ import static org.mockito.Mockito.when; public final class GroupByRowComparatorTest { + private final List<Boolean> caseSensitives = Lists.newArrayList(false, false, false); + @Test public void assertCompareToForAscWithOrderByItems() throws SQLException { ShardingSelectOptimizedStatement optimizedStatement = new ShardingSelectOptimizedStatement( @@ -59,7 +63,7 @@ public final class GroupByRowComparatorTest { createOrderByItem(new IndexOrderByItemSegment(0, 0, 1, OrderDirection.ASC, OrderDirection.ASC)), createOrderByItem(new IndexOrderByItemSegment(0, 0, 2, OrderDirection.ASC, OrderDirection.ASC))), false), new SelectItems(Collections.<SelectItem>emptyList(), false, 0), new Pagination(null, null, Collections.emptyList())); - GroupByRowComparator groupByRowComparator = new GroupByRowComparator(optimizedStatement); + GroupByRowComparator groupByRowComparator = new GroupByRowComparator(optimizedStatement, caseSensitives); MemoryQueryResultRow o1 = new MemoryQueryResultRow(mockQueryResult("1", "2")); MemoryQueryResultRow o2 = new MemoryQueryResultRow(mockQueryResult("3", "4")); assertTrue(groupByRowComparator.compare(o1, o2) < 0); @@ -76,7 +80,7 @@ public final class GroupByRowComparatorTest { createOrderByItem(new IndexOrderByItemSegment(0, 0, 1, OrderDirection.DESC, OrderDirection.ASC)), createOrderByItem(new IndexOrderByItemSegment(0, 0, 2, OrderDirection.DESC, OrderDirection.ASC))), false), new SelectItems(Collections.<SelectItem>emptyList(), false, 0), new Pagination(null, null, Collections.emptyList())); - GroupByRowComparator groupByRowComparator = new GroupByRowComparator(optimizedStatement); + GroupByRowComparator groupByRowComparator = new GroupByRowComparator(optimizedStatement, caseSensitives); MemoryQueryResultRow o1 = new MemoryQueryResultRow(mockQueryResult("1", "2")); MemoryQueryResultRow o2 = new MemoryQueryResultRow(mockQueryResult("3", "4")); assertTrue(groupByRowComparator.compare(o1, o2) > 0); @@ -93,7 +97,7 @@ public final class GroupByRowComparatorTest { createOrderByItem(new IndexOrderByItemSegment(0, 0, 1, OrderDirection.ASC, OrderDirection.ASC)), createOrderByItem(new IndexOrderByItemSegment(0, 0, 2, OrderDirection.DESC, OrderDirection.ASC))), false), new SelectItems(Collections.<SelectItem>emptyList(), false, 0), new Pagination(null, null, Collections.emptyList())); - GroupByRowComparator groupByRowComparator = new GroupByRowComparator(optimizedStatement); + GroupByRowComparator groupByRowComparator = new GroupByRowComparator(optimizedStatement, caseSensitives); MemoryQueryResultRow o1 = new MemoryQueryResultRow(mockQueryResult("1", "2")); MemoryQueryResultRow o2 = new MemoryQueryResultRow(mockQueryResult("1", "2")); assertThat(groupByRowComparator.compare(o1, o2), is(0)); @@ -107,7 +111,7 @@ public final class GroupByRowComparatorTest { createOrderByItem(new IndexOrderByItemSegment(0, 0, 1, OrderDirection.ASC, OrderDirection.ASC)), createOrderByItem(new IndexOrderByItemSegment(0, 0, 2, OrderDirection.ASC, OrderDirection.ASC))), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false), new SelectItems(Collections.<SelectItem>emptyList(), false, 0), new Pagination(null, null, Collections.emptyList())); - GroupByRowComparator groupByRowComparator = new GroupByRowComparator(optimizedStatement); + GroupByRowComparator groupByRowComparator = new GroupByRowComparator(optimizedStatement, caseSensitives); MemoryQueryResultRow o1 = new MemoryQueryResultRow(mockQueryResult("1", "2")); MemoryQueryResultRow o2 = new MemoryQueryResultRow(mockQueryResult("3", "4")); assertTrue(groupByRowComparator.compare(o1, o2) < 0); @@ -121,7 +125,7 @@ public final class GroupByRowComparatorTest { createOrderByItem(new IndexOrderByItemSegment(0, 0, 1, OrderDirection.DESC, OrderDirection.ASC)), createOrderByItem(new IndexOrderByItemSegment(0, 0, 2, OrderDirection.DESC, OrderDirection.ASC))), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false), new SelectItems(Collections.<SelectItem>emptyList(), false, 0), new Pagination(null, null, Collections.emptyList())); - GroupByRowComparator groupByRowComparator = new GroupByRowComparator(optimizedStatement); + GroupByRowComparator groupByRowComparator = new GroupByRowComparator(optimizedStatement, caseSensitives); MemoryQueryResultRow o1 = new MemoryQueryResultRow(mockQueryResult("1", "2")); MemoryQueryResultRow o2 = new MemoryQueryResultRow(mockQueryResult("3", "4")); assertTrue(groupByRowComparator.compare(o1, o2) > 0); @@ -135,7 +139,7 @@ public final class GroupByRowComparatorTest { createOrderByItem(new IndexOrderByItemSegment(0, 0, 1, OrderDirection.ASC, OrderDirection.ASC)), createOrderByItem(new IndexOrderByItemSegment(0, 0, 2, OrderDirection.DESC, OrderDirection.ASC))), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false), new SelectItems(Collections.<SelectItem>emptyList(), false, 0), new Pagination(null, null, Collections.emptyList())); - GroupByRowComparator groupByRowComparator = new GroupByRowComparator(optimizedStatement); + GroupByRowComparator groupByRowComparator = new GroupByRowComparator(optimizedStatement, caseSensitives); MemoryQueryResultRow o1 = new MemoryQueryResultRow(mockQueryResult("1", "2")); MemoryQueryResultRow o2 = new MemoryQueryResultRow(mockQueryResult("1", "2")); assertThat(groupByRowComparator.compare(o1, o2), is(0)); diff --git a/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/orderby/CompareUtilTest.java b/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/orderby/CompareUtilTest.java index b61457016e5..4c0d1003432 100644 --- a/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/orderby/CompareUtilTest.java +++ b/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/orderby/CompareUtilTest.java @@ -25,58 +25,70 @@ import static org.junit.Assert.assertThat; public final class CompareUtilTest { + private final boolean caseSensitive = true; + @Test public void assertCompareToWhenBothNull() { - assertThat(CompareUtil.compareTo(null, null, OrderDirection.DESC, OrderDirection.ASC), is(0)); + assertThat(CompareUtil.compareTo(null, null, OrderDirection.DESC, OrderDirection.ASC, caseSensitive), is(0)); } @Test public void assertCompareToWhenFirstValueIsNullForOrderByAscAndNullOrderByAsc() { - assertThat(CompareUtil.compareTo(null, 1, OrderDirection.ASC, OrderDirection.ASC), is(-1)); + assertThat(CompareUtil.compareTo(null, 1, OrderDirection.ASC, OrderDirection.ASC, caseSensitive), is(-1)); } @Test public void assertCompareToWhenFirstValueIsNullForOrderByAscAndNullOrderByDesc() { - assertThat(CompareUtil.compareTo(null, 1, OrderDirection.ASC, OrderDirection.DESC), is(1)); + assertThat(CompareUtil.compareTo(null, 1, OrderDirection.ASC, OrderDirection.DESC, caseSensitive), is(1)); } @Test public void assertCompareToWhenFirstValueIsNullForOrderByDescAndNullOrderByAsc() { - assertThat(CompareUtil.compareTo(null, 1, OrderDirection.DESC, OrderDirection.ASC), is(1)); + assertThat(CompareUtil.compareTo(null, 1, OrderDirection.DESC, OrderDirection.ASC, caseSensitive), is(1)); } @Test public void assertCompareToWhenFirstValueIsNullForOrderByDescAndNullOrderByDesc() { - assertThat(CompareUtil.compareTo(null, 1, OrderDirection.DESC, OrderDirection.DESC), is(-1)); + assertThat(CompareUtil.compareTo(null, 1, OrderDirection.DESC, OrderDirection.DESC, caseSensitive), is(-1)); } @Test public void assertCompareToWhenSecondValueIsNullForOrderByAscAndNullOrderByAsc() { - assertThat(CompareUtil.compareTo(1, null, OrderDirection.ASC, OrderDirection.ASC), is(1)); + assertThat(CompareUtil.compareTo(1, null, OrderDirection.ASC, OrderDirection.ASC, caseSensitive), is(1)); } @Test public void assertCompareToWhenSecondValueIsNullForOrderByAscAndNullOrderByDesc() { - assertThat(CompareUtil.compareTo(1, null, OrderDirection.ASC, OrderDirection.DESC), is(-1)); + assertThat(CompareUtil.compareTo(1, null, OrderDirection.ASC, OrderDirection.DESC, caseSensitive), is(-1)); } @Test public void assertCompareToWhenSecondValueIsNullForOrderByDescAndNullOrderByAsc() { - assertThat(CompareUtil.compareTo(1, null, OrderDirection.DESC, OrderDirection.ASC), is(-1)); + assertThat(CompareUtil.compareTo(1, null, OrderDirection.DESC, OrderDirection.ASC, caseSensitive), is(-1)); } @Test public void assertCompareToWhenSecondValueIsNullForOrderByDescAndNullOrderByDesc() { - assertThat(CompareUtil.compareTo(1, null, OrderDirection.DESC, OrderDirection.DESC), is(1)); + assertThat(CompareUtil.compareTo(1, null, OrderDirection.DESC, OrderDirection.DESC, caseSensitive), is(1)); } @Test public void assertCompareToWhenAsc() { - assertThat(CompareUtil.compareTo(1, 2, OrderDirection.ASC, OrderDirection.ASC), is(-1)); + assertThat(CompareUtil.compareTo(1, 2, OrderDirection.ASC, OrderDirection.ASC, caseSensitive), is(-1)); } @Test public void assertCompareToWhenDesc() { - assertThat(CompareUtil.compareTo(1, 2, OrderDirection.DESC, OrderDirection.ASC), is(1)); + assertThat(CompareUtil.compareTo(1, 2, OrderDirection.DESC, OrderDirection.ASC, caseSensitive), is(1)); + } + + @Test + public void assetCompareToStringWithCaseSensitive() { + assertThat(CompareUtil.compareTo("A", "a", OrderDirection.DESC, OrderDirection.ASC, caseSensitive), is(32)); + } + + @Test + public void assetCompareToStringWithCaseInsensitive() { + assertThat(CompareUtil.compareTo("A", "a", OrderDirection.DESC, OrderDirection.ASC, !caseSensitive), is(0)); } } diff --git a/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/orderby/OrderByStreamMergedResultTest.java b/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/orderby/OrderByStreamMergedResultTest.java index 1dd6ba63402..813ca0850d4 100644 --- a/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/orderby/OrderByStreamMergedResultTest.java +++ b/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/orderby/OrderByStreamMergedResultTest.java @@ -63,11 +63,8 @@ public final class OrderByStreamMergedResultTest { @Before public void setUp() throws SQLException { - ResultSet resultSet = mock(ResultSet.class); - ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class); - when(resultSet.getMetaData()).thenReturn(resultSetMetaData); queryResults = Lists.<QueryResult>newArrayList( - new TestQueryResult(resultSet), new TestQueryResult(mock(ResultSet.class)), new TestQueryResult(mock(ResultSet.class))); + new TestQueryResult(mockResultSet()), new TestQueryResult(mockResultSet()), new TestQueryResult(mockResultSet())); OptimizedStatement optimizedStatement = new ShardingSelectOptimizedStatement( new SelectStatement(), Collections.<ShardingCondition>emptyList(), new AndCondition(), new GroupBy(Collections.<OrderByItem>emptyList(), 0), new OrderBy(Collections.singletonList(new OrderByItem(new IndexOrderByItemSegment(0, 0, 1, OrderDirection.ASC, OrderDirection.ASC))), false), @@ -75,6 +72,13 @@ public final class OrderByStreamMergedResultTest { routeResult = new SQLRouteResult(optimizedStatement); } + private ResultSet mockResultSet() throws SQLException { + ResultSet result = mock(ResultSet.class); + ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class); + when(result.getMetaData()).thenReturn(resultSetMetaData); + return result; + } + @Test public void assertNextForResultSetsAllEmpty() throws SQLException { mergeEngine = new DQLMergeEngine(DatabaseTypes.getActualDatabaseType("MySQL"), routeResult, queryResults); @@ -123,4 +127,52 @@ public final class OrderByStreamMergedResultTest { assertThat(actual.getValue(1, Object.class).toString(), is("4")); assertFalse(actual.next()); } + + @Test + public void assertNextForCaseSensitive() throws SQLException { + when(queryResults.get(0).next()).thenReturn(true, false); + when(queryResults.get(0).isCaseSensitive(1)).thenReturn(true); + when(queryResults.get(0).getValue(1, Object.class)).thenReturn("b"); + when(queryResults.get(1).next()).thenReturn(true, true, false); + when(queryResults.get(1).isCaseSensitive(1)).thenReturn(true); + when(queryResults.get(1).getValue(1, Object.class)).thenReturn("B", "B", "a", "a"); + when(queryResults.get(2).next()).thenReturn(true, false); + when(queryResults.get(2).isCaseSensitive(1)).thenReturn(true); + when(queryResults.get(2).getValue(1, Object.class)).thenReturn("A"); + mergeEngine = new DQLMergeEngine(DatabaseTypes.getActualDatabaseType("MySQL"), routeResult, queryResults); + MergedResult actual = mergeEngine.merge(); + assertTrue(actual.next()); + assertThat(actual.getValue(1, Object.class).toString(), is("A")); + assertTrue(actual.next()); + assertThat(actual.getValue(1, Object.class).toString(), is("B")); + assertTrue(actual.next()); + assertThat(actual.getValue(1, Object.class).toString(), is("a")); + assertTrue(actual.next()); + assertThat(actual.getValue(1, Object.class).toString(), is("b")); + assertFalse(actual.next()); + } + + @Test + public void assertNextForCaseInsensitive() throws SQLException { + when(queryResults.get(0).next()).thenReturn(true, false); + when(queryResults.get(0).isCaseSensitive(1)).thenReturn(false); + when(queryResults.get(0).getValue(1, Object.class)).thenReturn("b"); + when(queryResults.get(1).next()).thenReturn(true, true, false); + when(queryResults.get(1).isCaseSensitive(1)).thenReturn(false); + when(queryResults.get(1).getValue(1, Object.class)).thenReturn("a", "a", "B", "B"); + when(queryResults.get(2).next()).thenReturn(true, false); + when(queryResults.get(2).isCaseSensitive(1)).thenReturn(false); + when(queryResults.get(2).getValue(1, Object.class)).thenReturn("A"); + mergeEngine = new DQLMergeEngine(DatabaseTypes.getActualDatabaseType("MySQL"), routeResult, queryResults); + MergedResult actual = mergeEngine.merge(); + assertTrue(actual.next()); + assertThat(actual.getValue(1, Object.class).toString(), is("a")); + assertTrue(actual.next()); + assertThat(actual.getValue(1, Object.class).toString(), is("A")); + assertTrue(actual.next()); + assertThat(actual.getValue(1, Object.class).toString(), is("B")); + assertTrue(actual.next()); + assertThat(actual.getValue(1, Object.class).toString(), is("b")); + assertFalse(actual.next()); + } } diff --git a/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/orderby/OrderByValueTest.java b/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/orderby/OrderByValueTest.java index d61aa78c441..5b47c89ab7c 100644 --- a/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/orderby/OrderByValueTest.java +++ b/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/orderby/OrderByValueTest.java @@ -28,6 +28,7 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.sql.ResultSet; +import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.Arrays; @@ -46,12 +47,19 @@ public final class OrderByValueTest { @Mock private ResultSet resultSet2; + @Mock + private ResultSetMetaData resultSetMetaData; + @Before public void setUp() throws SQLException { when(resultSet1.next()).thenReturn(true, false); when(resultSet2.next()).thenReturn(true, false); when(resultSet1.getObject(1)).thenReturn("1"); when(resultSet1.getObject(2)).thenReturn("2"); + when(resultSet1.getMetaData()).thenReturn(resultSetMetaData); + when(resultSet2.getMetaData()).thenReturn(resultSetMetaData); + when(resultSetMetaData.isCaseSensitive(1)).thenReturn(false); + when(resultSetMetaData.isCaseSensitive(1)).thenReturn(true); } @Test diff --git a/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/fixture/TestQueryResult.java b/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/fixture/TestQueryResult.java index ed9dbaf23b5..f7583dd585c 100644 --- a/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/fixture/TestQueryResult.java +++ b/sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/fixture/TestQueryResult.java @@ -201,6 +201,11 @@ public final class TestQueryResult implements QueryResult { return resultSet.wasNull(); } + @Override + public boolean isCaseSensitive(final int columnIndex) throws SQLException { + return resultSet.getMetaData().isCaseSensitive(columnIndex); + } + @Override public int getColumnCount() throws SQLException { return resultSet.getMetaData().getColumnCount();
['sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/MemoryQueryResult.java', 'sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/groupby/GroupByRowComparator.java', 'sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/AggregationDistinctQueryResult.java', 'sharding-core/sharding-core-execute/src/test/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultMetaDataTest.java', 'sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/orderby/CompareUtil.java', 'sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/DistinctQueryResult.java', 'sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/groupby/GroupByRowComparatorTest.java', 'sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/groupby/GroupByMemoryMergedResult.java', 'sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/StreamQueryResult.java', 'sharding-core/sharding-core-merge/src/main/java/org/apache/shardingsphere/core/merge/dql/orderby/OrderByValue.java', 'sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/DQLMergeEngineTest.java', 'sharding-core/sharding-core-execute/src/test/java/org/apache/shardingsphere/core/execute/sql/execute/result/DistinctQueryResultTest.java', 'sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/fixture/TestQueryResult.java', 'sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/orderby/OrderByStreamMergedResultTest.java', 'sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResult.java', 'sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/orderby/OrderByValueTest.java', 'sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultMetaData.java', 'sharding-core/sharding-core-merge/src/test/java/org/apache/shardingsphere/core/merge/dql/orderby/CompareUtilTest.java']
{'.java': 18}
18
18
0
0
18
2,992,753
600,410
76,352
1,047
6,618
1,287
121
10
4,063
580
1,341
163
0
4
1970-01-01T00:26:03
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,474
apache/shardingsphere/2678/2629
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2629
https://github.com/apache/shardingsphere/pull/2678
https://github.com/apache/shardingsphere/pull/2678
1
fixes
Get NullPointerException when execute SQL on tables without sharding rule
## 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/apache/incubator-shardingsphere-example/issues). - Read documentation: [ShardingSphere Doc](https://shardingsphere.apache.org/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? ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-JDBC and Sharding-Proxy ### Expected behavior Get Sharding Execption when execute SQL on tables without sharding rule ### Actual behavior Get NullPointerException when execute SQL on tables without sharding rule ### Reason analyze (If you can) Parse engine will parse tableName, Route engine pass the SQLStatement to UnicastRoutingEngine, which return RoutingResult with null datasource name. Ref: ``` RoutingEngineFactory.java if (shardingRule.isAllBroadcastTables(tableNames)) { return sqlStatement instanceof SelectStatement ? new UnicastRoutingEngine(shardingRule, tableNames) : new DatabaseBroadcastRoutingEngine(shardingRule); } ShardingDataSourceNames.java public String getDefaultDataSourceName() { return 1 == dataSourceNames.size() ? dataSourceNames.iterator().next() : shardingRuleConfig.getDefaultDataSourceName(); } ``` ### 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).
ae3ea6a8edbd2bc709e507b78c1fb90021b8f7f5
3b9f933ca11b84e67e86cb8bc362e78c45501b12
https://github.com/apache/shardingsphere/compare/ae3ea6a8edbd2bc709e507b78c1fb90021b8f7f5...3b9f933ca11b84e67e86cb8bc362e78c45501b12
diff --git a/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingDataSourceNames.java b/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingDataSourceNames.java index 79d5acf97dc..64d007846cb 100644 --- a/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingDataSourceNames.java +++ b/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingDataSourceNames.java @@ -17,6 +17,7 @@ package org.apache.shardingsphere.core.rule; +import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import lombok.Getter; import org.apache.shardingsphere.api.config.masterslave.MasterSlaveRuleConfiguration; @@ -41,6 +42,7 @@ public final class ShardingDataSourceNames { private final Collection<String> dataSourceNames; public ShardingDataSourceNames(final ShardingRuleConfiguration shardingRuleConfig, final Collection<String> rawDataSourceNames) { + Preconditions.checkArgument(null != shardingRuleConfig, "can not construct ShardingDataSourceNames with null ShardingRuleConfig"); this.shardingRuleConfig = shardingRuleConfig; dataSourceNames = getAllDataSourceNames(rawDataSourceNames); } diff --git a/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingRule.java b/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingRule.java index 8490e7f4db8..48bf8699de6 100644 --- a/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingRule.java +++ b/sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingRule.java @@ -73,7 +73,8 @@ public class ShardingRule implements BaseRule { private final EncryptRule encryptRule; public ShardingRule(final ShardingRuleConfiguration shardingRuleConfig, final Collection<String> dataSourceNames) { - Preconditions.checkArgument(!dataSourceNames.isEmpty(), "Data sources cannot be empty."); + Preconditions.checkArgument(null != shardingRuleConfig, "ShardingRuleConfig cannot be null."); + Preconditions.checkArgument(null != dataSourceNames && !dataSourceNames.isEmpty(), "Data sources cannot be empty."); this.shardingRuleConfig = shardingRuleConfig; shardingDataSourceNames = new ShardingDataSourceNames(shardingRuleConfig, dataSourceNames); tableRules = createTableRules(shardingRuleConfig); diff --git a/sharding-core/sharding-core-common/src/test/java/org/apache/shardingsphere/core/rule/ShardingDataSourceNamesTest.java b/sharding-core/sharding-core-common/src/test/java/org/apache/shardingsphere/core/rule/ShardingDataSourceNamesTest.java index e127f5b2613..a0140a60033 100644 --- a/sharding-core/sharding-core-common/src/test/java/org/apache/shardingsphere/core/rule/ShardingDataSourceNamesTest.java +++ b/sharding-core/sharding-core-common/src/test/java/org/apache/shardingsphere/core/rule/ShardingDataSourceNamesTest.java @@ -31,6 +31,7 @@ import java.util.Collections; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; public final class ShardingDataSourceNamesTest { @@ -90,4 +91,9 @@ public final class ShardingDataSourceNamesTest { String actual = new ShardingDataSourceNames(shardingRuleConfig, Arrays.asList("master_ds", "slave_ds")).getRawMasterDataSourceName("default_ds"); assertThat(actual, is("default_ds")); } + + @Test(expected = IllegalArgumentException.class) + public void assertConstructShardingDataSourceNamesWithNullShardingRuleConfiguration() { + new ShardingDataSourceNames(null, Arrays.asList("master_ds", "slave_ds")).getRawMasterDataSourceName("default_ds"); + } } diff --git a/sharding-core/sharding-core-common/src/test/java/org/apache/shardingsphere/core/rule/ShardingRuleTest.java b/sharding-core/sharding-core-common/src/test/java/org/apache/shardingsphere/core/rule/ShardingRuleTest.java index 60df86596e1..8b48c1ce954 100644 --- a/sharding-core/sharding-core-common/src/test/java/org/apache/shardingsphere/core/rule/ShardingRuleTest.java +++ b/sharding-core/sharding-core-common/src/test/java/org/apache/shardingsphere/core/rule/ShardingRuleTest.java @@ -43,6 +43,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -328,6 +329,21 @@ public final class ShardingRuleTest { ShardingRule actual = createMaximumShardingRule(); assertThat(actual.getShardingLogicTableNames(Arrays.asList("LOGIC_TABLE", "BROADCAST_TABLE")), CoreMatchers.<Collection<String>>is(Collections.singletonList("LOGIC_TABLE"))); } + + @Test(expected = IllegalArgumentException.class) + public void assertConstructShardingRuleWithNullShardingRuleConfiguration() { + new ShardingRule(null, createDataSourceNames()); + } + + @Test(expected = IllegalArgumentException.class) + public void assertConstructShardingRuleWithNullDataSourceNames(){ + ShardingRuleConfiguration shardingRuleConfiguration = new ShardingRuleConfiguration(); + TableRuleConfiguration tableRuleConfiguration = createTableRuleConfiguration("LOGIC_TABLE", "ms_ds_${0..1}.table_${0..2}"); + shardingRuleConfiguration.getTableRuleConfigs().add(tableRuleConfiguration); + shardingRuleConfiguration.getMasterSlaveRuleConfigs().add(createMasterSlaveRuleConfiguration("ms_ds_0", "master_ds_0", "slave_ds_0")); + shardingRuleConfiguration.getMasterSlaveRuleConfigs().add(createMasterSlaveRuleConfiguration("ms_ds_1", "master_ds_1", "slave_ds_1")); + new ShardingRule(shardingRuleConfiguration, null); + } private ShardingRule createMaximumShardingRule() { ShardingRuleConfiguration shardingRuleConfiguration = new ShardingRuleConfiguration();
['sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingDataSourceNames.java', 'sharding-core/sharding-core-common/src/test/java/org/apache/shardingsphere/core/rule/ShardingRuleTest.java', 'sharding-core/sharding-core-common/src/main/java/org/apache/shardingsphere/core/rule/ShardingRule.java', 'sharding-core/sharding-core-common/src/test/java/org/apache/shardingsphere/core/rule/ShardingDataSourceNamesTest.java']
{'.java': 4}
4
4
0
0
4
2,979,125
597,718
76,020
1,041
513
91
5
2
1,809
207
373
40
2
1
1970-01-01T00:26:02
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,475
apache/shardingsphere/2598/2596
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2596
https://github.com/apache/shardingsphere/pull/2598
https://github.com/apache/shardingsphere/pull/2598
1
fix
use sharding-jdbc-spring-boot-starter throw java.util.NoSuchElementException: No value bound
## 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/apache/incubator-shardingsphere-example/issues). - Read documentation: [ShardingSphere Doc](https://shardingsphere.apache.org/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-RC2-SNAPSHOT ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-JDBC ### Expected behavior Do not throw an exception ### Actual behavior throw an exception ### Reason analyze (If you can) spring.shardingsphere.encrypt.encryptors is not configured ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc. pom.xml ```xml <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <java.version>1.8</java.version> <!-- <sharding-sphere.version>4.0.0-RC1</sharding-sphere.version> --> <sharding-sphere.version>4.0.0-RC2-SNAPSHOT</sharding-sphere.version> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> <relativePath /> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>sharding-jdbc-spring-boot-starter</artifactId> <version>${sharding-sphere.version}</version> </dependency> </dependencies> ``` application.yml ```yml spring: shardingsphere: datasource: names: d0,d1 d0: type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.jdbc.Driver jdbc-url: jdbc:mysql://dbserver:3306/d0?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false username: root password: d1: type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.jdbc.Driver jdbc-url: jdbc:mysql://dbserver:3306/d1?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false username: root password: props: sql: show: true ``` DemoApplication.java ```java @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` Log ``` java.lang.reflect.InvocationTargetException: null at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191] at org.apache.shardingsphere.shardingjdbc.spring.boot.util.PropertyUtil.v2(PropertyUtil.java:98) ~[sharding-jdbc-spring-boot-starter-4.0.0-RC2-SNAPSHOT.jar:4.0.0-RC2-SNAPSHOT] at org.apache.shardingsphere.shardingjdbc.spring.boot.util.PropertyUtil.handle(PropertyUtil.java:61) ~[sharding-jdbc-spring-boot-starter-4.0.0-RC2-SNAPSHOT.jar:4.0.0-RC2-SNAPSHOT] at org.apache.shardingsphere.shardingjdbc.spring.boot.encrypt.EncryptRuleCondition.getMatchOutcome(EncryptRuleCondition.java:40) ~[sharding-jdbc-spring-boot-starter-4.0.0-RC2-SNAPSHOT.jar:4.0.0-RC2-SNAPSHOT] at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:47) ~[spring-boot-autoconfigure-2.0.1.RELEASE.jar:2.0.1.RELEASE] at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:108) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForBeanMethod(ConfigurationClassBeanDefinitionReader.java:179) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:141) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:117) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:328) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:233) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:273) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:93) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:694) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:532) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) [spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE] at net.saisimon.demo.DemoApplication.main(DemoApplication.java:10) [classes/:na] Caused by: java.util.NoSuchElementException: No value bound at org.springframework.boot.context.properties.bind.BindResult.get(BindResult.java:56) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE] ... 25 common frames omitted ``` ### Example codes for reproduce this issue (such as a github link).
a4ec12b259bc3d0349e3e2369f4ef7927254787c
f9fa5dbcc7f941206e52446b9d69bb7b21f89f47
https://github.com/apache/shardingsphere/compare/a4ec12b259bc3d0349e3e2369f4ef7927254787c...f9fa5dbcc7f941206e52446b9d69bb7b21f89f47
diff --git a/sharding-spring/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/main/java/org/apache/shardingsphere/shardingjdbc/orchestration/spring/boot/util/PropertyUtil.java b/sharding-spring/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/main/java/org/apache/shardingsphere/shardingjdbc/orchestration/spring/boot/util/PropertyUtil.java index 30bcee5a36c..61316090f78 100644 --- a/sharding-spring/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/main/java/org/apache/shardingsphere/shardingjdbc/orchestration/spring/boot/util/PropertyUtil.java +++ b/sharding-spring/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/main/java/org/apache/shardingsphere/shardingjdbc/orchestration/spring/boot/util/PropertyUtil.java @@ -53,8 +53,14 @@ public final class PropertyUtil { */ @SuppressWarnings("unchecked") public static boolean containPropertyPrefix(final Environment environment, final String prefix) { - Map<String, Object> properties = (Map<String, Object>) (1 == springBootVersion ? v1(environment, prefix, false) : v2(environment, prefix, Map.class)); - return !properties.isEmpty(); + try { + Map<String, Object> properties = (Map<String, Object>) (1 == springBootVersion ? v1(environment, prefix, false) : v2(environment, prefix, Map.class)); + return !properties.isEmpty(); + // CHECKSTYLE:OFF + } catch (final Exception ex) { + // CHECKSTYLE:ON + return false; + } } /** diff --git a/sharding-spring/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/src/main/java/org/apache/shardingsphere/shardingjdbc/spring/boot/encrypt/EncryptRuleCondition.java b/sharding-spring/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/src/main/java/org/apache/shardingsphere/shardingjdbc/spring/boot/encrypt/EncryptRuleCondition.java index 95adbf923dd..3163973c313 100644 --- a/sharding-spring/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/src/main/java/org/apache/shardingsphere/shardingjdbc/spring/boot/encrypt/EncryptRuleCondition.java +++ b/sharding-spring/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/src/main/java/org/apache/shardingsphere/shardingjdbc/spring/boot/encrypt/EncryptRuleCondition.java @@ -23,7 +23,6 @@ import org.springframework.boot.autoconfigure.condition.SpringBootCondition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; -import java.util.Map; /** * Encrypt condition. @@ -35,9 +34,8 @@ public final class EncryptRuleCondition extends SpringBootCondition { private static final String ENCRYPT_PREFIX = "spring.shardingsphere.encrypt.encryptors"; @Override - @SuppressWarnings("unchecked") public ConditionOutcome getMatchOutcome(final ConditionContext conditionContext, final AnnotatedTypeMetadata annotatedTypeMetadata) { - Map<String, Object> encryptors = PropertyUtil.handle(conditionContext.getEnvironment(), ENCRYPT_PREFIX.trim(), Map.class); - return encryptors.isEmpty() ? ConditionOutcome.noMatch("Can't find ShardingSphere encrypt rule configuration in environment.") : ConditionOutcome.match(); + boolean isEncrypt = PropertyUtil.containPropertyPrefix(conditionContext.getEnvironment(), ENCRYPT_PREFIX); + return isEncrypt ? ConditionOutcome.match() : ConditionOutcome.noMatch("Can't find ShardingSphere encrypt rule configuration in environment."); } } diff --git a/sharding-spring/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/src/main/java/org/apache/shardingsphere/shardingjdbc/spring/boot/util/PropertyUtil.java b/sharding-spring/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/src/main/java/org/apache/shardingsphere/shardingjdbc/spring/boot/util/PropertyUtil.java index 61673badf60..468dc8f2dee 100644 --- a/sharding-spring/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/src/main/java/org/apache/shardingsphere/shardingjdbc/spring/boot/util/PropertyUtil.java +++ b/sharding-spring/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/src/main/java/org/apache/shardingsphere/shardingjdbc/spring/boot/util/PropertyUtil.java @@ -44,6 +44,25 @@ public final class PropertyUtil { } } + /** + * Whether environment contain properties with specified prefix. + * + * @param environment the environment context + * @param prefix the prefix part of property key + * @return true if contain, otherwise false + */ + @SuppressWarnings("unchecked") + public static boolean containPropertyPrefix(final Environment environment, final String prefix) { + try { + Map<String, Object> properties = (Map<String, Object>) (1 == springBootVersion ? v1(environment, prefix, false) : v2(environment, prefix, Map.class)); + return !properties.isEmpty(); + // CHECKSTYLE:OFF + } catch (final Exception ex) { + // CHECKSTYLE:ON + return false; + } + } + /** * Spring Boot 1.x is compatible with Spring Boot 2.x by Using Java Reflect. * @param environment : the environment context @@ -56,7 +75,7 @@ public final class PropertyUtil { public static <T> T handle(final Environment environment, final String prefix, final Class<T> targetClass) { switch (springBootVersion) { case 1: - return (T) v1(environment, prefix); + return (T) v1(environment, prefix, true); default: return (T) v2(environment, prefix, targetClass); } @@ -64,7 +83,7 @@ public final class PropertyUtil { @SuppressWarnings("unchecked") @SneakyThrows - private static Object v1(final Environment environment, final String prefix) { + private static Object v1(final Environment environment, final String prefix, final boolean handlePlaceholder) { Class<?> resolverClass = Class.forName("org.springframework.boot.bind.RelaxedPropertyResolver"); Constructor<?> resolverConstructor = resolverClass.getDeclaredConstructor(PropertyResolver.class); Method getSubPropertiesMethod = resolverClass.getDeclaredMethod("getSubProperties", String.class); @@ -76,7 +95,7 @@ public final class PropertyUtil { for (Entry<String, Object> entry : dataSourceProps.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); - if (value instanceof String && ((String) value).contains(PlaceholderConfigurerSupport.DEFAULT_PLACEHOLDER_PREFIX)) { + if (handlePlaceholder && value instanceof String && ((String) value).contains(PlaceholderConfigurerSupport.DEFAULT_PLACEHOLDER_PREFIX)) { String resolvedValue = (String) getPropertyMethod.invoke(resolverObject, prefixParam + key); propertiesWithPlaceholderResolved.put(key, resolvedValue); } else {
['sharding-spring/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/src/main/java/org/apache/shardingsphere/shardingjdbc/spring/boot/util/PropertyUtil.java', 'sharding-spring/sharding-jdbc-orchestration-spring/sharding-jdbc-orchestration-spring-boot-starter/src/main/java/org/apache/shardingsphere/shardingjdbc/orchestration/spring/boot/util/PropertyUtil.java', 'sharding-spring/sharding-jdbc-spring/sharding-jdbc-spring-boot-starter/src/main/java/org/apache/shardingsphere/shardingjdbc/spring/boot/encrypt/EncryptRuleCondition.java']
{'.java': 3}
3
3
0
0
3
2,990,278
600,549
76,529
1,049
2,538
493
41
3
7,537
329
1,913
130
2
4
1970-01-01T00:26:01
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,489
apache/shardingsphere/2296/2224
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/2224
https://github.com/apache/shardingsphere/pull/2296
https://github.com/apache/shardingsphere/pull/2296
1
fixes
wrong result for the null value in int column
age null mysql> insert into my_orders(name,create_time,age,ttt,dc) values('ruiaylin1', '2019-04-16 18:00:00', null,null, 14.56) ; Query OK, 1 row affected (0.10 sec) 【proxy】 mysql> select * from my_orders ; +------+-----------+-----------------------+------+------+-------+ | id | name | create_time | age | ttt | dc | +------+-----------+-----------------------+------+------+-------+ | 1 | ruiaylin | 2019-04-15 18:00:00.0 | 0 | NULL | NULL | | 2 | ruiaylin1 | 2019-04-16 18:00:00.0 | 15 | NULL | NULL | | 3 | ruiaylin1 | 2019-04-16 18:00:00.0 | 15 | NULL | 14.56 | | 4 | ruiaylin1 | 2019-04-16 18:00:00.0 | 0 | NULL | 14.56 | # age 0 +------+-----------+-----------------------+------+------+-------+ 4 rows in set (0.03 sec) 【mysql】 mysql> mysql> select * from my_orders_201904 ; +----+-----------+---------------------+------+------+-------+ | id | name | create_time | age | ttt | dc | +----+-----------+---------------------+------+------+-------+ | 1 | ruiaylin | 2019-04-15 18:00:00 | NULL | NULL | NULL | | 2 | ruiaylin1 | 2019-04-16 18:00:00 | 15 | NULL | NULL | | 3 | ruiaylin1 | 2019-04-16 18:00:00 | 15 | NULL | 14.56 | | 4 | ruiaylin1 | 2019-04-16 18:00:00 | NULL | NULL | 14.56 | # age NULL +----+-----------+---------------------+------+------+-------+ 4 rows in set (0.00 sec)
bfcbbeb0654ede68527ab51a1b71376c8c96e13e
f96642cde22a46d9cee2c1837b245614df25f53c
https://github.com/apache/shardingsphere/compare/bfcbbeb0654ede68527ab51a1b71376c8c96e13e...f96642cde22a46d9cee2c1837b245614df25f53c
diff --git a/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/MemoryQueryResult.java b/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/MemoryQueryResult.java index 52d81c6e2fe..1e79d31f888 100644 --- a/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/MemoryQueryResult.java +++ b/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/MemoryQueryResult.java @@ -68,7 +68,7 @@ public final class MemoryQueryResult implements QueryResult { while (resultSet.next()) { List<Object> rowData = new ArrayList<>(resultSet.getMetaData().getColumnCount()); for (int columnIndex = 1; columnIndex <= resultSet.getMetaData().getColumnCount(); columnIndex++) { - rowData.add(QueryResultUtil.getValueByColumnType(resultSet, columnIndex)); + rowData.add(QueryResultUtil.getValue(resultSet, columnIndex)); } result.add(new QueryRow(rowData)); } diff --git a/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultUtil.java b/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultUtil.java index 19dad89f35d..e41c8c2a35b 100644 --- a/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultUtil.java +++ b/sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultUtil.java @@ -29,6 +29,19 @@ import java.sql.Types; */ public class QueryResultUtil { + /** + * Get value. + * + * @param resultSet result set + * @param columnIndex column index of value + * @return {@code null} if the column is SQL {@code NULL}, otherwise the value of column + * @throws SQLException SQL exception + */ + public static Object getValue(final ResultSet resultSet, final int columnIndex) throws SQLException { + Object result = getValueByColumnType(resultSet, columnIndex); + return resultSet.wasNull() ? null : result; + } + /** * Get value by column type. * diff --git a/sharding-core/sharding-core-execute/src/test/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultUtilTest.java b/sharding-core/sharding-core-execute/src/test/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultUtilTest.java index 8f93501faec..89531decbcc 100644 --- a/sharding-core/sharding-core-execute/src/test/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultUtilTest.java +++ b/sharding-core/sharding-core-execute/src/test/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultUtilTest.java @@ -36,6 +36,7 @@ import java.sql.Timestamp; import java.sql.Types; import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; @@ -61,7 +62,7 @@ public class QueryResultUtilTest { public void assertGetValueByBit() { when(resultSetMetaData.getColumnType(1)).thenReturn(Types.BIT); when(resultSet.getBoolean(1)).thenReturn(true); - assertTrue((boolean) QueryResultUtil.getValueByColumnType(resultSet, 1)); + assertTrue((boolean) QueryResultUtil.getValue(resultSet, 1)); } @Test @@ -69,7 +70,7 @@ public class QueryResultUtilTest { public void assertGetValueByBoolean() { when(resultSetMetaData.getColumnType(1)).thenReturn(Types.BOOLEAN); when(resultSet.getBoolean(1)).thenReturn(true); - assertTrue((boolean) QueryResultUtil.getValueByColumnType(resultSet, 1)); + assertTrue((boolean) QueryResultUtil.getValue(resultSet, 1)); } @Test @@ -77,7 +78,7 @@ public class QueryResultUtilTest { public void assertGetValueByTinyint() { when(resultSetMetaData.getColumnType(1)).thenReturn(Types.TINYINT); when(resultSet.getByte(1)).thenReturn(Byte.MAX_VALUE); - assertThat((byte) QueryResultUtil.getValueByColumnType(resultSet, 1), is(Byte.MAX_VALUE)); + assertThat((byte) QueryResultUtil.getValue(resultSet, 1), is(Byte.MAX_VALUE)); } @Test @@ -85,7 +86,7 @@ public class QueryResultUtilTest { public void assertGetValueBySmallint() { when(resultSetMetaData.getColumnType(1)).thenReturn(Types.SMALLINT); when(resultSet.getShort(1)).thenReturn(Short.MAX_VALUE); - assertThat((short) QueryResultUtil.getValueByColumnType(resultSet, 1), is(Short.MAX_VALUE)); + assertThat((short) QueryResultUtil.getValue(resultSet, 1), is(Short.MAX_VALUE)); } @Test @@ -93,7 +94,7 @@ public class QueryResultUtilTest { public void assertGetValueByInteger() { when(resultSetMetaData.getColumnType(1)).thenReturn(Types.INTEGER); when(resultSet.getInt(1)).thenReturn(Integer.MAX_VALUE); - assertThat((int) QueryResultUtil.getValueByColumnType(resultSet, 1), is(Integer.MAX_VALUE)); + assertThat((int) QueryResultUtil.getValue(resultSet, 1), is(Integer.MAX_VALUE)); } @Test @@ -101,7 +102,7 @@ public class QueryResultUtilTest { public void assertGetValueByBigint() { when(resultSetMetaData.getColumnType(1)).thenReturn(Types.BIGINT); when(resultSet.getLong(1)).thenReturn(Long.MAX_VALUE); - assertThat((long) QueryResultUtil.getValueByColumnType(resultSet, 1), is(Long.MAX_VALUE)); + assertThat((long) QueryResultUtil.getValue(resultSet, 1), is(Long.MAX_VALUE)); } @Test @@ -109,7 +110,7 @@ public class QueryResultUtilTest { public void assertGetValueByNumeric() { when(resultSetMetaData.getColumnType(1)).thenReturn(Types.NUMERIC); when(resultSet.getBigDecimal(1)).thenReturn(BigDecimal.TEN); - assertThat((BigDecimal) QueryResultUtil.getValueByColumnType(resultSet, 1), is(BigDecimal.TEN)); + assertThat((BigDecimal) QueryResultUtil.getValue(resultSet, 1), is(BigDecimal.TEN)); } @Test @@ -117,7 +118,7 @@ public class QueryResultUtilTest { public void assertGetValueByDecimal() { when(resultSetMetaData.getColumnType(1)).thenReturn(Types.DECIMAL); when(resultSet.getBigDecimal(1)).thenReturn(BigDecimal.TEN); - assertThat((BigDecimal) QueryResultUtil.getValueByColumnType(resultSet, 1), is(BigDecimal.TEN)); + assertThat((BigDecimal) QueryResultUtil.getValue(resultSet, 1), is(BigDecimal.TEN)); } @Test @@ -125,7 +126,7 @@ public class QueryResultUtilTest { public void assertGetValueByFloat() { when(resultSetMetaData.getColumnType(1)).thenReturn(Types.FLOAT); when(resultSet.getDouble(1)).thenReturn(Double.MAX_VALUE); - assertThat((double) QueryResultUtil.getValueByColumnType(resultSet, 1), is(Double.MAX_VALUE)); + assertThat((double) QueryResultUtil.getValue(resultSet, 1), is(Double.MAX_VALUE)); } @Test @@ -133,7 +134,7 @@ public class QueryResultUtilTest { public void assertGetValueByDouble() { when(resultSetMetaData.getColumnType(1)).thenReturn(Types.DOUBLE); when(resultSet.getDouble(1)).thenReturn(Double.MAX_VALUE); - assertThat((double) QueryResultUtil.getValueByColumnType(resultSet, 1), is(Double.MAX_VALUE)); + assertThat((double) QueryResultUtil.getValue(resultSet, 1), is(Double.MAX_VALUE)); } @Test @@ -141,7 +142,7 @@ public class QueryResultUtilTest { public void assertGetValueByChar() { when(resultSetMetaData.getColumnType(1)).thenReturn(Types.CHAR); when(resultSet.getString(1)).thenReturn("x"); - assertThat((String) QueryResultUtil.getValueByColumnType(resultSet, 1), is("x")); + assertThat((String) QueryResultUtil.getValue(resultSet, 1), is("x")); } @Test @@ -149,7 +150,7 @@ public class QueryResultUtilTest { public void assertGetValueByVarchar() { when(resultSetMetaData.getColumnType(1)).thenReturn(Types.VARCHAR); when(resultSet.getString(1)).thenReturn("xxxxx"); - assertThat((String) QueryResultUtil.getValueByColumnType(resultSet, 1), is("xxxxx")); + assertThat((String) QueryResultUtil.getValue(resultSet, 1), is("xxxxx")); } @Test @@ -157,7 +158,7 @@ public class QueryResultUtilTest { public void assertGetValueByLongVarchar() { when(resultSetMetaData.getColumnType(1)).thenReturn(Types.LONGVARCHAR); when(resultSet.getString(1)).thenReturn("xxxxx"); - assertThat((String) QueryResultUtil.getValueByColumnType(resultSet, 1), is("xxxxx")); + assertThat((String) QueryResultUtil.getValue(resultSet, 1), is("xxxxx")); } @Test @@ -165,7 +166,7 @@ public class QueryResultUtilTest { public void assertGetValueByBinary() { when(resultSetMetaData.getColumnType(1)).thenReturn(Types.BINARY); when(resultSet.getBytes(1)).thenReturn("xxxxx".getBytes()); - assertThat((byte[]) QueryResultUtil.getValueByColumnType(resultSet, 1), is("xxxxx".getBytes())); + assertThat((byte[]) QueryResultUtil.getValue(resultSet, 1), is("xxxxx".getBytes())); } @Test @@ -173,7 +174,7 @@ public class QueryResultUtilTest { public void assertGetValueByVarBinary() { when(resultSetMetaData.getColumnType(1)).thenReturn(Types.VARBINARY); when(resultSet.getBytes(1)).thenReturn("xxxxx".getBytes()); - assertThat((byte[]) QueryResultUtil.getValueByColumnType(resultSet, 1), is("xxxxx".getBytes())); + assertThat((byte[]) QueryResultUtil.getValue(resultSet, 1), is("xxxxx".getBytes())); } @Test @@ -181,7 +182,7 @@ public class QueryResultUtilTest { public void assertGetValueByLongVarBinary() { when(resultSetMetaData.getColumnType(1)).thenReturn(Types.LONGVARBINARY); when(resultSet.getBytes(1)).thenReturn("xxxxx".getBytes()); - assertThat((byte[]) QueryResultUtil.getValueByColumnType(resultSet, 1), is("xxxxx".getBytes())); + assertThat((byte[]) QueryResultUtil.getValue(resultSet, 1), is("xxxxx".getBytes())); } @Test @@ -190,7 +191,7 @@ public class QueryResultUtilTest { long currentTime = System.currentTimeMillis(); when(resultSetMetaData.getColumnType(1)).thenReturn(Types.DATE); when(resultSet.getDate(1)).thenReturn(new Date(currentTime)); - assertThat((Date) QueryResultUtil.getValueByColumnType(resultSet, 1), is(new Date(currentTime))); + assertThat((Date) QueryResultUtil.getValue(resultSet, 1), is(new Date(currentTime))); } @Test @@ -199,7 +200,7 @@ public class QueryResultUtilTest { long currentTime = System.currentTimeMillis(); when(resultSetMetaData.getColumnType(1)).thenReturn(Types.TIME); when(resultSet.getTime(1)).thenReturn(new Time(currentTime)); - assertThat((Time) QueryResultUtil.getValueByColumnType(resultSet, 1), is(new Time(currentTime))); + assertThat((Time) QueryResultUtil.getValue(resultSet, 1), is(new Time(currentTime))); } @Test @@ -208,7 +209,7 @@ public class QueryResultUtilTest { long currentTime = System.currentTimeMillis(); when(resultSetMetaData.getColumnType(1)).thenReturn(Types.TIMESTAMP); when(resultSet.getTimestamp(1)).thenReturn(new Timestamp(currentTime)); - assertThat((Timestamp) QueryResultUtil.getValueByColumnType(resultSet, 1), is(new Timestamp(currentTime))); + assertThat((Timestamp) QueryResultUtil.getValue(resultSet, 1), is(new Timestamp(currentTime))); } @Test @@ -217,7 +218,7 @@ public class QueryResultUtilTest { Clob clob = mock(Clob.class); when(resultSetMetaData.getColumnType(1)).thenReturn(Types.CLOB); when(resultSet.getClob(1)).thenReturn(clob); - assertThat((Clob) QueryResultUtil.getValueByColumnType(resultSet, 1), is(clob)); + assertThat((Clob) QueryResultUtil.getValue(resultSet, 1), is(clob)); } @Test @@ -226,7 +227,7 @@ public class QueryResultUtilTest { Blob blob = mock(Blob.class); when(resultSetMetaData.getColumnType(1)).thenReturn(Types.BLOB); when(resultSet.getBlob(1)).thenReturn(blob); - assertThat((Blob) QueryResultUtil.getValueByColumnType(resultSet, 1), is(blob)); + assertThat((Blob) QueryResultUtil.getValue(resultSet, 1), is(blob)); } @Test @@ -235,6 +236,14 @@ public class QueryResultUtilTest { Object object = new Object(); when(resultSetMetaData.getColumnType(1)).thenReturn(Types.OTHER); when(resultSet.getObject(1)).thenReturn(object); - assertThat(QueryResultUtil.getValueByColumnType(resultSet, 1), is(object)); + assertThat(QueryResultUtil.getValue(resultSet, 1), is(object)); } + + @Test + @SneakyThrows + public void assertNullResultValue() { + when(resultSet.getObject(1)).thenReturn(null); + assertNull(QueryResultUtil.getValue(resultSet, 1)); + } + }
['sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/MemoryQueryResult.java', 'sharding-core/sharding-core-execute/src/main/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultUtil.java', 'sharding-core/sharding-core-execute/src/test/java/org/apache/shardingsphere/core/execute/sql/execute/result/QueryResultUtilTest.java']
{'.java': 3}
3
3
0
0
3
3,235,472
653,661
81,811
1,108
681
127
15
2
1,427
196
522
29
0
0
1970-01-01T00:25:56
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,527
apache/shardingsphere/1139/1057
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1057
https://github.com/apache/shardingsphere/pull/1139
https://github.com/apache/shardingsphere/pull/1139
1
fixes
Table name of no sharding is set low-case defaultly
### Which version of Sharding-Sphere do you using? 2.0.3 ### Expected behavior insert data correctly ### Actual behavior can't insert data, throw exception "Table 'test' doesn't exist" ### Reason analyze Database is case-sensitive and table name is in upper-case. a part of tables is sharing, and other part of tables is not sharding, when insert data into no sharding table, it throw exception "Table 'test' doesn't exist". The reason is that sharding-jdbc set table name low-case defaultly.
18fcde4ca1e52d13a4a2a7c55e894347de27dc67
e3d5cc886106bcca70e9763e8846e765635832e9
https://github.com/apache/shardingsphere/compare/18fcde4ca1e52d13a4a2a7c55e894347de27dc67...e3d5cc886106bcca70e9763e8846e765635832e9
diff --git a/sharding-core/src/main/java/io/shardingsphere/core/rule/ShardingRule.java b/sharding-core/src/main/java/io/shardingsphere/core/rule/ShardingRule.java index 1114f15583b..3ff955fccb9 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/rule/ShardingRule.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/rule/ShardingRule.java @@ -133,7 +133,7 @@ public final class ShardingRule { return tableRule.get(); } if (!Strings.isNullOrEmpty(shardingDataSourceNames.getDefaultDataSourceName())) { - return createTableRuleWithDefaultDataSource(logicTableName.toLowerCase()); + return createTableRuleWithDefaultDataSource(logicTableName); } throw new ShardingConfigurationException("Cannot find table rule and default data source with logic table: '%s'", logicTableName); }
['sharding-core/src/main/java/io/shardingsphere/core/rule/ShardingRule.java']
{'.java': 1}
1
1
0
0
1
2,263,124
470,701
63,556
809
161
25
2
1
506
77
117
12
0
0
1970-01-01T00:25:34
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,526
apache/shardingsphere/1148/1143
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1143
https://github.com/apache/shardingsphere/pull/1148
https://github.com/apache/shardingsphere/pull/1148
1
fixes
No result from SQL "SELECT COUNT(*) FROM t_order" in prepared statement
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-SNAPSHOT ### Which project do you using? Sharding-JDBC or Sharding-Proxy? Sharding-Proxy ### Expected behavior Return the row count of table `t_order`. ### Actual behavior No return result. ### Reason analyze Lost "Packet Number: 4". Packets in wireshark: Frame 2568: 94 bytes on wire (752 bits), 49 bytes captured (392 bits) on interface 0 Null/Loopback Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1 Transmission Control Protocol, Src Port: 3307, Dst Port: 54133, Seq: 1053, Ack: 1220, Len: 5 MySQL Protocol Packet Length: 1 Packet Number: 1 Number of fields: 1 Frame 2570: 168 bytes on wire (1344 bits), 86 bytes captured (688 bits) on interface 0 Null/Loopback Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1 Transmission Control Protocol, Src Port: 3307, Dst Port: 54133, Seq: 1058, Ack: 1220, Len: 42 MySQL Protocol Packet Length: 38 Packet Number: 2 Catalog: def Database: Table: Original table: Name: COUNT(*) Original name: COUNT(*) Charset number: utf8 COLLATE utf8_general_ci (33) Length: 21 Type: FIELD_TYPE_LONGLONG (8) Flags: 0x0000 Decimals: 0 Frame 2572: 102 bytes on wire (816 bits), 53 bytes captured (424 bits) on interface 0 Null/Loopback Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1 Transmission Control Protocol, Src Port: 3307, Dst Port: 54133, Seq: 1100, Ack: 1220, Len: 9 MySQL Protocol Packet Length: 5 Packet Number: 3 EOF marker: 254 Warnings: 0 Server Status: 0x0002 Frame 2574: 102 bytes on wire (816 bits), 53 bytes captured (424 bits) on interface 0 Null/Loopback Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1 Transmission Control Protocol, Src Port: 3307, Dst Port: 54133, Seq: 1109, Ack: 1220, Len: 9 MySQL Protocol Packet Length: 5 Packet Number: 5 EOF marker: 254 Warnings: 0 Server Status: 0x0002 ### Steps to reproduce the behavior Execute SQL "SELECT COUNT(*) FROM t_order" in prepared statement. ### For bug report, please *MUST* provide the reproduce example codes (such as a github link). Since it's straightforward to reproduce, you can add this SQL in the raw example.
97568b5db775e091fae6bbbb488c165eeb556065
17fc6da9a1c46af96e8e5b1270a8541b14cfbd0f
https://github.com/apache/shardingsphere/compare/97568b5db775e091fae6bbbb488c165eeb556065...17fc6da9a1c46af96e8e5b1270a8541b14cfbd0f
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 0bf8206c81b..4d21232c407 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 @@ -21,6 +21,7 @@ import io.shardingsphere.proxy.transport.mysql.constant.ColumnType; import io.shardingsphere.proxy.transport.mysql.packet.MySQLPacketPayload; import lombok.RequiredArgsConstructor; +import java.math.BigDecimal; import java.sql.Timestamp; import java.util.Date; @@ -107,7 +108,7 @@ public final class BinaryProtocolValue { payload.writeStringLenenc(binaryData.toString()); break; case MYSQL_TYPE_LONGLONG: - payload.writeInt8((Long) binaryData); + payload.writeInt8(((BigDecimal) binaryData).longValue()); break; case MYSQL_TYPE_LONG: case MYSQL_TYPE_INT24:
['sharding-proxy/src/main/java/io/shardingsphere/proxy/transport/mysql/packet/command/query/binary/execute/BinaryProtocolValue.java']
{'.java': 1}
1
1
0
0
1
2,256,773
469,460
63,326
805
159
28
3
1
2,453
347
764
77
0
0
1970-01-01T00:25:34
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,525
apache/shardingsphere/1161/1143
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1143
https://github.com/apache/shardingsphere/pull/1161
https://github.com/apache/shardingsphere/pull/1161
1
fixes
No result from SQL "SELECT COUNT(*) FROM t_order" in prepared statement
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-SNAPSHOT ### Which project do you using? Sharding-JDBC or Sharding-Proxy? Sharding-Proxy ### Expected behavior Return the row count of table `t_order`. ### Actual behavior No return result. ### Reason analyze Lost "Packet Number: 4". Packets in wireshark: Frame 2568: 94 bytes on wire (752 bits), 49 bytes captured (392 bits) on interface 0 Null/Loopback Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1 Transmission Control Protocol, Src Port: 3307, Dst Port: 54133, Seq: 1053, Ack: 1220, Len: 5 MySQL Protocol Packet Length: 1 Packet Number: 1 Number of fields: 1 Frame 2570: 168 bytes on wire (1344 bits), 86 bytes captured (688 bits) on interface 0 Null/Loopback Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1 Transmission Control Protocol, Src Port: 3307, Dst Port: 54133, Seq: 1058, Ack: 1220, Len: 42 MySQL Protocol Packet Length: 38 Packet Number: 2 Catalog: def Database: Table: Original table: Name: COUNT(*) Original name: COUNT(*) Charset number: utf8 COLLATE utf8_general_ci (33) Length: 21 Type: FIELD_TYPE_LONGLONG (8) Flags: 0x0000 Decimals: 0 Frame 2572: 102 bytes on wire (816 bits), 53 bytes captured (424 bits) on interface 0 Null/Loopback Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1 Transmission Control Protocol, Src Port: 3307, Dst Port: 54133, Seq: 1100, Ack: 1220, Len: 9 MySQL Protocol Packet Length: 5 Packet Number: 3 EOF marker: 254 Warnings: 0 Server Status: 0x0002 Frame 2574: 102 bytes on wire (816 bits), 53 bytes captured (424 bits) on interface 0 Null/Loopback Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1 Transmission Control Protocol, Src Port: 3307, Dst Port: 54133, Seq: 1109, Ack: 1220, Len: 9 MySQL Protocol Packet Length: 5 Packet Number: 5 EOF marker: 254 Warnings: 0 Server Status: 0x0002 ### Steps to reproduce the behavior Execute SQL "SELECT COUNT(*) FROM t_order" in prepared statement. ### For bug report, please *MUST* provide the reproduce example codes (such as a github link). Since it's straightforward to reproduce, you can add this SQL in the raw example.
3c35015feb7a6965e404a6a0f91203fb690473be
1c42231b63c01fe32d8d0ccb3102918e411481c3
https://github.com/apache/shardingsphere/compare/3c35015feb7a6965e404a6a0f91203fb690473be...1c42231b63c01fe32d8d0ccb3102918e411481c3
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 4d21232c407..6579c517db2 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 @@ -108,7 +108,11 @@ public final class BinaryProtocolValue { payload.writeStringLenenc(binaryData.toString()); break; case MYSQL_TYPE_LONGLONG: - payload.writeInt8(((BigDecimal) binaryData).longValue()); + if (binaryData instanceof BigDecimal) { + payload.writeInt8(((BigDecimal) binaryData).longValue()); + } else { + payload.writeInt8((Long) binaryData); + } break; case MYSQL_TYPE_LONG: case MYSQL_TYPE_INT24:
['sharding-proxy/src/main/java/io/shardingsphere/proxy/transport/mysql/packet/command/query/binary/execute/BinaryProtocolValue.java']
{'.java': 1}
1
1
0
0
1
2,258,310
469,766
63,362
804
314
51
6
1
2,453
347
764
77
0
0
1970-01-01T00:25:34
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,517
apache/shardingsphere/1353/1351
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1351
https://github.com/apache/shardingsphere/pull/1353
https://github.com/apache/shardingsphere/pull/1353
1
fixes
Parsing error from sql "SHOW FULL TABLES FROM `sharding_db` WHERE Table_type != 'VIEW'"
## 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: [Sharding-Sphere 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 Sharding-Sphere did you use? 3.0.0.M5-SNAPSHOT ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-Proxy ### Expected behavior "SHOW FULL TABLES FROM `sharding_db` WHERE Table_type != 'VIEW'" execute success ### Actual behavior execute failure: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Table_type != 'VIEW'' at line 1 ### Reason analyze (If you can) parsing error: Logic SQL: SHOW FULL TABLES FROM `sharding_db` WHERE Table_type != 'VIEW' Actual SQL: ds_0 ::: SHOW FULL TABLES Table_type != 'VIEW' ### 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).
837a2925a38a6784908f62ada033e7945fc0cf00
966c221ae670432cddf1fafbaa5cb80e16010c6e
https://github.com/apache/shardingsphere/compare/837a2925a38a6784908f62ada033e7945fc0cf00...966c221ae670432cddf1fafbaa5cb80e16010c6e
diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/dialect/mysql/sql/MySQLShowParser.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/dialect/mysql/sql/MySQLShowParser.java index 391a578e0b5..cc39eedae63 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/dialect/mysql/sql/MySQLShowParser.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/dialect/mysql/sql/MySQLShowParser.java @@ -108,7 +108,6 @@ public final class MySQLShowParser extends AbstractShowParser { if (lexerEngine.equalAny(DefaultKeyword.FROM, DefaultKeyword.IN)) { int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length(); lexerEngine.nextToken(); - lexerEngine.nextToken(); result.getSqlTokens().add(new RemoveToken(beginPosition, lexerEngine.getCurrentToken().getEndPosition())); } return result; diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/JDBCBackendHandler.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/JDBCBackendHandler.java index b1eb913eaa8..e62907a3fcc 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/JDBCBackendHandler.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/JDBCBackendHandler.java @@ -139,7 +139,10 @@ public final class JDBCBackendHandler extends AbstractBackendHandler { private void setResponseColumnLabelForShowTablesMergedResult(final QueryResponsePackets queryResponsePackets) { for (ColumnDefinition41Packet each : queryResponsePackets.getColumnDefinition41Packets()) { - each.setName("Tables_in_" + shardingSchema.getName()); + if (each.getName().startsWith("Tables_in_")) { + each.setName("Tables_in_" + shardingSchema.getName()); + break; + } } }
['sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/dialect/mysql/sql/MySQLShowParser.java', 'sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/jdbc/JDBCBackendHandler.java']
{'.java': 2}
2
2
0
0
2
2,236,797
466,313
62,563
793
275
49
6
2
1,434
200
335
32
2
0
1970-01-01T00:25:39
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,516
apache/shardingsphere/1369/1349
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1349
https://github.com/apache/shardingsphere/pull/1369
https://github.com/apache/shardingsphere/pull/1369
1
fixes
Registry can not watch changes from sharding proxy clients.
## 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: [Sharding-Sphere 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 Sharding-Sphere did you use? ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-Proxy ### Reason analyze (If you can) The registry can not watch changes from clients, if sharding proxy loads configurations from local. So it is necessary to modify some APIs of orchestration.
32d08cc13bd948d3f7d62186a78d76d4feed5c77
40d28cf217625c182d0a044b22798423353cca39
https://github.com/apache/shardingsphere/compare/32d08cc13bd948d3f7d62186a78d76d4feed5c77...40d28cf217625c182d0a044b22798423353cca39
diff --git a/sharding-jdbc/sharding-jdbc-orchestration/src/main/java/io/shardingsphere/shardingjdbc/orchestration/internal/datasource/OrchestrationMasterSlaveDataSource.java b/sharding-jdbc/sharding-jdbc-orchestration/src/main/java/io/shardingsphere/shardingjdbc/orchestration/internal/datasource/OrchestrationMasterSlaveDataSource.java index 7582b696e3f..e0e6b225af4 100644 --- a/sharding-jdbc/sharding-jdbc-orchestration/src/main/java/io/shardingsphere/shardingjdbc/orchestration/internal/datasource/OrchestrationMasterSlaveDataSource.java +++ b/sharding-jdbc/sharding-jdbc-orchestration/src/main/java/io/shardingsphere/shardingjdbc/orchestration/internal/datasource/OrchestrationMasterSlaveDataSource.java @@ -25,6 +25,7 @@ import io.shardingsphere.api.config.MasterSlaveRuleConfiguration; import io.shardingsphere.core.constant.properties.ShardingProperties; import io.shardingsphere.core.rule.MasterSlaveRule; import io.shardingsphere.orchestration.config.OrchestrationConfiguration; +import io.shardingsphere.orchestration.config.OrchestrationType; import io.shardingsphere.orchestration.internal.OrchestrationFacade; import io.shardingsphere.orchestration.internal.config.ConfigurationService; import io.shardingsphere.orchestration.internal.event.config.MasterSlaveConfigurationEventBusEvent; @@ -58,7 +59,7 @@ public class OrchestrationMasterSlaveDataSource extends AbstractOrchestrationDat Preconditions.checkState(null != masterSlaveRuleConfig && !Strings.isNullOrEmpty(masterSlaveRuleConfig.getMasterDataSourceName()), "No available master slave rule configuration to load."); dataSource = new MasterSlaveDataSource(configService.loadDataSourceMap(), new OrchestrationMasterSlaveRule(masterSlaveRuleConfig), configService.loadMasterSlaveConfigMap(), new ShardingProperties(configService.loadMasterSlaveProperties())); - initOrchestrationFacade(dataSource); + getOrchestrationFacade().init(OrchestrationType.MASTER_SLAVE); } private void initOrchestrationFacade(final MasterSlaveDataSource masterSlaveDataSource) { diff --git a/sharding-jdbc/sharding-jdbc-orchestration/src/main/java/io/shardingsphere/shardingjdbc/orchestration/internal/datasource/OrchestrationShardingDataSource.java b/sharding-jdbc/sharding-jdbc-orchestration/src/main/java/io/shardingsphere/shardingjdbc/orchestration/internal/datasource/OrchestrationShardingDataSource.java index c20bf3aa2e2..94ae1c3b659 100644 --- a/sharding-jdbc/sharding-jdbc-orchestration/src/main/java/io/shardingsphere/shardingjdbc/orchestration/internal/datasource/OrchestrationShardingDataSource.java +++ b/sharding-jdbc/sharding-jdbc-orchestration/src/main/java/io/shardingsphere/shardingjdbc/orchestration/internal/datasource/OrchestrationShardingDataSource.java @@ -22,6 +22,7 @@ import com.google.common.eventbus.Subscribe; import io.shardingsphere.api.ConfigMapContext; import io.shardingsphere.api.config.ShardingRuleConfiguration; import io.shardingsphere.orchestration.config.OrchestrationConfiguration; +import io.shardingsphere.orchestration.config.OrchestrationType; import io.shardingsphere.orchestration.internal.OrchestrationFacade; import io.shardingsphere.orchestration.internal.config.ConfigurationService; import io.shardingsphere.orchestration.internal.event.config.ShardingConfigurationEventBusEvent; @@ -56,7 +57,7 @@ public class OrchestrationShardingDataSource extends AbstractOrchestrationDataSo Preconditions.checkState(null != shardingRuleConfig && !shardingRuleConfig.getTableRuleConfigs().isEmpty(), "Missing the sharding rule configuration on register center"); dataSource = new ShardingDataSource(configService.loadDataSourceMap(), new OrchestrationShardingRule(shardingRuleConfig, configService.loadDataSourceMap().keySet()), configService.loadShardingConfigMap(), configService.loadShardingProperties()); - initOrchestrationFacade(dataSource); + getOrchestrationFacade().init(OrchestrationType.SHARDING); } private void initOrchestrationFacade(final ShardingDataSource shardingDataSource) { diff --git a/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/config/OrchestrationType.java b/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/config/OrchestrationType.java index 78b457f5921..367cf330a0f 100644 --- a/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/config/OrchestrationType.java +++ b/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/config/OrchestrationType.java @@ -25,5 +25,5 @@ package io.shardingsphere.orchestration.config; */ public enum OrchestrationType { - SHARDING, MASTER_SLAVE + SHARDING, MASTER_SLAVE, PROXY } diff --git a/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/OrchestrationFacade.java b/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/OrchestrationFacade.java index 5b4690e9af0..8c30ba08c91 100644 --- a/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/OrchestrationFacade.java +++ b/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/OrchestrationFacade.java @@ -24,6 +24,7 @@ import io.shardingsphere.core.rule.DataSourceParameter; import io.shardingsphere.core.yaml.YamlRuleConfiguration; import io.shardingsphere.core.yaml.other.YamlServerConfiguration; import io.shardingsphere.orchestration.config.OrchestrationConfiguration; +import io.shardingsphere.orchestration.config.OrchestrationType; import io.shardingsphere.orchestration.internal.config.ConfigurationService; import io.shardingsphere.orchestration.internal.listener.ListenerFactory; import io.shardingsphere.orchestration.internal.state.datasource.DataSourceService; @@ -137,6 +138,27 @@ public final class OrchestrationFacade implements AutoCloseable { listenerManager.initProxyListeners(); } + /** + * Initialize for proxy orchestration. + * + *@param orchestrationType orchestration type + */ + public void init(final OrchestrationType orchestrationType) { + switch (orchestrationType) { + case MASTER_SLAVE: + listenerManager.initMasterSlaveListeners(); + break; + case SHARDING: + listenerManager.initShardingListeners(); + break; + case PROXY: + listenerManager.initProxyListeners(); + break; + default: + throw new UnsupportedOperationException(orchestrationType.name()); + } + } + private void reviseShardingRuleConfigurationForMasterSlave(final Map<String, DataSource> dataSourceMap, final ShardingRuleConfiguration shardingRuleConfig) { for (Entry<String, DataSource> entry : dataSourceMap.entrySet()) { if (entry.getValue() instanceof MasterSlaveDataSource) { diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/Bootstrap.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/Bootstrap.java index 935e5577efb..4984905b5fa 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/Bootstrap.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/Bootstrap.java @@ -21,6 +21,7 @@ import io.shardingsphere.core.rule.DataSourceParameter; import io.shardingsphere.core.yaml.YamlRuleConfiguration; import io.shardingsphere.core.yaml.other.YamlServerConfiguration; import io.shardingsphere.opentracing.ShardingTracer; +import io.shardingsphere.orchestration.config.OrchestrationType; import io.shardingsphere.orchestration.internal.OrchestrationFacade; import io.shardingsphere.shardingproxy.config.ShardingConfiguration; import io.shardingsphere.shardingproxy.config.ShardingConfigurationLoader; @@ -87,10 +88,9 @@ public final class Bootstrap { private static void startWithRegistryCenter( final ProxyYamlServerConfiguration serverConfig, final Map<String, ProxyYamlRuleConfiguration> ruleConfigs, final int port) throws InterruptedException { + try (OrchestrationFacade orchestrationFacade = new OrchestrationFacade(serverConfig.getOrchestration().getOrchestrationConfiguration())) { - if (!ruleConfigs.isEmpty()) { - orchestrationFacade.init(getYamlServerConfiguration(serverConfig), getSchemaDataSourceMap(ruleConfigs), getRuleConfiguration(ruleConfigs)); - } + initOrchestrationFacade(serverConfig, ruleConfigs, orchestrationFacade); GlobalRegistry.getInstance().init(orchestrationFacade.getConfigService().loadYamlServerConfiguration(), orchestrationFacade.getConfigService().loadProxyDataSources(), orchestrationFacade.getConfigService().loadProxyConfiguration(), true); initOpenTracing(); @@ -98,6 +98,14 @@ public final class Bootstrap { } } + private static void initOrchestrationFacade(final ProxyYamlServerConfiguration serverConfig, final Map<String, ProxyYamlRuleConfiguration> ruleConfigs, final OrchestrationFacade orchestrationFacade) { + if (ruleConfigs.isEmpty()) { + orchestrationFacade.init(OrchestrationType.PROXY); + } else { + orchestrationFacade.init(getYamlServerConfiguration(serverConfig), getSchemaDataSourceMap(ruleConfigs), getRuleConfiguration(ruleConfigs)); + } + } + private static void initOpenTracing() { if (GlobalRegistry.getInstance().isOpenTracingEnable()) { ShardingTracer.init();
['sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/OrchestrationFacade.java', 'sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/config/OrchestrationType.java', 'sharding-jdbc/sharding-jdbc-orchestration/src/main/java/io/shardingsphere/shardingjdbc/orchestration/internal/datasource/OrchestrationShardingDataSource.java', 'sharding-jdbc/sharding-jdbc-orchestration/src/main/java/io/shardingsphere/shardingjdbc/orchestration/internal/datasource/OrchestrationMasterSlaveDataSource.java', 'sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/Bootstrap.java']
{'.java': 5}
5
5
0
0
5
2,055,925
429,256
57,222
741
2,055
398
44
5
925
121
204
24
2
0
1970-01-01T00:25:40
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,515
apache/shardingsphere/1377/1373
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1373
https://github.com/apache/shardingsphere/pull/1377
https://github.com/apache/shardingsphere/pull/1377
2
fixes
Mysql aurora version not supported
## Bug Report jdbcUrl = jdbc:mysql:aurora://host:3306/.. Then throws exception: "The URL of JDBC is not supported. Please refer to this pattern: jdbc:mysql://([\\w\\-\\.]+):?([0-9]*)/([\\w\\-]+);?\\S* " See: https://github.com/sharding-sphere/sharding-sphere/blob/dev/sharding-core/src/main/java/io/shardingsphere/core/metadata/datasource/dialect/MySQLDataSourceMetaData.java#L44
15615247de30e69461adba8caca9498a22f06151
ed4895486c9ed499df206edfbf6218d826548c6a
https://github.com/apache/shardingsphere/compare/15615247de30e69461adba8caca9498a22f06151...ed4895486c9ed499df206edfbf6218d826548c6a
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 f9a202c76c0..00a79826cc3 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,14 +41,14 @@ public final class MySQLDataSourceMetaData implements DataSourceMetaData { private final String schemeName; - private final Pattern pattern = Pattern.compile("jdbc:mysql://([\\\\w\\\\-\\\\.]+):?([0-9]*)/([\\\\w\\\\-]+);?\\\\S*", Pattern.CASE_INSENSITIVE); + private final Pattern pattern = Pattern.compile("jdbc:mysql:(\\\\w*:)?//([\\\\w\\\\-\\\\.]+):?([0-9]*)/([\\\\w\\\\-]+);?\\\\S*", Pattern.CASE_INSENSITIVE); public MySQLDataSourceMetaData(final String url) { Matcher matcher = pattern.matcher(url); if (matcher.find()) { - hostName = matcher.group(1); - port = Strings.isNullOrEmpty(matcher.group(2)) ? DEFAULT_PORT : Integer.valueOf(matcher.group(2)); - schemeName = matcher.group(3); + hostName = matcher.group(2); + port = Strings.isNullOrEmpty(matcher.group(3)) ? DEFAULT_PORT : Integer.valueOf(matcher.group(3)); + schemeName = matcher.group(4); } else { 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/MySQLDataSourceMetaData.java']
{'.java': 1}
1
1
0
0
1
2,056,782
429,438
57,241
741
681
177
8
1
382
25
109
7
1
0
1970-01-01T00:25:40
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,500
apache/shardingsphere/1895/1830
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1830
https://github.com/apache/shardingsphere/pull/1895
https://github.com/apache/shardingsphere/pull/1895
1
fixes
4.0.0.M1-SNAPSHOT report a error : current logic schema is null
The version using sharding-sphere is 4.0.0.M1-SNAPSHOT. I use sharding-Proxy. I configure a config-sharding file, there is no problem in querying data with java code, but I will get an error when connecting to the service with navicat. Unknown exception: current logic schema is null
4b1cc76450542840d42d076faae89458484ecee4
d06ae376c2e53001f41cfea603814939047e4e67
https://github.com/apache/shardingsphere/compare/4b1cc76450542840d42d076faae89458484ecee4...d06ae376c2e53001f41cfea603814939047e4e67
diff --git a/sharding-proxy/src/main/java/org/apache/shardingsphere/shardingproxy/backend/text/ComQueryBackendHandlerFactory.java b/sharding-proxy/src/main/java/org/apache/shardingsphere/shardingproxy/backend/text/ComQueryBackendHandlerFactory.java index 7d55f1389d0..f874705f857 100644 --- a/sharding-proxy/src/main/java/org/apache/shardingsphere/shardingproxy/backend/text/ComQueryBackendHandlerFactory.java +++ b/sharding-proxy/src/main/java/org/apache/shardingsphere/shardingproxy/backend/text/ComQueryBackendHandlerFactory.java @@ -39,6 +39,9 @@ import org.apache.shardingsphere.shardingproxy.backend.text.transaction.SkipBack import org.apache.shardingsphere.shardingproxy.backend.text.transaction.TransactionBackendHandler; import org.apache.shardingsphere.transaction.core.TransactionOperationType; +import java.util.Arrays; +import java.util.List; + /** * Com query backend handler factory. * @@ -53,9 +56,7 @@ public final class ComQueryBackendHandlerFactory { private static final String SET_AUTOCOMMIT_1 = "SET AUTOCOMMIT=1"; - private static final String GUI_SET_NAMES = "SET NAMES"; - - private static final String GUI_SHOW_VARIABLES = "SHOW VARIABLES LIKE"; + private static final List<String> GUI_SQL = Arrays.asList("SET NAMES", "SHOW VARIABLES LIKE", "SHOW CHARACTER SET", "SHOW COLLATION"); /** * Create new text protocol backend handler instance. @@ -81,10 +82,13 @@ public final class ComQueryBackendHandlerFactory { return SQLType.DAL == sqlStatement.getType() ? createDALBackendHandler(sqlStatement, sql, backendConnection) : new QueryBackendHandler(sql, backendConnection); } - private static TextProtocolBackendHandler createDALBackendHandler( - final SQLStatement sqlStatement, final String sql, final BackendConnection backendConnection) { - if (null == backendConnection.getLogicSchema() && (sql.toUpperCase().startsWith(GUI_SET_NAMES) || sql.toUpperCase().startsWith(GUI_SHOW_VARIABLES))) { - return new GUICompatibilityBackendHandler(); + private static TextProtocolBackendHandler createDALBackendHandler(final SQLStatement sqlStatement, final String sql, final BackendConnection backendConnection) { + if (null == backendConnection.getLogicSchema()) { + for (String each : GUI_SQL) { + if (sql.toUpperCase().startsWith(each)) { + return new GUICompatibilityBackendHandler(); + } + } } if (sqlStatement instanceof SetStatement) { return new BroadcastBackendHandler(sql, backendConnection);
['sharding-proxy/src/main/java/org/apache/shardingsphere/shardingproxy/backend/text/ComQueryBackendHandlerFactory.java']
{'.java': 1}
1
1
0
0
1
2,831,861
575,304
72,362
965
1,163
212
18
1
305
44
73
11
0
0
1970-01-01T00:25:50
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,544
apache/shardingsphere/329/328
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/328
https://github.com/apache/shardingsphere/pull/329
https://github.com/apache/shardingsphere/pull/329
1
fixes
ShardingConnection commit 时,持有的 Connection commit 异常时,后面的 Connection 无法提交
ShardingConnection 继承自 AbstractConnectionAdapter, commit 代码如下: ```Java // AbstractConnectionAdapter.java @Override public final void commit() throws SQLException { for (Connection each : getConnections()) { each.commit(); } } @Override public final void rollback() throws SQLException { Collection<SQLException> exceptions = new LinkedList<>(); for (Connection each : getConnections()) { try { each.rollback(); } catch (final SQLException ex) { exceptions.add(ex); } } throwSQLExceptionIfNecessary(exceptions); } ``` * 未对 `Connection#commit()` 异常进行捕获,导致异常时,后面的 Connection 无法提交 参考 `#rollback()` 方法修改如下: ``` Java @Override public final void commit() throws SQLException { Collection<SQLException> exceptions = new LinkedList<>(); for (Connection each : getConnections()) { try { each.commit(); } catch (final SQLException ex) { exceptions.add(ex); } } throwSQLExceptionIfNecessary(exceptions); } ``` 已经提交 pr。
c96a91e76cbce11bb24bbd5802cfb23c7ca3d95c
21c326939bce09f5d0ec73f45563e85807bf986a
https://github.com/apache/shardingsphere/compare/c96a91e76cbce11bb24bbd5802cfb23c7ca3d95c...21c326939bce09f5d0ec73f45563e85807bf986a
diff --git a/sharding-jdbc-core/src/main/java/com/dangdang/ddframe/rdb/sharding/jdbc/adapter/AbstractConnectionAdapter.java b/sharding-jdbc-core/src/main/java/com/dangdang/ddframe/rdb/sharding/jdbc/adapter/AbstractConnectionAdapter.java index e21c6fd1c3e..fc26e005572 100644 --- a/sharding-jdbc-core/src/main/java/com/dangdang/ddframe/rdb/sharding/jdbc/adapter/AbstractConnectionAdapter.java +++ b/sharding-jdbc-core/src/main/java/com/dangdang/ddframe/rdb/sharding/jdbc/adapter/AbstractConnectionAdapter.java @@ -63,9 +63,15 @@ public abstract class AbstractConnectionAdapter extends AbstractUnsupportedOpera @Override public final void commit() throws SQLException { + Collection<SQLException> exceptions = new LinkedList<>(); for (Connection each : getConnections()) { - each.commit(); + try { + each.commit(); + } catch (final SQLException ex) { + exceptions.add(ex); + } } + throwSQLExceptionIfNecessary(exceptions); } @Override
['sharding-jdbc-core/src/main/java/com/dangdang/ddframe/rdb/sharding/jdbc/adapter/AbstractConnectionAdapter.java']
{'.java': 1}
1
1
0
0
1
917,716
201,068
26,236
335
295
46
8
1
1,226
106
255
46
0
2
1970-01-01T00:25:02
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,501
apache/shardingsphere/1760/1754
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1754
https://github.com/apache/shardingsphere/pull/1760
https://github.com/apache/shardingsphere/pull/1760
1
fixes
can't get partition key value
## 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 ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-Proxy ### Expected behavior ps = connection.prepareStatement("select * from t_order where merc_no='1234567891' and tx_dt in ('20190102', '20190103') limit 0,10 "); 08:38:35.467 [main] INFO MyComplexKeysShardingAlgorithm - collection:["ds_0","ds_1","ds_2","ds_3"],shardingValues:[{"columnName":"merc_no","logicTableName":"t_order","values"**:[-1]**},{"columnName":"tx_dt","logicTableName":"t_order",**"values":[-1,-1]}**] t_order: databaseStrategy: complex: shardingColumns: merc_no, tx_dt algorithmClassName: MyComplexKeysShardingAlgorithm tableStrategy: inline: shardingColumn: tx_dt algorithmExpression: t_order_${tx_dt} ### Actual behavior ### 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).
66fb25b3cc7e760f9495cd19bb92c4dd3df4b9ca
316991ec0c1bd9369c9e7b23a62077d8f3e02453
https://github.com/apache/shardingsphere/compare/66fb25b3cc7e760f9495cd19bb92c4dd3df4b9ca...316991ec0c1bd9369c9e7b23a62077d8f3e02453
diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/antlr/sql/segment/expr/CommonExpressionSegment.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/antlr/sql/segment/expr/CommonExpressionSegment.java index d1e0e029c8f..13a4ed01a43 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/antlr/sql/segment/expr/CommonExpressionSegment.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/antlr/sql/segment/expr/CommonExpressionSegment.java @@ -37,5 +37,5 @@ public final class CommonExpressionSegment extends ExpressionWithAliasSegment { private int index = -1; - private Number value = -1; + private Number value; }
['sharding-core/src/main/java/io/shardingsphere/core/parsing/antlr/sql/segment/expr/CommonExpressionSegment.java']
{'.java': 1}
1
1
0
0
1
2,400,017
499,666
66,606
869
58
13
2
1
1,655
169
401
42
2
0
1970-01-01T00:25:47
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,513
apache/shardingsphere/1471/1415
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1415
https://github.com/apache/shardingsphere/pull/1471
https://github.com/apache/shardingsphere/pull/1471
1
fixes
mysql workbench cannot connect in 3.0.0
I config username and password and can connect in mysql wordbench in **3.0.0.M2**. But i cannot connect in **3.0.0**, return is _"Failed to Connect to MySQL at 127.0.0.1:3307 with user root Unknown database '`sharding_db`'"_
878ed163b080365ad7ff04f90a3ebdb6be92d0e0
6dd758a8ae218e49a6baffe2e2f4f198b113d6cc
https://github.com/apache/shardingsphere/compare/878ed163b080365ad7ff04f90a3ebdb6be92d0e0...6dd758a8ae218e49a6baffe2e2f4f198b113d6cc
diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/SchemaIgnoreBackendHandler.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/SchemaIgnoreBackendHandler.java index 3f70ebe653a..a5c52c37db4 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/SchemaIgnoreBackendHandler.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/SchemaIgnoreBackendHandler.java @@ -22,6 +22,7 @@ import io.shardingsphere.core.merger.dal.show.ShowDatabasesMergedResult; import io.shardingsphere.core.parsing.parser.dialect.mysql.statement.ShowDatabasesStatement; import io.shardingsphere.core.parsing.parser.dialect.mysql.statement.UseStatement; import io.shardingsphere.core.parsing.parser.sql.SQLStatement; +import io.shardingsphere.core.util.SQLUtil; import io.shardingsphere.shardingproxy.frontend.common.FrontendHandler; import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import io.shardingsphere.shardingproxy.transport.mysql.constant.ColumnType; @@ -90,7 +91,7 @@ public final class SchemaIgnoreBackendHandler implements BackendHandler { } private CommandResponsePackets handleUseStatement(final UseStatement useStatement, final FrontendHandler frontendHandler) { - String schema = useStatement.getSchema(); + String schema = SQLUtil.getExactlyValue(useStatement.getSchema()); if (!GLOBAL_REGISTRY.schemaExists(schema)) { return new CommandResponsePackets(new ErrPacket(1, ServerErrorCode.ER_BAD_DB_ERROR, schema)); }
['sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/SchemaIgnoreBackendHandler.java']
{'.java': 1}
1
1
0
0
1
2,246,716
469,274
62,158
833
171
34
3
1
231
34
69
6
0
0
1970-01-01T00:25:42
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,512
apache/shardingsphere/1488/1467
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1467
https://github.com/apache/shardingsphere/pull/1488
https://github.com/apache/shardingsphere/pull/1488
1
fixes
read-write splitting many thread
Read and write separation, no proper routing when multithreading version:3.0.0 Our requirement is to force the main library to be routed at the beginning of the "add", "create", "save", "insert", "update", "del" methods. In the process of using high-concurrency, the route is not correct。 Found in the middleware, found that the judgment route is a static variable, `private static boolean isMasterRouteOnly` 。 This static variable is shared by all threads. The a thread is not executed. The b thread modifies this value. Then, when routing, it uses this variable to judge the route, resulting in no correct route. sharding code ``` java @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class HintManagerHolder { public static final String DB_TABLE_NAME = "DB_TABLE_NAME"; public static final String DB_COLUMN_NAME = "DB_COLUMN_NAME"; private static final ThreadLocal<HintManager> HINT_MANAGER_HOLDER = new ThreadLocal<>(); private static final Multimap<String, Comparable<?>> DATABASE_SHARDING_VALUES = HashMultimap.create(); private static final Multimap<String, Comparable<?>> TABLE_SHARDING_VALUES = HashMultimap.create(); @Setter private static boolean databaseShardingOnly; @Setter private static boolean isMasterRouteOnly; ``` our code ``` java private static final ThreadLocal<Boolean> CUS_HINT_MANAGER_HOLDER = new ThreadLocal<>(); @Order(Ordered.HIGHEST_PRECEDENCE) @Around("execution(public * com.xhg..dao..*.*(..)) || execution(public * com.xhg..service.impl..*.*(..))") public Object hintMasterCalls(ProceedingJoinPoint jp) throws Throwable { String methodName = jp.getSignature().getName(); if (HintManagerHolder.isMasterRouteOnly() || HintManagerHolder.get() != null) { if (CUS_HINT_MANAGER_HOLDER.get() == null || !CUS_HINT_MANAGER_HOLDER.get()) { CUS_HINT_MANAGER_HOLDER.set(true); } return jp.proceed(); } if (CUS_HINT_MANAGER_HOLDER.get() == null || !CUS_HINT_MANAGER_HOLDER.get()) { String[] methodPreArr = {"add", "create", "save", "insert", "update", "del"}; for (String methodPre : methodPreArr) { if (methodName.startsWith(methodPre)) { CUS_HINT_MANAGER_HOLDER.set(true); break; } } } if (CUS_HINT_MANAGER_HOLDER.get() != null && CUS_HINT_MANAGER_HOLDER.get()) { HintManager hintManager = HintManager.getInstance(); hintManager.setMasterRouteOnly(); } return jp.proceed(); } ```
73a20b577a79bce969183026262bab033d13db0a
ed155384a86d74142accad8acc869c89896d7f3c
https://github.com/apache/shardingsphere/compare/73a20b577a79bce969183026262bab033d13db0a...ed155384a86d74142accad8acc869c89896d7f3c
diff --git a/sharding-core/src/main/java/io/shardingsphere/api/HintManager.java b/sharding-core/src/main/java/io/shardingsphere/api/HintManager.java index d060ef2db29..01c725f4c8d 100644 --- a/sharding-core/src/main/java/io/shardingsphere/api/HintManager.java +++ b/sharding-core/src/main/java/io/shardingsphere/api/HintManager.java @@ -17,8 +17,11 @@ package io.shardingsphere.api; +import com.google.common.collect.HashMultimap; +import com.google.common.collect.Multimap; import io.shardingsphere.core.hint.HintManagerHolder; import lombok.AccessLevel; +import lombok.Getter; import lombok.NoArgsConstructor; /** @@ -31,6 +34,18 @@ import lombok.NoArgsConstructor; @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class HintManager implements AutoCloseable { + @Getter + private final Multimap<String, Comparable<?>> databaseShardingValues = HashMultimap.create(); + + @Getter + private final Multimap<String, Comparable<?>> tableShardingValues = HashMultimap.create(); + + @Getter + private boolean databaseShardingOnly; + + @Getter + private boolean masterRouteOnly; + /** * Get a new instance for {@code HintManager}. * @@ -51,14 +66,16 @@ public final class HintManager implements AutoCloseable { * @param value sharding value */ public void setDatabaseShardingValue(final Comparable<?> value) { - HintManagerHolder.setDatabaseShardingValue(value); + databaseShardingValues.clear(); + addDatabaseShardingValue(HintManagerHolder.DB_TABLE_NAME, value); + databaseShardingOnly = true; } /** * Set CRUD operation force route to master database only. */ public void setMasterRouteOnly() { - HintManagerHolder.setMasterRouteOnly(true); + masterRouteOnly = true; } /** @@ -70,7 +87,8 @@ public final class HintManager implements AutoCloseable { * @param value sharding value */ public void addDatabaseShardingValue(final String logicTable, final Comparable<?> value) { - HintManagerHolder.addDatabaseShardingValue(logicTable, value); + databaseShardingValues.put(logicTable, value); + databaseShardingOnly = false; } /** @@ -82,7 +100,8 @@ public final class HintManager implements AutoCloseable { * @param value sharding value */ public void addTableShardingValue(final String logicTable, final Comparable<?> value) { - HintManagerHolder.addTableShardingValue(logicTable, value); + tableShardingValues.put(logicTable, value); + databaseShardingOnly = false; } @Override diff --git a/sharding-core/src/main/java/io/shardingsphere/core/hint/HintManagerHolder.java b/sharding-core/src/main/java/io/shardingsphere/core/hint/HintManagerHolder.java index 01af1ca25de..199a572d7c2 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/hint/HintManagerHolder.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/hint/HintManagerHolder.java @@ -19,14 +19,11 @@ package io.shardingsphere.core.hint; import com.google.common.base.Optional; import com.google.common.base.Preconditions; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Multimap; import io.shardingsphere.api.HintManager; import io.shardingsphere.api.algorithm.sharding.ListShardingValue; import io.shardingsphere.api.algorithm.sharding.ShardingValue; import lombok.AccessLevel; import lombok.NoArgsConstructor; -import lombok.Setter; import java.util.Collection; @@ -47,16 +44,6 @@ public final class HintManagerHolder { private static final ThreadLocal<HintManager> HINT_MANAGER_HOLDER = new ThreadLocal<>(); - private static final Multimap<String, Comparable<?>> DATABASE_SHARDING_VALUES = HashMultimap.create(); - - private static final Multimap<String, Comparable<?>> TABLE_SHARDING_VALUES = HashMultimap.create(); - - @Setter - private static boolean databaseShardingOnly; - - @Setter - private static boolean isMasterRouteOnly; - /** * Set hint manager. * @@ -67,53 +54,13 @@ public final class HintManagerHolder { HINT_MANAGER_HOLDER.set(hintManager); } - /** - * Add sharding value for one certain sharding database. - * - * <p>The sharding operator is {@code =}</p> - * When you need to assign the values to one certain sharding database, use this method to add sharding value for this database. - * - * @param value sharding value - */ - public static void setDatabaseShardingValue(final Comparable<?> value) { - DATABASE_SHARDING_VALUES.clear(); - addDatabaseShardingValue(DB_TABLE_NAME, value); - databaseShardingOnly = true; - } - - /** - * Add sharding value for database. - * - * <p>The sharding operator is {@code =}</p> - * - * @param logicTable logic table name - * @param value sharding value - */ - public static void addDatabaseShardingValue(final String logicTable, final Comparable<?> value) { - DATABASE_SHARDING_VALUES.put(logicTable, value); - databaseShardingOnly = false; - } - - /** - * Add sharding value for table. - * - * <p>The sharding operator is {@code =}</p> - * - * @param logicTable logic table name - * @param value sharding value - */ - public static void addTableShardingValue(final String logicTable, final Comparable<?> value) { - TABLE_SHARDING_VALUES.put(logicTable, value); - databaseShardingOnly = false; - } - /** * Judge whether only database is sharding. * * @return database sharding or not */ public static boolean isDatabaseShardingOnly() { - return null != HINT_MANAGER_HOLDER.get() && databaseShardingOnly; + return null != HINT_MANAGER_HOLDER.get() && HINT_MANAGER_HOLDER.get().isDatabaseShardingOnly(); } /** @@ -122,7 +69,7 @@ public final class HintManagerHolder { * @return is force route to master database only or not */ public static boolean isMasterRouteOnly() { - return null != HINT_MANAGER_HOLDER.get() && isMasterRouteOnly; + return null != HINT_MANAGER_HOLDER.get() && HINT_MANAGER_HOLDER.get().isMasterRouteOnly(); } /** @@ -132,10 +79,10 @@ public final class HintManagerHolder { * @return database sharding value */ public static Optional<ShardingValue> getDatabaseShardingValue(final String logicTable) { - if (null == HINT_MANAGER_HOLDER.get() || !DATABASE_SHARDING_VALUES.containsKey(logicTable)) { + if (null == HINT_MANAGER_HOLDER.get() || !HINT_MANAGER_HOLDER.get().getDatabaseShardingValues().containsKey(logicTable)) { return Optional.absent(); } - return Optional.of(getShardingValue(logicTable, DATABASE_SHARDING_VALUES.get(logicTable))); + return Optional.of(getShardingValue(logicTable, HINT_MANAGER_HOLDER.get().getDatabaseShardingValues().get(logicTable))); } /** @@ -145,10 +92,10 @@ public final class HintManagerHolder { * @return table sharding value */ public static Optional<ShardingValue> getTableShardingValue(final String logicTable) { - if (null == HINT_MANAGER_HOLDER.get() || !TABLE_SHARDING_VALUES.containsKey(logicTable)) { + if (null == HINT_MANAGER_HOLDER.get() || !HINT_MANAGER_HOLDER.get().getTableShardingValues().containsKey(logicTable)) { return Optional.absent(); } - return Optional.of(getShardingValue(logicTable, TABLE_SHARDING_VALUES.get(logicTable))); + return Optional.of(getShardingValue(logicTable, HINT_MANAGER_HOLDER.get().getTableShardingValues().get(logicTable))); } @SuppressWarnings("unchecked") @@ -171,9 +118,5 @@ public final class HintManagerHolder { */ public static void clear() { HINT_MANAGER_HOLDER.remove(); - DATABASE_SHARDING_VALUES.clear(); - TABLE_SHARDING_VALUES.clear(); - databaseShardingOnly = false; - isMasterRouteOnly = false; } } diff --git a/sharding-core/src/test/java/io/shardingsphere/core/hint/HintManagerHolderTest.java b/sharding-core/src/test/java/io/shardingsphere/core/hint/HintManagerHolderTest.java index e6927db6c9b..7b22d770d25 100644 --- a/sharding-core/src/test/java/io/shardingsphere/core/hint/HintManagerHolderTest.java +++ b/sharding-core/src/test/java/io/shardingsphere/core/hint/HintManagerHolderTest.java @@ -66,6 +66,12 @@ public final class HintManagerHolderTest { hintManager.close(); assertFalse(HintManagerHolder.isMasterRouteOnly()); } + + @Test + public void assertIsDatabaseShardingOnly() { + hintManager.setDatabaseShardingValue("1"); + assertTrue(HintManagerHolder.isDatabaseShardingOnly()); + } @Test public void assertIsDatabaseShardingOnlyWithoutSet() { @@ -77,6 +83,8 @@ public final class HintManagerHolderTest { public void assertIsMasterRouteOnly() { hintManager.setMasterRouteOnly(); assertTrue(HintManagerHolder.isMasterRouteOnly()); + hintManager.close(); + assertFalse(HintManagerHolder.isMasterRouteOnly()); } @Test
['sharding-core/src/test/java/io/shardingsphere/core/hint/HintManagerHolderTest.java', 'sharding-core/src/main/java/io/shardingsphere/core/hint/HintManagerHolder.java', 'sharding-core/src/main/java/io/shardingsphere/api/HintManager.java']
{'.java': 3}
3
3
0
0
3
2,271,506
474,365
62,906
840
4,356
960
96
2
2,730
256
587
68
0
2
1970-01-01T00:25:42
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,518
apache/shardingsphere/1341/1340
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1340
https://github.com/apache/shardingsphere/pull/1341
https://github.com/apache/shardingsphere/pull/1341
1
fixes
Proxy gets NULL Pointer exception when disable datasource from registry.
## 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: [Sharding-Sphere 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 Sharding-Sphere did you use? 3.0.0.M5 ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-Proxy ### The problem is: If we have no disabled datasource in registry, the proxy will renew the datasource map, but will get null exception.
90b411eee57fd7370f2a6072150c921861234d21
086431405f8a4083c77cfce188b1e556075577c4
https://github.com/apache/shardingsphere/compare/90b411eee57fd7370f2a6072150c921861234d21...086431405f8a4083c77cfce188b1e556075577c4
diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java index c2f905f8b79..aade829a5dc 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java @@ -36,6 +36,7 @@ import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; +import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -196,7 +197,15 @@ public final class GlobalRegistry { @Subscribe public void renewDisabledDataSourceNames(final ProxyDisabledStateEventBusEvent disabledStateEventBusEvent) { for (Entry<String, ShardingSchema> entry : shardingSchemas.entrySet()) { - entry.getValue().getBackendDataSource().setAvailableDataSources(disabledStateEventBusEvent.getDisabledSchemaDataSourceMap().get(entry.getKey())); + entry.getValue().getBackendDataSource().setAvailableDataSources(getDisabledDataSourceNames(disabledStateEventBusEvent.getDisabledSchemaDataSourceMap(), entry.getKey())); } } + + private Collection<String> getDisabledDataSourceNames(final Map<String, Collection<String>> disabledSchemaDataSourceMap, final String shardingSchemaName) { + Collection<String> result = new LinkedList<>(); + if (disabledSchemaDataSourceMap.containsKey(shardingSchemaName)) { + result.addAll(disabledSchemaDataSourceMap.get(shardingSchemaName)); + } + return result; + } }
['sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/GlobalRegistry.java']
{'.java': 1}
1
1
0
0
1
2,231,928
465,317
62,513
793
794
139
11
1
876
115
201
21
2
0
1970-01-01T00:25:39
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,510
apache/shardingsphere/1588/1533
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1533
https://github.com/apache/shardingsphere/pull/1588
https://github.com/apache/shardingsphere/pull/1588
1
fixes
The result of `getBytes` is wrong.
## Bug Report ### Which version of Sharding-Sphere did you use? 3.0.0 ### Which project did you use? Sharding-JDBC or Sharding-Proxy? Sharding-Proxy ### Expected behavior The result of bytes should be: [88, -99, -9, 80, 65, -64, 65, -70, -83, -98, 49, 15, -115, -103, 13, 116] ### Actual behavior The result change every time: [91, 66, 64, 49, 50, 57, 52, 99, 50, 51, 52] [91, 66, 64, 55, 50, 101, 49, 56, 57, 100, 54] [91, 66, 64, 52, 54, 55, 54, 98, 48, 53, 56] [91, 66, 64, 51, 48, 52, 51, 98, 49, 99, 99] [91, 66, 64, 49, 97, 99, 102, 97, 99, 53, 56] ### Reason analyze (If you can) ### Steps to reproduce the behavior, such as: SQL to execute, sharding rule configuration, when exception occur etc. ```sql CREATE TABLE `binary_test` ( `id` binary(16) NOT NULL ) ENGINE=InnoDB; insert into binary_test (id) value (0x589df75041c041baad9e310f8d990d74); ``` ### Example codes for reproduce this issue (such as a github link). ```java Connection connection = ds.getConnection(); PreparedStatement ps = connection.prepareStatement("SELECT * FROM binary_test"); ps.execute(); ResultSet rs = ps.getResultSet(); rs.next(); byte[] result = rs.getBytes("id"); System.out.println(Arrays.toString(result)); ```
2da4913fc627d38da54ed3cc46d15a87179dab28
938442f3eb38e00b93f67d091b0e9e7dd132e952
https://github.com/apache/shardingsphere/compare/2da4913fc627d38da54ed3cc46d15a87179dab28...938442f3eb38e00b93f67d091b0e9e7dd132e952
diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/constant/ColumnType.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/constant/ColumnType.java index e65b43894bc..fdd19647ffd 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/constant/ColumnType.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/constant/ColumnType.java @@ -116,9 +116,9 @@ public enum ColumnType { JDBC_TYPE_AND_COLUMN_TYPE_MAP.put(Types.DATE, MYSQL_TYPE_DATE); JDBC_TYPE_AND_COLUMN_TYPE_MAP.put(Types.TIME, MYSQL_TYPE_TIME); JDBC_TYPE_AND_COLUMN_TYPE_MAP.put(Types.TIMESTAMP, MYSQL_TYPE_TIMESTAMP); - JDBC_TYPE_AND_COLUMN_TYPE_MAP.put(Types.BINARY, MYSQL_TYPE_BLOB); - JDBC_TYPE_AND_COLUMN_TYPE_MAP.put(Types.VARBINARY, MYSQL_TYPE_MEDIUM_BLOB); - JDBC_TYPE_AND_COLUMN_TYPE_MAP.put(Types.LONGVARBINARY, MYSQL_TYPE_LONG_BLOB); + JDBC_TYPE_AND_COLUMN_TYPE_MAP.put(Types.BINARY, MYSQL_TYPE_VARCHAR); + JDBC_TYPE_AND_COLUMN_TYPE_MAP.put(Types.VARBINARY, MYSQL_TYPE_VARCHAR); + JDBC_TYPE_AND_COLUMN_TYPE_MAP.put(Types.LONGVARBINARY, MYSQL_TYPE_VARCHAR); JDBC_TYPE_AND_COLUMN_TYPE_MAP.put(Types.NULL, MYSQL_TYPE_NULL); JDBC_TYPE_AND_COLUMN_TYPE_MAP.put(Types.BLOB, MYSQL_TYPE_BLOB); } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/MySQLPacketPayload.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/MySQLPacketPayload.java index 717b08945c9..5d5f79d0318 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/MySQLPacketPayload.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/MySQLPacketPayload.java @@ -266,6 +266,20 @@ public final class MySQLPacketPayload implements AutoCloseable { byteBuf.writeBytes(value.getBytes()); } + /** + * Write lenenc bytes to byte buffers. + * + * @param value fixed length bytes + */ + public void writeBytesLenenc(final byte[] value) { + if (0 == value.length) { + byteBuf.writeByte(0); + return; + } + writeIntLenenc(value.length); + byteBuf.writeBytes(value); + } + /** * Read fixed length string from byte buffers. * diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/protocol/StringLenencBinaryProtocolValue.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/protocol/StringLenencBinaryProtocolValue.java index fdb23893c11..15119066d81 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/protocol/StringLenencBinaryProtocolValue.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/protocol/StringLenencBinaryProtocolValue.java @@ -34,6 +34,10 @@ public final class StringLenencBinaryProtocolValue implements BinaryProtocolValu @Override public void write(final MySQLPacketPayload payload, final Object value) { - payload.writeStringLenenc(value.toString()); + if (value instanceof byte[]) { + payload.writeBytesLenenc((byte[]) value); + } else { + payload.writeStringLenenc(value.toString()); + } } } diff --git a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/text/TextResultSetRowPacket.java b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/text/TextResultSetRowPacket.java index cfe1df2aba7..11accce219a 100644 --- a/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/text/TextResultSetRowPacket.java +++ b/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/text/TextResultSetRowPacket.java @@ -56,7 +56,11 @@ public final class TextResultSetRowPacket implements MySQLPacket { if (null == each) { payload.writeInt1(NULL); } else { - payload.writeStringLenenc(each.toString()); + if (each instanceof byte[]) { + payload.writeBytesLenenc((byte[]) each); + } else { + payload.writeStringLenenc(each.toString()); + } } } } diff --git a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/constant/ColumnTypeTest.java b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/constant/ColumnTypeTest.java index 3b19a49ccf2..a13dfad5e6f 100644 --- a/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/constant/ColumnTypeTest.java +++ b/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/constant/ColumnTypeTest.java @@ -44,9 +44,9 @@ public final class ColumnTypeTest { assertThat(ColumnType.valueOfJDBCType(Types.DATE), is(ColumnType.MYSQL_TYPE_DATE)); assertThat(ColumnType.valueOfJDBCType(Types.TIME), is(ColumnType.MYSQL_TYPE_TIME)); assertThat(ColumnType.valueOfJDBCType(Types.TIMESTAMP), is(ColumnType.MYSQL_TYPE_TIMESTAMP)); - assertThat(ColumnType.valueOfJDBCType(Types.BINARY), is(ColumnType.MYSQL_TYPE_BLOB)); - assertThat(ColumnType.valueOfJDBCType(Types.VARBINARY), is(ColumnType.MYSQL_TYPE_MEDIUM_BLOB)); - assertThat(ColumnType.valueOfJDBCType(Types.LONGVARBINARY), is(ColumnType.MYSQL_TYPE_LONG_BLOB)); + assertThat(ColumnType.valueOfJDBCType(Types.BINARY), is(ColumnType.MYSQL_TYPE_VARCHAR)); + assertThat(ColumnType.valueOfJDBCType(Types.VARBINARY), is(ColumnType.MYSQL_TYPE_VARCHAR)); + assertThat(ColumnType.valueOfJDBCType(Types.LONGVARBINARY), is(ColumnType.MYSQL_TYPE_VARCHAR)); assertThat(ColumnType.valueOfJDBCType(Types.NULL), is(ColumnType.MYSQL_TYPE_NULL)); assertThat(ColumnType.valueOfJDBCType(Types.BLOB), is(ColumnType.MYSQL_TYPE_BLOB)); }
['sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/transport/mysql/constant/ColumnTypeTest.java', 'sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/binary/execute/protocol/StringLenencBinaryProtocolValue.java', 'sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/MySQLPacketPayload.java', 'sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/packet/command/query/text/TextResultSetRowPacket.java', 'sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/transport/mysql/constant/ColumnType.java']
{'.java': 5}
5
5
0
0
5
2,424,645
507,120
67,201
907
1,358
279
32
4
1,320
188
443
47
0
2
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,545
apache/shardingsphere/325/322
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/322
https://github.com/apache/shardingsphere/pull/325
https://github.com/apache/shardingsphere/pull/325
1
fixes
可执行jar发布,用YamlShardingDataSource时报错
Please answer these questions before submitting your issue. Thanks! ### Which version of Sharding-Jdbc do you using? 1.5.0.M3 ### Expected behavior 我用可执行jar的方式发布,用YamlShardingDataSource生成datasource ### Actual behavior 报错: class path resource [xx.yml] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/xx.jar!/BOOT-INF/classes!/xx.yml ### Steps to reproduce the behavior YamlShardingDataSource的入参是java.io.File。我用可执行jar的方式发布,获取不到File,但是可以获取到InputStream,原因见: https://stackoverflow.com/questions/25869428/classpath-resource-not-found-when-running-as-jar 希望能提供java.io.Inputsream的入参而不仅仅是java.io.File入参 ### Please provide the reproduce example codes (such as github link) if possible.
d6ac50704f5e45beeeded09a4f0b160c7320b993
3a00d604ae798e295c6077d7fbf874448a44c8c4
https://github.com/apache/shardingsphere/compare/d6ac50704f5e45beeeded09a4f0b160c7320b993...3a00d604ae798e295c6077d7fbf874448a44c8c4
diff --git a/sharding-jdbc-config-parent/sharding-jdbc-config-yaml/src/main/java/com/dangdang/ddframe/rdb/sharding/config/yaml/api/YamlShardingDataSource.java b/sharding-jdbc-config-parent/sharding-jdbc-config-yaml/src/main/java/com/dangdang/ddframe/rdb/sharding/config/yaml/api/YamlShardingDataSource.java index e35f97388d8..55ac5ef49f4 100644 --- a/sharding-jdbc-config-parent/sharding-jdbc-config-yaml/src/main/java/com/dangdang/ddframe/rdb/sharding/config/yaml/api/YamlShardingDataSource.java +++ b/sharding-jdbc-config-parent/sharding-jdbc-config-yaml/src/main/java/com/dangdang/ddframe/rdb/sharding/config/yaml/api/YamlShardingDataSource.java @@ -27,7 +27,7 @@ import javax.sql.DataSource; import java.io.File; import java.io.FileInputStream; import java.io.IOException; -import java.io.InputStreamReader; +import java.io.InputStream; import java.util.Map; /** @@ -36,21 +36,28 @@ import java.util.Map; * @author gaohongtao */ public class YamlShardingDataSource extends ShardingDataSource { - + public YamlShardingDataSource(final File yamlFile) throws IOException { super(new ShardingRuleBuilder(yamlFile.getName(), unmarshal(yamlFile)).build(), unmarshal(yamlFile).getProps()); } - + public YamlShardingDataSource(final Map<String, DataSource> dataSource, final File yamlFile) throws IOException { super(new ShardingRuleBuilder(yamlFile.getName(), dataSource, unmarshal(yamlFile)).build(), unmarshal(yamlFile).getProps()); } - + + public YamlShardingDataSource(String logroot, final InputStream inputStream) throws IOException { + super(new ShardingRuleBuilder(logroot, unmarshal(inputStream)).build(), unmarshal(inputStream).getProps()); + } + private static YamlConfig unmarshal(final File yamlFile) throws IOException { try ( FileInputStream fileInputStream = new FileInputStream(yamlFile); - InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8") ) { - return new Yaml(new Constructor(YamlConfig.class)).loadAs(inputStreamReader, YamlConfig.class); + return unmarshal(fileInputStream); } } + + private static YamlConfig unmarshal(final InputStream inputStream) throws IOException { + return new Yaml(new Constructor(YamlConfig.class)).loadAs(inputStream, YamlConfig.class); + } }
['sharding-jdbc-config-parent/sharding-jdbc-config-yaml/src/main/java/com/dangdang/ddframe/rdb/sharding/config/yaml/api/YamlShardingDataSource.java']
{'.java': 1}
1
1
0
0
1
867,590
189,477
24,878
310
777
141
19
1
746
69
211
17
1
0
1970-01-01T00:25:02
18,658
Java
{'Java': 22772685, 'ANTLR': 1011078, 'FreeMarker': 120878, 'Shell': 14522, 'Dockerfile': 13922, 'Batchfile': 3214}
Apache License 2.0
3,528
apache/shardingsphere/1056/1055
apache
shardingsphere
https://github.com/apache/shardingsphere/issues/1055
https://github.com/apache/shardingsphere/pull/1056
https://github.com/apache/shardingsphere/pull/1056
1
fixes
Throw NullPointerException in InsertColumnsClauseParser.
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.M2 ### Expected behavior If there is no table to be queried, ss should give information that this logic table does not exist. ### Actual behavior If there is no table to be queried, ss throw NullPointerException. ### Reason analyze If there is no table to be queried, ss will get null by shardingMetaData.getTableMetaDataMap().get(tableName). ### Steps to reproduce the behavior insert into ttttt values(1,2); (ttttt does not exist in database.) ### For bug report, please *MUST* provide the reproduce example codes (such as a github link).
3c166002e0eb5985ebadd63ee8cad8e7f6a584df
8de048297db9eb16f2ea4f5674f51612684421eb
https://github.com/apache/shardingsphere/compare/3c166002e0eb5985ebadd63ee8cad8e7f6a584df...8de048297db9eb16f2ea4f5674f51612684421eb
diff --git a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/InsertColumnsClauseParser.java b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/InsertColumnsClauseParser.java index e285218ff1c..4a300b38567 100644 --- a/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/InsertColumnsClauseParser.java +++ b/sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/InsertColumnsClauseParser.java @@ -43,6 +43,7 @@ import java.util.LinkedList; * * @author zhangliang * @author maxiaoguang + * @author panjuan */ public final class InsertColumnsClauseParser implements SQLClauseParser { @@ -92,7 +93,7 @@ public final class InsertColumnsClauseParser implements SQLClauseParser { insertStatement.setColumnsListLastPosition(lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length()); lexerEngine.nextToken(); } else { - Collection<String> columnNames = shardingMetaData.getTableMetaDataMap().get(tableName).getAllColumnNames(); + Collection<String> columnNames = shardingMetaData.getTableMetaDataMap().containsKey(tableName) ? shardingMetaData.getTableMetaDataMap().get(tableName).getAllColumnNames() : new LinkedList<String>(); int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length() - 1; insertStatement.getSqlTokens().add(new InsertColumnToken(beginPosition, "(")); ItemsToken columnsToken = new ItemsToken(beginPosition); 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 b2832f9c86b..fbb78f48acf 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 @@ -102,6 +102,8 @@ public final class MySQLFrontendHandler extends FrontendHandler { } } catch (final SQLException ex) { context.writeAndFlush(new ErrPacket(++currentSequenceId, ex)); + } catch (final Exception ex) { + context.writeAndFlush(new ErrPacket(1, ServerErrorCode.ER_STD_UNKNOWN_EXCEPTION, ex.getMessage())); } }
['sharding-proxy/src/main/java/io/shardingsphere/proxy/frontend/mysql/MySQLFrontendHandler.java', 'sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/clause/InsertColumnsClauseParser.java']
{'.java': 2}
2
2
0
0
2
2,179,328
453,634
61,439
773
512
96
5
2
744
113
165
16
0
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