code
stringlengths 227
324k
| indentifier
stringlengths 171
323k
| lang
stringclasses 2
values |
|---|---|---|
published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.InetAddress; import java.net.MulticastSocket; import java.net.SocketException; import java.nio.channels.DatagramChannel; import static org.testng.Assert.assertThrows; /* * @test * @bug 8236105 8240533 * @summary Check that DatagramSocket throws expected * Exception when sending a DatagramPacket with port 0 * @run testng/othervm SendPortZero */ public class SendPortZero { private InetAddress loopbackAddr, wildcardAddr; private DatagramSocket datagramSocket, datagramSocketAdaptor; private DatagramPacket loopbackZeroPkt, wildcardZeroPkt, wildcardValidPkt; private static final Class<SocketException> SE = SocketException.class; @BeforeTest public void setUp() throws IOException { datagramSocket = new DatagramSocket(); datagramSocketAdaptor = DatagramChannel.open().socket(); byte[] buf = "test".getBytes(); // Addresses loopbackAddr = InetAddress.getLoopbackAddress(); wildcardAddr = new InetSocketAddress(0).getAddress(); // Packets // loopback w/port 0 loopbackZeroPkt = new DatagramPacket(buf, 0, buf. <mask> <mask> <mask> ); loopbackZeroPkt.setAddress(loopbackAddr); loopbackZeroPkt.setPort(0); // wildcard w/port 0 wildcardZeroPkt = new DatagramPacket(buf, 0, buf. <mask> <mask> <mask> ); wildcardZeroPkt.setAddress(wildcardAddr); wildcardZeroPkt.setPort(0); // wildcard addr w/valid port // Not currently tested. See JDK-8236807 wildcardValidPkt = new DatagramPacket(buf, 0, buf. <mask> <mask> <mask> ); wildcardValidPkt.setAddress(wildcardAddr); wildcardValidPkt.setPort(datagramSocket.getLocalPort()); } @DataProvider(name = "data") public Object[][] variants() { return new Object[][]{ { datagramSocket, loopbackZeroPkt }, { datagramSocket, wildcardZeroPkt }, // Re-enable when JDK-8236807 fixed //{ datagramSocket, wildcardValidPkt }, { datagramSocketAdaptor, loopbackZeroPkt }, { datagramSocketAdaptor, wildcardZeroPkt }, // Re-enable when JDK-8236807 fixed //{ datagramSocketAdaptor, wildcardValidPkt }, }; } @Test(dataProvider = "data") public void testSend(DatagramSocket ds, DatagramPacket pkt) { assertThrows(SE, () -> ds.send(pkt)); } @AfterTest public void tearDown() { datagramSocket.close(); datagramSocketAdaptor.close(); } }
|
published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.InetAddress; import java.net.MulticastSocket; import java.net.SocketException; import java.nio.channels.DatagramChannel; import static org.testng.Assert.assertThrows; /* * @test * @bug 8236105 8240533 * @summary Check that DatagramSocket throws expected * Exception when sending a DatagramPacket with port 0 * @run testng/othervm SendPortZero */ public class SendPortZero { private InetAddress loopbackAddr, wildcardAddr; private DatagramSocket datagramSocket, datagramSocketAdaptor; private DatagramPacket loopbackZeroPkt, wildcardZeroPkt, wildcardValidPkt; private static final Class<SocketException> SE = SocketException.class; @BeforeTest public void setUp() throws IOException { datagramSocket = new DatagramSocket(); datagramSocketAdaptor = DatagramChannel.open().socket(); byte[] buf = "test".getBytes(); // Addresses loopbackAddr = InetAddress.getLoopbackAddress(); wildcardAddr = new InetSocketAddress(0).getAddress(); // Packets // loopback w/port 0 loopbackZeroPkt = new DatagramPacket(buf, 0, buf. length ); loopbackZeroPkt.setAddress(loopbackAddr); loopbackZeroPkt.setPort(0); // wildcard w/port 0 wildcardZeroPkt = new DatagramPacket(buf, 0, buf. length ); wildcardZeroPkt.setAddress(wildcardAddr); wildcardZeroPkt.setPort(0); // wildcard addr w/valid port // Not currently tested. See JDK-8236807 wildcardValidPkt = new DatagramPacket(buf, 0, buf. length ); wildcardValidPkt.setAddress(wildcardAddr); wildcardValidPkt.setPort(datagramSocket.getLocalPort()); } @DataProvider(name = "data") public Object[][] variants() { return new Object[][]{ { datagramSocket, loopbackZeroPkt }, { datagramSocket, wildcardZeroPkt }, // Re-enable when JDK-8236807 fixed //{ datagramSocket, wildcardValidPkt }, { datagramSocketAdaptor, loopbackZeroPkt }, { datagramSocketAdaptor, wildcardZeroPkt }, // Re-enable when JDK-8236807 fixed //{ datagramSocketAdaptor, wildcardValidPkt }, }; } @Test(dataProvider = "data") public void testSend(DatagramSocket ds, DatagramPacket pkt) { assertThrows(SE, () -> ds.send(pkt)); } @AfterTest public void tearDown() { datagramSocket.close(); datagramSocketAdaptor.close(); } }
|
java
|
hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.InetAddress; import java.net.MulticastSocket; import java.net.SocketException; import java.nio.channels.DatagramChannel; import static org.testng.Assert.assertThrows; /* * @test * @bug 8236105 8240533 * @summary Check that DatagramSocket throws expected * Exception when sending a DatagramPacket with port 0 * @run testng/othervm SendPortZero */ public class SendPortZero { private InetAddress loopbackAddr, wildcardAddr; private DatagramSocket datagramSocket, datagramSocketAdaptor; private DatagramPacket loopbackZeroPkt, wildcardZeroPkt, wildcardValidPkt; private static final Class<SocketException> SE = SocketException.class; @BeforeTest public void setUp() throws IOException { datagramSocket = new DatagramSocket(); datagramSocketAdaptor = DatagramChannel.open().socket(); byte[] buf = "test".getBytes(); // Addresses loopbackAddr = InetAddress.getLoopbackAddress(); wildcardAddr = new InetSocketAddress(0).getAddress(); // Packets // loopback w/port 0 loopbackZeroPkt = new DatagramPacket(buf, 0, buf. <mask> <mask> <mask> ); loopbackZeroPkt.setAddress(loopbackAddr); loopbackZeroPkt.setPort(0); // wildcard w/port 0 wildcardZeroPkt = new DatagramPacket(buf, 0, buf. <mask> <mask> <mask> ); wildcardZeroPkt.setAddress(wildcardAddr); wildcardZeroPkt.setPort(0); // wildcard addr w/valid port // Not currently tested. See JDK-8236807 wildcardValidPkt = new DatagramPacket(buf, 0, buf. <mask> <mask> <mask> ); wildcardValidPkt.setAddress(wildcardAddr); wildcardValidPkt.setPort(datagramSocket.getLocalPort()); } @DataProvider(name = "data") public Object[][] variants() { return new Object[][]{ { datagramSocket, loopbackZeroPkt }, { datagramSocket, wildcardZeroPkt }, // Re-enable when JDK-8236807 fixed //{ datagramSocket, wildcardValidPkt }, { datagramSocketAdaptor, loopbackZeroPkt }, { datagramSocketAdaptor, wildcardZeroPkt }, // Re-enable when JDK-8236807 fixed //{ datagramSocketAdaptor, wildcardValidPkt }, }; } @Test(dataProvider = "data") public void testSend(DatagramSocket ds, DatagramPacket pkt) { assertThrows(SE, () -> ds.send(pkt)); } @AfterTest public void tearDown() { datagramSocket.close(); datagramSocketAdaptor.close(); } }
|
hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.InetAddress; import java.net.MulticastSocket; import java.net.SocketException; import java.nio.channels.DatagramChannel; import static org.testng.Assert.assertThrows; /* * @test * @bug 8236105 8240533 * @summary Check that DatagramSocket throws expected * Exception when sending a DatagramPacket with port 0 * @run testng/othervm SendPortZero */ public class SendPortZero { private InetAddress loopbackAddr, wildcardAddr; private DatagramSocket datagramSocket, datagramSocketAdaptor; private DatagramPacket loopbackZeroPkt, wildcardZeroPkt, wildcardValidPkt; private static final Class<SocketException> SE = SocketException.class; @BeforeTest public void setUp() throws IOException { datagramSocket = new DatagramSocket(); datagramSocketAdaptor = DatagramChannel.open().socket(); byte[] buf = "test".getBytes(); // Addresses loopbackAddr = InetAddress.getLoopbackAddress(); wildcardAddr = new InetSocketAddress(0).getAddress(); // Packets // loopback w/port 0 loopbackZeroPkt = new DatagramPacket(buf, 0, buf. length ); loopbackZeroPkt.setAddress(loopbackAddr); loopbackZeroPkt.setPort(0); // wildcard w/port 0 wildcardZeroPkt = new DatagramPacket(buf, 0, buf. length ); wildcardZeroPkt.setAddress(wildcardAddr); wildcardZeroPkt.setPort(0); // wildcard addr w/valid port // Not currently tested. See JDK-8236807 wildcardValidPkt = new DatagramPacket(buf, 0, buf. length ); wildcardValidPkt.setAddress(wildcardAddr); wildcardValidPkt.setPort(datagramSocket.getLocalPort()); } @DataProvider(name = "data") public Object[][] variants() { return new Object[][]{ { datagramSocket, loopbackZeroPkt }, { datagramSocket, wildcardZeroPkt }, // Re-enable when JDK-8236807 fixed //{ datagramSocket, wildcardValidPkt }, { datagramSocketAdaptor, loopbackZeroPkt }, { datagramSocketAdaptor, wildcardZeroPkt }, // Re-enable when JDK-8236807 fixed //{ datagramSocketAdaptor, wildcardValidPkt }, }; } @Test(dataProvider = "data") public void testSend(DatagramSocket ds, DatagramPacket pkt) { assertThrows(SE, () -> ds.send(pkt)); } @AfterTest public void tearDown() { datagramSocket.close(); datagramSocketAdaptor.close(); } }
|
java
|
FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.InetAddress; import java.net.MulticastSocket; import java.net.SocketException; import java.nio.channels.DatagramChannel; import static org.testng.Assert.assertThrows; /* * @test * @bug 8236105 8240533 * @summary Check that DatagramSocket throws expected * Exception when sending a DatagramPacket with port 0 * @run testng/othervm SendPortZero */ public class SendPortZero { private InetAddress loopbackAddr, wildcardAddr; private DatagramSocket datagramSocket, datagramSocketAdaptor; private DatagramPacket loopbackZeroPkt, wildcardZeroPkt, wildcardValidPkt; private static final Class<SocketException> SE = SocketException.class; @BeforeTest public void setUp() throws IOException { datagramSocket = new DatagramSocket(); datagramSocketAdaptor = DatagramChannel.open().socket(); byte[] buf = "test".getBytes(); // Addresses loopbackAddr = InetAddress.getLoopbackAddress(); wildcardAddr = new InetSocketAddress(0).getAddress(); // Packets // loopback w/port 0 loopbackZeroPkt = new DatagramPacket(buf, 0, buf. <mask> <mask> <mask> ); loopbackZeroPkt.setAddress(loopbackAddr); loopbackZeroPkt.setPort(0); // wildcard w/port 0 wildcardZeroPkt = new DatagramPacket(buf, 0, buf. <mask> <mask> <mask> ); wildcardZeroPkt.setAddress(wildcardAddr); wildcardZeroPkt.setPort(0); // wildcard addr w/valid port // Not currently tested. See JDK-8236807 wildcardValidPkt = new DatagramPacket(buf, 0, buf. <mask> <mask> <mask> ); wildcardValidPkt.setAddress(wildcardAddr); wildcardValidPkt.setPort(datagramSocket.getLocalPort()); } @DataProvider(name = "data") public Object[][] variants() { return new Object[][]{ { datagramSocket, loopbackZeroPkt }, { datagramSocket, wildcardZeroPkt }, // Re-enable when JDK-8236807 fixed //{ datagramSocket, wildcardValidPkt }, { datagramSocketAdaptor, loopbackZeroPkt }, { datagramSocketAdaptor, wildcardZeroPkt }, // Re-enable when JDK-8236807 fixed //{ datagramSocketAdaptor, wildcardValidPkt }, }; } @Test(dataProvider = "data") public void testSend(DatagramSocket ds, DatagramPacket pkt) { assertThrows(SE, () -> ds.send(pkt)); } @AfterTest public void tearDown() { datagramSocket.close(); datagramSocketAdaptor.close(); } }
|
FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.InetAddress; import java.net.MulticastSocket; import java.net.SocketException; import java.nio.channels.DatagramChannel; import static org.testng.Assert.assertThrows; /* * @test * @bug 8236105 8240533 * @summary Check that DatagramSocket throws expected * Exception when sending a DatagramPacket with port 0 * @run testng/othervm SendPortZero */ public class SendPortZero { private InetAddress loopbackAddr, wildcardAddr; private DatagramSocket datagramSocket, datagramSocketAdaptor; private DatagramPacket loopbackZeroPkt, wildcardZeroPkt, wildcardValidPkt; private static final Class<SocketException> SE = SocketException.class; @BeforeTest public void setUp() throws IOException { datagramSocket = new DatagramSocket(); datagramSocketAdaptor = DatagramChannel.open().socket(); byte[] buf = "test".getBytes(); // Addresses loopbackAddr = InetAddress.getLoopbackAddress(); wildcardAddr = new InetSocketAddress(0).getAddress(); // Packets // loopback w/port 0 loopbackZeroPkt = new DatagramPacket(buf, 0, buf. length ); loopbackZeroPkt.setAddress(loopbackAddr); loopbackZeroPkt.setPort(0); // wildcard w/port 0 wildcardZeroPkt = new DatagramPacket(buf, 0, buf. length ); wildcardZeroPkt.setAddress(wildcardAddr); wildcardZeroPkt.setPort(0); // wildcard addr w/valid port // Not currently tested. See JDK-8236807 wildcardValidPkt = new DatagramPacket(buf, 0, buf. length ); wildcardValidPkt.setAddress(wildcardAddr); wildcardValidPkt.setPort(datagramSocket.getLocalPort()); } @DataProvider(name = "data") public Object[][] variants() { return new Object[][]{ { datagramSocket, loopbackZeroPkt }, { datagramSocket, wildcardZeroPkt }, // Re-enable when JDK-8236807 fixed //{ datagramSocket, wildcardValidPkt }, { datagramSocketAdaptor, loopbackZeroPkt }, { datagramSocketAdaptor, wildcardZeroPkt }, // Re-enable when JDK-8236807 fixed //{ datagramSocketAdaptor, wildcardValidPkt }, }; } @Test(dataProvider = "data") public void testSend(DatagramSocket ds, DatagramPacket pkt) { assertThrows(SE, () -> ds.send(pkt)); } @AfterTest public void tearDown() { datagramSocket.close(); datagramSocketAdaptor.close(); } }
|
java
|
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.server.share.context; import org.apache.kafka.common.TopicIdPartition; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.Uuid; import org.apache.kafka.common.message.ShareFetchResponseData; import org.apache.kafka.common.message.ShareFetchResponseData.PartitionData; import org.apache.kafka.common.protocol.Errors; import org.apache.kafka.common.requests.ShareFetchRequest; import org.apache.kafka.common.requests.ShareFetchRequest.SharePartitionData; import org.apache.kafka.common.requests.ShareFetchResponse; import org.apache.kafka.common.requests.ShareRequestMetadata; import org.apache.kafka.server.share.CachedSharePartition; import org.apache.kafka.server.share.ErroneousAndValidPartitionData; import org.apache.kafka.server.share.session.ShareSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; /** * The context for a share session fetch request. */ public class ShareSessionContext extends ShareFetchContext { private static final Logger log = LoggerFactory.getLogger(ShareSessionContext.class); private final ShareRequestMetadata reqMetadata; private final boolean <mask> <mask> <mask> <mask> <mask> ; private Map<TopicIdPartition, SharePartitionData> shareFetchData; private ShareSession session; /** * The share fetch context for the first request that starts a share session. * * @param reqMetadata The request metadata. * @param shareFetchData The share partition data from the share fetch request. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData) { this.reqMetadata = reqMetadata; this.shareFetchData = shareFetchData; this. <mask> <mask> <mask> <mask> <mask> = false; } /** * The share fetch context for a subsequent request that utilizes an existing share session. * * @param reqMetadata The request metadata. * @param session The subsequent fetch request session. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, ShareSession session) { this.reqMetadata = reqMetadata; this.session = session; this. <mask> <mask> <mask> <mask> <mask> = true; } // Visible for testing public Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData() { return shareFetchData; } // Visible for testing public boolean <mask> <mask> <mask> <mask> <mask> () { return <mask> <mask> <mask> <mask> <mask> ; } // Visible for testing public ShareSession session() { return session; } @Override boolean isTraceEnabled() { return log.isTraceEnabled(); } @Override public ShareFetchResponse throttleResponse(int throttleTimeMs) { if (! <mask> <mask> <mask> <mask> <mask> ) { return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); int sessionEpoch; synchronized (session) { sessionEpoch = session.epoch; } if (sessionEpoch != expectedEpoch) { log.debug("Subsequent share session {} expected epoch {}, but got {}. " + "Possible duplicate request.", session.key(), expectedEpoch, sessionEpoch); return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.INVALID_SHARE_SESSION_EPOCH, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } /** * Iterator that goes over the given partition map and selects partitions that need to be included in the response. * If updateShareContextAndRemoveUnselected is set to true, the
|
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.server.share.context; import org.apache.kafka.common.TopicIdPartition; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.Uuid; import org.apache.kafka.common.message.ShareFetchResponseData; import org.apache.kafka.common.message.ShareFetchResponseData.PartitionData; import org.apache.kafka.common.protocol.Errors; import org.apache.kafka.common.requests.ShareFetchRequest; import org.apache.kafka.common.requests.ShareFetchRequest.SharePartitionData; import org.apache.kafka.common.requests.ShareFetchResponse; import org.apache.kafka.common.requests.ShareRequestMetadata; import org.apache.kafka.server.share.CachedSharePartition; import org.apache.kafka.server.share.ErroneousAndValidPartitionData; import org.apache.kafka.server.share.session.ShareSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; /** * The context for a share session fetch request. */ public class ShareSessionContext extends ShareFetchContext { private static final Logger log = LoggerFactory.getLogger(ShareSessionContext.class); private final ShareRequestMetadata reqMetadata; private final boolean isSubsequent ; private Map<TopicIdPartition, SharePartitionData> shareFetchData; private ShareSession session; /** * The share fetch context for the first request that starts a share session. * * @param reqMetadata The request metadata. * @param shareFetchData The share partition data from the share fetch request. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData) { this.reqMetadata = reqMetadata; this.shareFetchData = shareFetchData; this. isSubsequent = false; } /** * The share fetch context for a subsequent request that utilizes an existing share session. * * @param reqMetadata The request metadata. * @param session The subsequent fetch request session. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, ShareSession session) { this.reqMetadata = reqMetadata; this.session = session; this. isSubsequent = true; } // Visible for testing public Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData() { return shareFetchData; } // Visible for testing public boolean isSubsequent () { return isSubsequent ; } // Visible for testing public ShareSession session() { return session; } @Override boolean isTraceEnabled() { return log.isTraceEnabled(); } @Override public ShareFetchResponse throttleResponse(int throttleTimeMs) { if (! isSubsequent ) { return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); int sessionEpoch; synchronized (session) { sessionEpoch = session.epoch; } if (sessionEpoch != expectedEpoch) { log.debug("Subsequent share session {} expected epoch {}, but got {}. " + "Possible duplicate request.", session.key(), expectedEpoch, sessionEpoch); return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.INVALID_SHARE_SESSION_EPOCH, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } /** * Iterator that goes over the given partition map and selects partitions that need to be included in the response. * If updateShareContextAndRemoveUnselected is set to true, the
|
java
|
* contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.server.share.context; import org.apache.kafka.common.TopicIdPartition; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.Uuid; import org.apache.kafka.common.message.ShareFetchResponseData; import org.apache.kafka.common.message.ShareFetchResponseData.PartitionData; import org.apache.kafka.common.protocol.Errors; import org.apache.kafka.common.requests.ShareFetchRequest; import org.apache.kafka.common.requests.ShareFetchRequest.SharePartitionData; import org.apache.kafka.common.requests.ShareFetchResponse; import org.apache.kafka.common.requests.ShareRequestMetadata; import org.apache.kafka.server.share.CachedSharePartition; import org.apache.kafka.server.share.ErroneousAndValidPartitionData; import org.apache.kafka.server.share.session.ShareSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; /** * The context for a share session fetch request. */ public class ShareSessionContext extends ShareFetchContext { private static final Logger log = LoggerFactory.getLogger(ShareSessionContext.class); private final ShareRequestMetadata reqMetadata; private final boolean <mask> <mask> <mask> <mask> <mask> ; private Map<TopicIdPartition, SharePartitionData> shareFetchData; private ShareSession session; /** * The share fetch context for the first request that starts a share session. * * @param reqMetadata The request metadata. * @param shareFetchData The share partition data from the share fetch request. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData) { this.reqMetadata = reqMetadata; this.shareFetchData = shareFetchData; this. <mask> <mask> <mask> <mask> <mask> = false; } /** * The share fetch context for a subsequent request that utilizes an existing share session. * * @param reqMetadata The request metadata. * @param session The subsequent fetch request session. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, ShareSession session) { this.reqMetadata = reqMetadata; this.session = session; this. <mask> <mask> <mask> <mask> <mask> = true; } // Visible for testing public Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData() { return shareFetchData; } // Visible for testing public boolean <mask> <mask> <mask> <mask> <mask> () { return <mask> <mask> <mask> <mask> <mask> ; } // Visible for testing public ShareSession session() { return session; } @Override boolean isTraceEnabled() { return log.isTraceEnabled(); } @Override public ShareFetchResponse throttleResponse(int throttleTimeMs) { if (! <mask> <mask> <mask> <mask> <mask> ) { return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); int sessionEpoch; synchronized (session) { sessionEpoch = session.epoch; } if (sessionEpoch != expectedEpoch) { log.debug("Subsequent share session {} expected epoch {}, but got {}. " + "Possible duplicate request.", session.key(), expectedEpoch, sessionEpoch); return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.INVALID_SHARE_SESSION_EPOCH, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } /** * Iterator that goes over the given partition map and selects partitions that need to be included in the response. * If updateShareContextAndRemoveUnselected is set to true, the share context will be updated for the selected * partitions and also remove unselected ones as they are encountered. */ private class PartitionIterator implements Iterator<Entry<TopicIdPartition, PartitionData>> { private final Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator; private final boolean updateShareContextAndRemoveUnselected; private Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> nextElement; public PartitionIterator(Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator, boolean updateShareContextAndRemoveUnselected) { this.iterator = iterator; this.updateShareContextAndRemoveUnselected = updateShareContextAndRemoveUnselected; } @Override public boolean hasNext()
|
* contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.server.share.context; import org.apache.kafka.common.TopicIdPartition; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.Uuid; import org.apache.kafka.common.message.ShareFetchResponseData; import org.apache.kafka.common.message.ShareFetchResponseData.PartitionData; import org.apache.kafka.common.protocol.Errors; import org.apache.kafka.common.requests.ShareFetchRequest; import org.apache.kafka.common.requests.ShareFetchRequest.SharePartitionData; import org.apache.kafka.common.requests.ShareFetchResponse; import org.apache.kafka.common.requests.ShareRequestMetadata; import org.apache.kafka.server.share.CachedSharePartition; import org.apache.kafka.server.share.ErroneousAndValidPartitionData; import org.apache.kafka.server.share.session.ShareSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; /** * The context for a share session fetch request. */ public class ShareSessionContext extends ShareFetchContext { private static final Logger log = LoggerFactory.getLogger(ShareSessionContext.class); private final ShareRequestMetadata reqMetadata; private final boolean isSubsequent ; private Map<TopicIdPartition, SharePartitionData> shareFetchData; private ShareSession session; /** * The share fetch context for the first request that starts a share session. * * @param reqMetadata The request metadata. * @param shareFetchData The share partition data from the share fetch request. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData) { this.reqMetadata = reqMetadata; this.shareFetchData = shareFetchData; this. isSubsequent = false; } /** * The share fetch context for a subsequent request that utilizes an existing share session. * * @param reqMetadata The request metadata. * @param session The subsequent fetch request session. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, ShareSession session) { this.reqMetadata = reqMetadata; this.session = session; this. isSubsequent = true; } // Visible for testing public Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData() { return shareFetchData; } // Visible for testing public boolean isSubsequent () { return isSubsequent ; } // Visible for testing public ShareSession session() { return session; } @Override boolean isTraceEnabled() { return log.isTraceEnabled(); } @Override public ShareFetchResponse throttleResponse(int throttleTimeMs) { if (! isSubsequent ) { return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); int sessionEpoch; synchronized (session) { sessionEpoch = session.epoch; } if (sessionEpoch != expectedEpoch) { log.debug("Subsequent share session {} expected epoch {}, but got {}. " + "Possible duplicate request.", session.key(), expectedEpoch, sessionEpoch); return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.INVALID_SHARE_SESSION_EPOCH, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } /** * Iterator that goes over the given partition map and selects partitions that need to be included in the response. * If updateShareContextAndRemoveUnselected is set to true, the share context will be updated for the selected * partitions and also remove unselected ones as they are encountered. */ private class PartitionIterator implements Iterator<Entry<TopicIdPartition, PartitionData>> { private final Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator; private final boolean updateShareContextAndRemoveUnselected; private Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> nextElement; public PartitionIterator(Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator, boolean updateShareContextAndRemoveUnselected) { this.iterator = iterator; this.updateShareContextAndRemoveUnselected = updateShareContextAndRemoveUnselected; } @Override public boolean hasNext()
|
java
|
You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.server.share.context; import org.apache.kafka.common.TopicIdPartition; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.Uuid; import org.apache.kafka.common.message.ShareFetchResponseData; import org.apache.kafka.common.message.ShareFetchResponseData.PartitionData; import org.apache.kafka.common.protocol.Errors; import org.apache.kafka.common.requests.ShareFetchRequest; import org.apache.kafka.common.requests.ShareFetchRequest.SharePartitionData; import org.apache.kafka.common.requests.ShareFetchResponse; import org.apache.kafka.common.requests.ShareRequestMetadata; import org.apache.kafka.server.share.CachedSharePartition; import org.apache.kafka.server.share.ErroneousAndValidPartitionData; import org.apache.kafka.server.share.session.ShareSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; /** * The context for a share session fetch request. */ public class ShareSessionContext extends ShareFetchContext { private static final Logger log = LoggerFactory.getLogger(ShareSessionContext.class); private final ShareRequestMetadata reqMetadata; private final boolean <mask> <mask> <mask> <mask> <mask> ; private Map<TopicIdPartition, SharePartitionData> shareFetchData; private ShareSession session; /** * The share fetch context for the first request that starts a share session. * * @param reqMetadata The request metadata. * @param shareFetchData The share partition data from the share fetch request. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData) { this.reqMetadata = reqMetadata; this.shareFetchData = shareFetchData; this. <mask> <mask> <mask> <mask> <mask> = false; } /** * The share fetch context for a subsequent request that utilizes an existing share session. * * @param reqMetadata The request metadata. * @param session The subsequent fetch request session. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, ShareSession session) { this.reqMetadata = reqMetadata; this.session = session; this. <mask> <mask> <mask> <mask> <mask> = true; } // Visible for testing public Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData() { return shareFetchData; } // Visible for testing public boolean <mask> <mask> <mask> <mask> <mask> () { return <mask> <mask> <mask> <mask> <mask> ; } // Visible for testing public ShareSession session() { return session; } @Override boolean isTraceEnabled() { return log.isTraceEnabled(); } @Override public ShareFetchResponse throttleResponse(int throttleTimeMs) { if (! <mask> <mask> <mask> <mask> <mask> ) { return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); int sessionEpoch; synchronized (session) { sessionEpoch = session.epoch; } if (sessionEpoch != expectedEpoch) { log.debug("Subsequent share session {} expected epoch {}, but got {}. " + "Possible duplicate request.", session.key(), expectedEpoch, sessionEpoch); return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.INVALID_SHARE_SESSION_EPOCH, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } /** * Iterator that goes over the given partition map and selects partitions that need to be included in the response. * If updateShareContextAndRemoveUnselected is set to true, the share context will be updated for the selected * partitions and also remove unselected ones as they are encountered. */ private class PartitionIterator implements Iterator<Entry<TopicIdPartition, PartitionData>> { private final Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator; private final boolean updateShareContextAndRemoveUnselected; private Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> nextElement; public PartitionIterator(Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator, boolean updateShareContextAndRemoveUnselected) { this.iterator = iterator; this.updateShareContextAndRemoveUnselected = updateShareContextAndRemoveUnselected; } @Override public boolean hasNext() { while ((nextElement == null) && iterator.hasNext()) { Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> element = iterator.next(); TopicIdPartition topicPart = element.getKey(); ShareFetchResponseData.PartitionData respData = element.getValue(); synchronized (session) { CachedSharePartition cachedPart = session.partitionMap().find(new CachedSharePartition(topicPart)); boolean mustRespond = cachedPart.maybeUpdateResponseData(respData, updateShareContextAndRemoveUnselected); if (mustRespond) { nextElement = element; if (updateShareContextAndRemoveUnselected && ShareFetchResponse.recordsSize(respData) > 0) { // Session.partitionMap
|
You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.server.share.context; import org.apache.kafka.common.TopicIdPartition; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.Uuid; import org.apache.kafka.common.message.ShareFetchResponseData; import org.apache.kafka.common.message.ShareFetchResponseData.PartitionData; import org.apache.kafka.common.protocol.Errors; import org.apache.kafka.common.requests.ShareFetchRequest; import org.apache.kafka.common.requests.ShareFetchRequest.SharePartitionData; import org.apache.kafka.common.requests.ShareFetchResponse; import org.apache.kafka.common.requests.ShareRequestMetadata; import org.apache.kafka.server.share.CachedSharePartition; import org.apache.kafka.server.share.ErroneousAndValidPartitionData; import org.apache.kafka.server.share.session.ShareSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; /** * The context for a share session fetch request. */ public class ShareSessionContext extends ShareFetchContext { private static final Logger log = LoggerFactory.getLogger(ShareSessionContext.class); private final ShareRequestMetadata reqMetadata; private final boolean isSubsequent ; private Map<TopicIdPartition, SharePartitionData> shareFetchData; private ShareSession session; /** * The share fetch context for the first request that starts a share session. * * @param reqMetadata The request metadata. * @param shareFetchData The share partition data from the share fetch request. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData) { this.reqMetadata = reqMetadata; this.shareFetchData = shareFetchData; this. isSubsequent = false; } /** * The share fetch context for a subsequent request that utilizes an existing share session. * * @param reqMetadata The request metadata. * @param session The subsequent fetch request session. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, ShareSession session) { this.reqMetadata = reqMetadata; this.session = session; this. isSubsequent = true; } // Visible for testing public Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData() { return shareFetchData; } // Visible for testing public boolean isSubsequent () { return isSubsequent ; } // Visible for testing public ShareSession session() { return session; } @Override boolean isTraceEnabled() { return log.isTraceEnabled(); } @Override public ShareFetchResponse throttleResponse(int throttleTimeMs) { if (! isSubsequent ) { return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); int sessionEpoch; synchronized (session) { sessionEpoch = session.epoch; } if (sessionEpoch != expectedEpoch) { log.debug("Subsequent share session {} expected epoch {}, but got {}. " + "Possible duplicate request.", session.key(), expectedEpoch, sessionEpoch); return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.INVALID_SHARE_SESSION_EPOCH, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } /** * Iterator that goes over the given partition map and selects partitions that need to be included in the response. * If updateShareContextAndRemoveUnselected is set to true, the share context will be updated for the selected * partitions and also remove unselected ones as they are encountered. */ private class PartitionIterator implements Iterator<Entry<TopicIdPartition, PartitionData>> { private final Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator; private final boolean updateShareContextAndRemoveUnselected; private Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> nextElement; public PartitionIterator(Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator, boolean updateShareContextAndRemoveUnselected) { this.iterator = iterator; this.updateShareContextAndRemoveUnselected = updateShareContextAndRemoveUnselected; } @Override public boolean hasNext() { while ((nextElement == null) && iterator.hasNext()) { Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> element = iterator.next(); TopicIdPartition topicPart = element.getKey(); ShareFetchResponseData.PartitionData respData = element.getValue(); synchronized (session) { CachedSharePartition cachedPart = session.partitionMap().find(new CachedSharePartition(topicPart)); boolean mustRespond = cachedPart.maybeUpdateResponseData(respData, updateShareContextAndRemoveUnselected); if (mustRespond) { nextElement = element; if (updateShareContextAndRemoveUnselected && ShareFetchResponse.recordsSize(respData) > 0) { // Session.partitionMap
|
java
|
in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.server.share.context; import org.apache.kafka.common.TopicIdPartition; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.Uuid; import org.apache.kafka.common.message.ShareFetchResponseData; import org.apache.kafka.common.message.ShareFetchResponseData.PartitionData; import org.apache.kafka.common.protocol.Errors; import org.apache.kafka.common.requests.ShareFetchRequest; import org.apache.kafka.common.requests.ShareFetchRequest.SharePartitionData; import org.apache.kafka.common.requests.ShareFetchResponse; import org.apache.kafka.common.requests.ShareRequestMetadata; import org.apache.kafka.server.share.CachedSharePartition; import org.apache.kafka.server.share.ErroneousAndValidPartitionData; import org.apache.kafka.server.share.session.ShareSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; /** * The context for a share session fetch request. */ public class ShareSessionContext extends ShareFetchContext { private static final Logger log = LoggerFactory.getLogger(ShareSessionContext.class); private final ShareRequestMetadata reqMetadata; private final boolean <mask> <mask> <mask> <mask> <mask> ; private Map<TopicIdPartition, SharePartitionData> shareFetchData; private ShareSession session; /** * The share fetch context for the first request that starts a share session. * * @param reqMetadata The request metadata. * @param shareFetchData The share partition data from the share fetch request. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData) { this.reqMetadata = reqMetadata; this.shareFetchData = shareFetchData; this. <mask> <mask> <mask> <mask> <mask> = false; } /** * The share fetch context for a subsequent request that utilizes an existing share session. * * @param reqMetadata The request metadata. * @param session The subsequent fetch request session. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, ShareSession session) { this.reqMetadata = reqMetadata; this.session = session; this. <mask> <mask> <mask> <mask> <mask> = true; } // Visible for testing public Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData() { return shareFetchData; } // Visible for testing public boolean <mask> <mask> <mask> <mask> <mask> () { return <mask> <mask> <mask> <mask> <mask> ; } // Visible for testing public ShareSession session() { return session; } @Override boolean isTraceEnabled() { return log.isTraceEnabled(); } @Override public ShareFetchResponse throttleResponse(int throttleTimeMs) { if (! <mask> <mask> <mask> <mask> <mask> ) { return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); int sessionEpoch; synchronized (session) { sessionEpoch = session.epoch; } if (sessionEpoch != expectedEpoch) { log.debug("Subsequent share session {} expected epoch {}, but got {}. " + "Possible duplicate request.", session.key(), expectedEpoch, sessionEpoch); return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.INVALID_SHARE_SESSION_EPOCH, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } /** * Iterator that goes over the given partition map and selects partitions that need to be included in the response. * If updateShareContextAndRemoveUnselected is set to true, the share context will be updated for the selected * partitions and also remove unselected ones as they are encountered. */ private class PartitionIterator implements Iterator<Entry<TopicIdPartition, PartitionData>> { private final Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator; private final boolean updateShareContextAndRemoveUnselected; private Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> nextElement; public PartitionIterator(Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator, boolean updateShareContextAndRemoveUnselected) { this.iterator = iterator; this.updateShareContextAndRemoveUnselected = updateShareContextAndRemoveUnselected; } @Override public boolean hasNext() { while ((nextElement == null) && iterator.hasNext()) { Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> element = iterator.next(); TopicIdPartition topicPart = element.getKey(); ShareFetchResponseData.PartitionData respData = element.getValue(); synchronized (session) { CachedSharePartition cachedPart = session.partitionMap().find(new CachedSharePartition(topicPart)); boolean mustRespond = cachedPart.maybeUpdateResponseData(respData, updateShareContextAndRemoveUnselected); if (mustRespond) { nextElement = element; if (updateShareContextAndRemoveUnselected && ShareFetchResponse.recordsSize(respData) > 0) { // Session.partitionMap is of type ImplicitLinkedHashCollection<> which tracks the order of insertion of elements. // Since, we are updating an element in this case,
|
in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.server.share.context; import org.apache.kafka.common.TopicIdPartition; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.Uuid; import org.apache.kafka.common.message.ShareFetchResponseData; import org.apache.kafka.common.message.ShareFetchResponseData.PartitionData; import org.apache.kafka.common.protocol.Errors; import org.apache.kafka.common.requests.ShareFetchRequest; import org.apache.kafka.common.requests.ShareFetchRequest.SharePartitionData; import org.apache.kafka.common.requests.ShareFetchResponse; import org.apache.kafka.common.requests.ShareRequestMetadata; import org.apache.kafka.server.share.CachedSharePartition; import org.apache.kafka.server.share.ErroneousAndValidPartitionData; import org.apache.kafka.server.share.session.ShareSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; /** * The context for a share session fetch request. */ public class ShareSessionContext extends ShareFetchContext { private static final Logger log = LoggerFactory.getLogger(ShareSessionContext.class); private final ShareRequestMetadata reqMetadata; private final boolean isSubsequent ; private Map<TopicIdPartition, SharePartitionData> shareFetchData; private ShareSession session; /** * The share fetch context for the first request that starts a share session. * * @param reqMetadata The request metadata. * @param shareFetchData The share partition data from the share fetch request. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData) { this.reqMetadata = reqMetadata; this.shareFetchData = shareFetchData; this. isSubsequent = false; } /** * The share fetch context for a subsequent request that utilizes an existing share session. * * @param reqMetadata The request metadata. * @param session The subsequent fetch request session. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, ShareSession session) { this.reqMetadata = reqMetadata; this.session = session; this. isSubsequent = true; } // Visible for testing public Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData() { return shareFetchData; } // Visible for testing public boolean isSubsequent () { return isSubsequent ; } // Visible for testing public ShareSession session() { return session; } @Override boolean isTraceEnabled() { return log.isTraceEnabled(); } @Override public ShareFetchResponse throttleResponse(int throttleTimeMs) { if (! isSubsequent ) { return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); int sessionEpoch; synchronized (session) { sessionEpoch = session.epoch; } if (sessionEpoch != expectedEpoch) { log.debug("Subsequent share session {} expected epoch {}, but got {}. " + "Possible duplicate request.", session.key(), expectedEpoch, sessionEpoch); return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.INVALID_SHARE_SESSION_EPOCH, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } /** * Iterator that goes over the given partition map and selects partitions that need to be included in the response. * If updateShareContextAndRemoveUnselected is set to true, the share context will be updated for the selected * partitions and also remove unselected ones as they are encountered. */ private class PartitionIterator implements Iterator<Entry<TopicIdPartition, PartitionData>> { private final Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator; private final boolean updateShareContextAndRemoveUnselected; private Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> nextElement; public PartitionIterator(Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator, boolean updateShareContextAndRemoveUnselected) { this.iterator = iterator; this.updateShareContextAndRemoveUnselected = updateShareContextAndRemoveUnselected; } @Override public boolean hasNext() { while ((nextElement == null) && iterator.hasNext()) { Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> element = iterator.next(); TopicIdPartition topicPart = element.getKey(); ShareFetchResponseData.PartitionData respData = element.getValue(); synchronized (session) { CachedSharePartition cachedPart = session.partitionMap().find(new CachedSharePartition(topicPart)); boolean mustRespond = cachedPart.maybeUpdateResponseData(respData, updateShareContextAndRemoveUnselected); if (mustRespond) { nextElement = element; if (updateShareContextAndRemoveUnselected && ShareFetchResponse.recordsSize(respData) > 0) { // Session.partitionMap is of type ImplicitLinkedHashCollection<> which tracks the order of insertion of elements. // Since, we are updating an element in this case,
|
java
|
distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.server.share.context; import org.apache.kafka.common.TopicIdPartition; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.Uuid; import org.apache.kafka.common.message.ShareFetchResponseData; import org.apache.kafka.common.message.ShareFetchResponseData.PartitionData; import org.apache.kafka.common.protocol.Errors; import org.apache.kafka.common.requests.ShareFetchRequest; import org.apache.kafka.common.requests.ShareFetchRequest.SharePartitionData; import org.apache.kafka.common.requests.ShareFetchResponse; import org.apache.kafka.common.requests.ShareRequestMetadata; import org.apache.kafka.server.share.CachedSharePartition; import org.apache.kafka.server.share.ErroneousAndValidPartitionData; import org.apache.kafka.server.share.session.ShareSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; /** * The context for a share session fetch request. */ public class ShareSessionContext extends ShareFetchContext { private static final Logger log = LoggerFactory.getLogger(ShareSessionContext.class); private final ShareRequestMetadata reqMetadata; private final boolean <mask> <mask> <mask> <mask> <mask> ; private Map<TopicIdPartition, SharePartitionData> shareFetchData; private ShareSession session; /** * The share fetch context for the first request that starts a share session. * * @param reqMetadata The request metadata. * @param shareFetchData The share partition data from the share fetch request. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData) { this.reqMetadata = reqMetadata; this.shareFetchData = shareFetchData; this. <mask> <mask> <mask> <mask> <mask> = false; } /** * The share fetch context for a subsequent request that utilizes an existing share session. * * @param reqMetadata The request metadata. * @param session The subsequent fetch request session. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, ShareSession session) { this.reqMetadata = reqMetadata; this.session = session; this. <mask> <mask> <mask> <mask> <mask> = true; } // Visible for testing public Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData() { return shareFetchData; } // Visible for testing public boolean <mask> <mask> <mask> <mask> <mask> () { return <mask> <mask> <mask> <mask> <mask> ; } // Visible for testing public ShareSession session() { return session; } @Override boolean isTraceEnabled() { return log.isTraceEnabled(); } @Override public ShareFetchResponse throttleResponse(int throttleTimeMs) { if (! <mask> <mask> <mask> <mask> <mask> ) { return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); int sessionEpoch; synchronized (session) { sessionEpoch = session.epoch; } if (sessionEpoch != expectedEpoch) { log.debug("Subsequent share session {} expected epoch {}, but got {}. " + "Possible duplicate request.", session.key(), expectedEpoch, sessionEpoch); return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.INVALID_SHARE_SESSION_EPOCH, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } /** * Iterator that goes over the given partition map and selects partitions that need to be included in the response. * If updateShareContextAndRemoveUnselected is set to true, the share context will be updated for the selected * partitions and also remove unselected ones as they are encountered. */ private class PartitionIterator implements Iterator<Entry<TopicIdPartition, PartitionData>> { private final Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator; private final boolean updateShareContextAndRemoveUnselected; private Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> nextElement; public PartitionIterator(Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator, boolean updateShareContextAndRemoveUnselected) { this.iterator = iterator; this.updateShareContextAndRemoveUnselected = updateShareContextAndRemoveUnselected; } @Override public boolean hasNext() { while ((nextElement == null) && iterator.hasNext()) { Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> element = iterator.next(); TopicIdPartition topicPart = element.getKey(); ShareFetchResponseData.PartitionData respData = element.getValue(); synchronized (session) { CachedSharePartition cachedPart = session.partitionMap().find(new CachedSharePartition(topicPart)); boolean mustRespond = cachedPart.maybeUpdateResponseData(respData, updateShareContextAndRemoveUnselected); if (mustRespond) { nextElement = element; if (updateShareContextAndRemoveUnselected && ShareFetchResponse.recordsSize(respData) > 0) { // Session.partitionMap is of type ImplicitLinkedHashCollection<> which tracks the order of insertion of elements. // Since, we are updating an element in this case, we need to perform
|
distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.server.share.context; import org.apache.kafka.common.TopicIdPartition; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.Uuid; import org.apache.kafka.common.message.ShareFetchResponseData; import org.apache.kafka.common.message.ShareFetchResponseData.PartitionData; import org.apache.kafka.common.protocol.Errors; import org.apache.kafka.common.requests.ShareFetchRequest; import org.apache.kafka.common.requests.ShareFetchRequest.SharePartitionData; import org.apache.kafka.common.requests.ShareFetchResponse; import org.apache.kafka.common.requests.ShareRequestMetadata; import org.apache.kafka.server.share.CachedSharePartition; import org.apache.kafka.server.share.ErroneousAndValidPartitionData; import org.apache.kafka.server.share.session.ShareSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; /** * The context for a share session fetch request. */ public class ShareSessionContext extends ShareFetchContext { private static final Logger log = LoggerFactory.getLogger(ShareSessionContext.class); private final ShareRequestMetadata reqMetadata; private final boolean isSubsequent ; private Map<TopicIdPartition, SharePartitionData> shareFetchData; private ShareSession session; /** * The share fetch context for the first request that starts a share session. * * @param reqMetadata The request metadata. * @param shareFetchData The share partition data from the share fetch request. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData) { this.reqMetadata = reqMetadata; this.shareFetchData = shareFetchData; this. isSubsequent = false; } /** * The share fetch context for a subsequent request that utilizes an existing share session. * * @param reqMetadata The request metadata. * @param session The subsequent fetch request session. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, ShareSession session) { this.reqMetadata = reqMetadata; this.session = session; this. isSubsequent = true; } // Visible for testing public Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData() { return shareFetchData; } // Visible for testing public boolean isSubsequent () { return isSubsequent ; } // Visible for testing public ShareSession session() { return session; } @Override boolean isTraceEnabled() { return log.isTraceEnabled(); } @Override public ShareFetchResponse throttleResponse(int throttleTimeMs) { if (! isSubsequent ) { return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); int sessionEpoch; synchronized (session) { sessionEpoch = session.epoch; } if (sessionEpoch != expectedEpoch) { log.debug("Subsequent share session {} expected epoch {}, but got {}. " + "Possible duplicate request.", session.key(), expectedEpoch, sessionEpoch); return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.INVALID_SHARE_SESSION_EPOCH, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } /** * Iterator that goes over the given partition map and selects partitions that need to be included in the response. * If updateShareContextAndRemoveUnselected is set to true, the share context will be updated for the selected * partitions and also remove unselected ones as they are encountered. */ private class PartitionIterator implements Iterator<Entry<TopicIdPartition, PartitionData>> { private final Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator; private final boolean updateShareContextAndRemoveUnselected; private Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> nextElement; public PartitionIterator(Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator, boolean updateShareContextAndRemoveUnselected) { this.iterator = iterator; this.updateShareContextAndRemoveUnselected = updateShareContextAndRemoveUnselected; } @Override public boolean hasNext() { while ((nextElement == null) && iterator.hasNext()) { Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> element = iterator.next(); TopicIdPartition topicPart = element.getKey(); ShareFetchResponseData.PartitionData respData = element.getValue(); synchronized (session) { CachedSharePartition cachedPart = session.partitionMap().find(new CachedSharePartition(topicPart)); boolean mustRespond = cachedPart.maybeUpdateResponseData(respData, updateShareContextAndRemoveUnselected); if (mustRespond) { nextElement = element; if (updateShareContextAndRemoveUnselected && ShareFetchResponse.recordsSize(respData) > 0) { // Session.partitionMap is of type ImplicitLinkedHashCollection<> which tracks the order of insertion of elements. // Since, we are updating an element in this case, we need to perform
|
java
|
specific language governing permissions and * limitations under the License. */ package org.apache.kafka.server.share.context; import org.apache.kafka.common.TopicIdPartition; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.Uuid; import org.apache.kafka.common.message.ShareFetchResponseData; import org.apache.kafka.common.message.ShareFetchResponseData.PartitionData; import org.apache.kafka.common.protocol.Errors; import org.apache.kafka.common.requests.ShareFetchRequest; import org.apache.kafka.common.requests.ShareFetchRequest.SharePartitionData; import org.apache.kafka.common.requests.ShareFetchResponse; import org.apache.kafka.common.requests.ShareRequestMetadata; import org.apache.kafka.server.share.CachedSharePartition; import org.apache.kafka.server.share.ErroneousAndValidPartitionData; import org.apache.kafka.server.share.session.ShareSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; /** * The context for a share session fetch request. */ public class ShareSessionContext extends ShareFetchContext { private static final Logger log = LoggerFactory.getLogger(ShareSessionContext.class); private final ShareRequestMetadata reqMetadata; private final boolean <mask> <mask> <mask> <mask> <mask> ; private Map<TopicIdPartition, SharePartitionData> shareFetchData; private ShareSession session; /** * The share fetch context for the first request that starts a share session. * * @param reqMetadata The request metadata. * @param shareFetchData The share partition data from the share fetch request. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData) { this.reqMetadata = reqMetadata; this.shareFetchData = shareFetchData; this. <mask> <mask> <mask> <mask> <mask> = false; } /** * The share fetch context for a subsequent request that utilizes an existing share session. * * @param reqMetadata The request metadata. * @param session The subsequent fetch request session. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, ShareSession session) { this.reqMetadata = reqMetadata; this.session = session; this. <mask> <mask> <mask> <mask> <mask> = true; } // Visible for testing public Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData() { return shareFetchData; } // Visible for testing public boolean <mask> <mask> <mask> <mask> <mask> () { return <mask> <mask> <mask> <mask> <mask> ; } // Visible for testing public ShareSession session() { return session; } @Override boolean isTraceEnabled() { return log.isTraceEnabled(); } @Override public ShareFetchResponse throttleResponse(int throttleTimeMs) { if (! <mask> <mask> <mask> <mask> <mask> ) { return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); int sessionEpoch; synchronized (session) { sessionEpoch = session.epoch; } if (sessionEpoch != expectedEpoch) { log.debug("Subsequent share session {} expected epoch {}, but got {}. " + "Possible duplicate request.", session.key(), expectedEpoch, sessionEpoch); return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.INVALID_SHARE_SESSION_EPOCH, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } /** * Iterator that goes over the given partition map and selects partitions that need to be included in the response. * If updateShareContextAndRemoveUnselected is set to true, the share context will be updated for the selected * partitions and also remove unselected ones as they are encountered. */ private class PartitionIterator implements Iterator<Entry<TopicIdPartition, PartitionData>> { private final Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator; private final boolean updateShareContextAndRemoveUnselected; private Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> nextElement; public PartitionIterator(Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator, boolean updateShareContextAndRemoveUnselected) { this.iterator = iterator; this.updateShareContextAndRemoveUnselected = updateShareContextAndRemoveUnselected; } @Override public boolean hasNext() { while ((nextElement == null) && iterator.hasNext()) { Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> element = iterator.next(); TopicIdPartition topicPart = element.getKey(); ShareFetchResponseData.PartitionData respData = element.getValue(); synchronized (session) { CachedSharePartition cachedPart = session.partitionMap().find(new CachedSharePartition(topicPart)); boolean mustRespond = cachedPart.maybeUpdateResponseData(respData, updateShareContextAndRemoveUnselected); if (mustRespond) { nextElement = element; if (updateShareContextAndRemoveUnselected && ShareFetchResponse.recordsSize(respData) > 0) { // Session.partitionMap is of type ImplicitLinkedHashCollection<> which tracks the order of insertion of elements. // Since, we are updating an element in this case, we need to perform a remove and then a mustAdd to maintain the correct order session.partitionMap().remove(cachedPart); session.partitionMap().mustAdd(cachedPart); } } else { if (updateShareContextAndRemoveUnselected) { iterator.remove(); } } } } return nextElement != null;
|
specific language governing permissions and * limitations under the License. */ package org.apache.kafka.server.share.context; import org.apache.kafka.common.TopicIdPartition; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.Uuid; import org.apache.kafka.common.message.ShareFetchResponseData; import org.apache.kafka.common.message.ShareFetchResponseData.PartitionData; import org.apache.kafka.common.protocol.Errors; import org.apache.kafka.common.requests.ShareFetchRequest; import org.apache.kafka.common.requests.ShareFetchRequest.SharePartitionData; import org.apache.kafka.common.requests.ShareFetchResponse; import org.apache.kafka.common.requests.ShareRequestMetadata; import org.apache.kafka.server.share.CachedSharePartition; import org.apache.kafka.server.share.ErroneousAndValidPartitionData; import org.apache.kafka.server.share.session.ShareSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; /** * The context for a share session fetch request. */ public class ShareSessionContext extends ShareFetchContext { private static final Logger log = LoggerFactory.getLogger(ShareSessionContext.class); private final ShareRequestMetadata reqMetadata; private final boolean isSubsequent ; private Map<TopicIdPartition, SharePartitionData> shareFetchData; private ShareSession session; /** * The share fetch context for the first request that starts a share session. * * @param reqMetadata The request metadata. * @param shareFetchData The share partition data from the share fetch request. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData) { this.reqMetadata = reqMetadata; this.shareFetchData = shareFetchData; this. isSubsequent = false; } /** * The share fetch context for a subsequent request that utilizes an existing share session. * * @param reqMetadata The request metadata. * @param session The subsequent fetch request session. */ public ShareSessionContext(ShareRequestMetadata reqMetadata, ShareSession session) { this.reqMetadata = reqMetadata; this.session = session; this. isSubsequent = true; } // Visible for testing public Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData() { return shareFetchData; } // Visible for testing public boolean isSubsequent () { return isSubsequent ; } // Visible for testing public ShareSession session() { return session; } @Override boolean isTraceEnabled() { return log.isTraceEnabled(); } @Override public ShareFetchResponse throttleResponse(int throttleTimeMs) { if (! isSubsequent ) { return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); int sessionEpoch; synchronized (session) { sessionEpoch = session.epoch; } if (sessionEpoch != expectedEpoch) { log.debug("Subsequent share session {} expected epoch {}, but got {}. " + "Possible duplicate request.", session.key(), expectedEpoch, sessionEpoch); return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.INVALID_SHARE_SESSION_EPOCH, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } /** * Iterator that goes over the given partition map and selects partitions that need to be included in the response. * If updateShareContextAndRemoveUnselected is set to true, the share context will be updated for the selected * partitions and also remove unselected ones as they are encountered. */ private class PartitionIterator implements Iterator<Entry<TopicIdPartition, PartitionData>> { private final Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator; private final boolean updateShareContextAndRemoveUnselected; private Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> nextElement; public PartitionIterator(Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator, boolean updateShareContextAndRemoveUnselected) { this.iterator = iterator; this.updateShareContextAndRemoveUnselected = updateShareContextAndRemoveUnselected; } @Override public boolean hasNext() { while ((nextElement == null) && iterator.hasNext()) { Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> element = iterator.next(); TopicIdPartition topicPart = element.getKey(); ShareFetchResponseData.PartitionData respData = element.getValue(); synchronized (session) { CachedSharePartition cachedPart = session.partitionMap().find(new CachedSharePartition(topicPart)); boolean mustRespond = cachedPart.maybeUpdateResponseData(respData, updateShareContextAndRemoveUnselected); if (mustRespond) { nextElement = element; if (updateShareContextAndRemoveUnselected && ShareFetchResponse.recordsSize(respData) > 0) { // Session.partitionMap is of type ImplicitLinkedHashCollection<> which tracks the order of insertion of elements. // Since, we are updating an element in this case, we need to perform a remove and then a mustAdd to maintain the correct order session.partitionMap().remove(cachedPart); session.partitionMap().mustAdd(cachedPart); } } else { if (updateShareContextAndRemoveUnselected) { iterator.remove(); } } } } return nextElement != null;
|
java
|
sessionEpoch); return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.INVALID_SHARE_SESSION_EPOCH, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } /** * Iterator that goes over the given partition map and selects partitions that need to be included in the response. * If updateShareContextAndRemoveUnselected is set to true, the share context will be updated for the selected * partitions and also remove unselected ones as they are encountered. */ private class PartitionIterator implements Iterator<Entry<TopicIdPartition, PartitionData>> { private final Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator; private final boolean updateShareContextAndRemoveUnselected; private Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> nextElement; public PartitionIterator(Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator, boolean updateShareContextAndRemoveUnselected) { this.iterator = iterator; this.updateShareContextAndRemoveUnselected = updateShareContextAndRemoveUnselected; } @Override public boolean hasNext() { while ((nextElement == null) && iterator.hasNext()) { Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> element = iterator.next(); TopicIdPartition topicPart = element.getKey(); ShareFetchResponseData.PartitionData respData = element.getValue(); synchronized (session) { CachedSharePartition cachedPart = session.partitionMap().find(new CachedSharePartition(topicPart)); boolean mustRespond = cachedPart.maybeUpdateResponseData(respData, updateShareContextAndRemoveUnselected); if (mustRespond) { nextElement = element; if (updateShareContextAndRemoveUnselected && ShareFetchResponse.recordsSize(respData) > 0) { // Session.partitionMap is of type ImplicitLinkedHashCollection<> which tracks the order of insertion of elements. // Since, we are updating an element in this case, we need to perform a remove and then a mustAdd to maintain the correct order session.partitionMap().remove(cachedPart); session.partitionMap().mustAdd(cachedPart); } } else { if (updateShareContextAndRemoveUnselected) { iterator.remove(); } } } } return nextElement != null; } @Override public Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> next() { if (!hasNext()) throw new NoSuchElementException(); Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> element = nextElement; nextElement = null; return element; } @Override public void remove() { throw new UnsupportedOperationException(); } } @Override public int responseSize(LinkedHashMap<TopicIdPartition, PartitionData> updates, short version) { if (! <mask> <mask> <mask> <mask> <mask> ) return ShareFetchResponse.sizeOf(version, updates.entrySet().iterator()); synchronized (session) { int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); if (session.epoch != expectedEpoch) { return ShareFetchResponse.sizeOf(version, Collections.emptyIterator()); } // Pass the partition iterator which updates neither the share fetch context nor the partition map. return ShareFetchResponse.sizeOf(version, new PartitionIterator(updates.entrySet().iterator(), false)); } } @Override public ShareFetchResponse updateAndGenerateResponseData(String groupId, Uuid memberId, LinkedHashMap<TopicIdPartition, ShareFetchResponseData.PartitionData> updates) { if (! <mask> <mask> <mask> <mask> <mask> ) { return new ShareFetchResponse(ShareFetchResponse.toMessage( Errors.NONE, 0, updates.entrySet().iterator(), Collections.emptyList())); } else { int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); int sessionEpoch; synchronized (session) { sessionEpoch = session.epoch; } if (sessionEpoch != expectedEpoch) { log.debug("Subsequent share session {} expected epoch {}, but got {}. Possible duplicate request.", session.key(), expectedEpoch, sessionEpoch); return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.INVALID_SHARE_SESSION_EPOCH, 0, Collections.emptyIterator(), Collections.emptyList())); } // Iterate over the update list using PartitionIterator. This will prune updates which don't need to be sent Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> partitionIterator = new PartitionIterator( updates.entrySet().iterator(), true); while (partitionIterator.hasNext()) { partitionIterator.next(); } log.debug("Subsequent share session context with session key {} returning {}", session.key(), partitionsToLogString(updates.keySet())); return new ShareFetchResponse(ShareFetchResponse.toMessage( Errors.NONE, 0, updates.entrySet().iterator(), Collections.emptyList())); } } @Override public ErroneousAndValidPartitionData getErroneousAndValidTopicIdPartitions() { if (! <mask> <mask> <mask> <mask> <mask> ) { return new ErroneousAndValidPartitionData(shareFetchData); } Map<TopicIdPartition, PartitionData> erroneous = new HashMap<>(); Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> valid = new HashMap<>(); // Take the session lock and iterate over all the cached partitions. synchronized (session) { session.partitionMap().forEach(cachedSharePartition -> { TopicIdPartition topicIdPartition = new TopicIdPartition(cachedSharePartition.topicId(), new TopicPartition(cachedSharePartition.topic(), cachedSharePartition.partition())); ShareFetchRequest.SharePartitionData reqData = cachedSharePartition.reqData(); if (topicIdPartition.topic() == null) { erroneous.put(topicIdPartition, ShareFetchResponse.partitionResponse(topicIdPartition, Errors.UNKNOWN_TOPIC_ID)); } else { valid.put(topicIdPartition, reqData); } }); return new ErroneousAndValidPartitionData(erroneous, valid); } } }
|
sessionEpoch); return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.INVALID_SHARE_SESSION_EPOCH, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs, Collections.emptyIterator(), Collections.emptyList())); } /** * Iterator that goes over the given partition map and selects partitions that need to be included in the response. * If updateShareContextAndRemoveUnselected is set to true, the share context will be updated for the selected * partitions and also remove unselected ones as they are encountered. */ private class PartitionIterator implements Iterator<Entry<TopicIdPartition, PartitionData>> { private final Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator; private final boolean updateShareContextAndRemoveUnselected; private Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> nextElement; public PartitionIterator(Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator, boolean updateShareContextAndRemoveUnselected) { this.iterator = iterator; this.updateShareContextAndRemoveUnselected = updateShareContextAndRemoveUnselected; } @Override public boolean hasNext() { while ((nextElement == null) && iterator.hasNext()) { Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> element = iterator.next(); TopicIdPartition topicPart = element.getKey(); ShareFetchResponseData.PartitionData respData = element.getValue(); synchronized (session) { CachedSharePartition cachedPart = session.partitionMap().find(new CachedSharePartition(topicPart)); boolean mustRespond = cachedPart.maybeUpdateResponseData(respData, updateShareContextAndRemoveUnselected); if (mustRespond) { nextElement = element; if (updateShareContextAndRemoveUnselected && ShareFetchResponse.recordsSize(respData) > 0) { // Session.partitionMap is of type ImplicitLinkedHashCollection<> which tracks the order of insertion of elements. // Since, we are updating an element in this case, we need to perform a remove and then a mustAdd to maintain the correct order session.partitionMap().remove(cachedPart); session.partitionMap().mustAdd(cachedPart); } } else { if (updateShareContextAndRemoveUnselected) { iterator.remove(); } } } } return nextElement != null; } @Override public Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> next() { if (!hasNext()) throw new NoSuchElementException(); Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> element = nextElement; nextElement = null; return element; } @Override public void remove() { throw new UnsupportedOperationException(); } } @Override public int responseSize(LinkedHashMap<TopicIdPartition, PartitionData> updates, short version) { if (! isSubsequent ) return ShareFetchResponse.sizeOf(version, updates.entrySet().iterator()); synchronized (session) { int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); if (session.epoch != expectedEpoch) { return ShareFetchResponse.sizeOf(version, Collections.emptyIterator()); } // Pass the partition iterator which updates neither the share fetch context nor the partition map. return ShareFetchResponse.sizeOf(version, new PartitionIterator(updates.entrySet().iterator(), false)); } } @Override public ShareFetchResponse updateAndGenerateResponseData(String groupId, Uuid memberId, LinkedHashMap<TopicIdPartition, ShareFetchResponseData.PartitionData> updates) { if (! isSubsequent ) { return new ShareFetchResponse(ShareFetchResponse.toMessage( Errors.NONE, 0, updates.entrySet().iterator(), Collections.emptyList())); } else { int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); int sessionEpoch; synchronized (session) { sessionEpoch = session.epoch; } if (sessionEpoch != expectedEpoch) { log.debug("Subsequent share session {} expected epoch {}, but got {}. Possible duplicate request.", session.key(), expectedEpoch, sessionEpoch); return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.INVALID_SHARE_SESSION_EPOCH, 0, Collections.emptyIterator(), Collections.emptyList())); } // Iterate over the update list using PartitionIterator. This will prune updates which don't need to be sent Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> partitionIterator = new PartitionIterator( updates.entrySet().iterator(), true); while (partitionIterator.hasNext()) { partitionIterator.next(); } log.debug("Subsequent share session context with session key {} returning {}", session.key(), partitionsToLogString(updates.keySet())); return new ShareFetchResponse(ShareFetchResponse.toMessage( Errors.NONE, 0, updates.entrySet().iterator(), Collections.emptyList())); } } @Override public ErroneousAndValidPartitionData getErroneousAndValidTopicIdPartitions() { if (! isSubsequent ) { return new ErroneousAndValidPartitionData(shareFetchData); } Map<TopicIdPartition, PartitionData> erroneous = new HashMap<>(); Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> valid = new HashMap<>(); // Take the session lock and iterate over all the cached partitions. synchronized (session) { session.partitionMap().forEach(cachedSharePartition -> { TopicIdPartition topicIdPartition = new TopicIdPartition(cachedSharePartition.topicId(), new TopicPartition(cachedSharePartition.topic(), cachedSharePartition.partition())); ShareFetchRequest.SharePartitionData reqData = cachedSharePartition.reqData(); if (topicIdPartition.topic() == null) { erroneous.put(topicIdPartition, ShareFetchResponse.partitionResponse(topicIdPartition, Errors.UNKNOWN_TOPIC_ID)); } else { valid.put(topicIdPartition, reqData); } }); return new ErroneousAndValidPartitionData(erroneous, valid); } } }
|
java
|
unselected ones as they are encountered. */ private class PartitionIterator implements Iterator<Entry<TopicIdPartition, PartitionData>> { private final Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator; private final boolean updateShareContextAndRemoveUnselected; private Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> nextElement; public PartitionIterator(Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator, boolean updateShareContextAndRemoveUnselected) { this.iterator = iterator; this.updateShareContextAndRemoveUnselected = updateShareContextAndRemoveUnselected; } @Override public boolean hasNext() { while ((nextElement == null) && iterator.hasNext()) { Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> element = iterator.next(); TopicIdPartition topicPart = element.getKey(); ShareFetchResponseData.PartitionData respData = element.getValue(); synchronized (session) { CachedSharePartition cachedPart = session.partitionMap().find(new CachedSharePartition(topicPart)); boolean mustRespond = cachedPart.maybeUpdateResponseData(respData, updateShareContextAndRemoveUnselected); if (mustRespond) { nextElement = element; if (updateShareContextAndRemoveUnselected && ShareFetchResponse.recordsSize(respData) > 0) { // Session.partitionMap is of type ImplicitLinkedHashCollection<> which tracks the order of insertion of elements. // Since, we are updating an element in this case, we need to perform a remove and then a mustAdd to maintain the correct order session.partitionMap().remove(cachedPart); session.partitionMap().mustAdd(cachedPart); } } else { if (updateShareContextAndRemoveUnselected) { iterator.remove(); } } } } return nextElement != null; } @Override public Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> next() { if (!hasNext()) throw new NoSuchElementException(); Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> element = nextElement; nextElement = null; return element; } @Override public void remove() { throw new UnsupportedOperationException(); } } @Override public int responseSize(LinkedHashMap<TopicIdPartition, PartitionData> updates, short version) { if (! <mask> <mask> <mask> <mask> <mask> ) return ShareFetchResponse.sizeOf(version, updates.entrySet().iterator()); synchronized (session) { int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); if (session.epoch != expectedEpoch) { return ShareFetchResponse.sizeOf(version, Collections.emptyIterator()); } // Pass the partition iterator which updates neither the share fetch context nor the partition map. return ShareFetchResponse.sizeOf(version, new PartitionIterator(updates.entrySet().iterator(), false)); } } @Override public ShareFetchResponse updateAndGenerateResponseData(String groupId, Uuid memberId, LinkedHashMap<TopicIdPartition, ShareFetchResponseData.PartitionData> updates) { if (! <mask> <mask> <mask> <mask> <mask> ) { return new ShareFetchResponse(ShareFetchResponse.toMessage( Errors.NONE, 0, updates.entrySet().iterator(), Collections.emptyList())); } else { int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); int sessionEpoch; synchronized (session) { sessionEpoch = session.epoch; } if (sessionEpoch != expectedEpoch) { log.debug("Subsequent share session {} expected epoch {}, but got {}. Possible duplicate request.", session.key(), expectedEpoch, sessionEpoch); return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.INVALID_SHARE_SESSION_EPOCH, 0, Collections.emptyIterator(), Collections.emptyList())); } // Iterate over the update list using PartitionIterator. This will prune updates which don't need to be sent Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> partitionIterator = new PartitionIterator( updates.entrySet().iterator(), true); while (partitionIterator.hasNext()) { partitionIterator.next(); } log.debug("Subsequent share session context with session key {} returning {}", session.key(), partitionsToLogString(updates.keySet())); return new ShareFetchResponse(ShareFetchResponse.toMessage( Errors.NONE, 0, updates.entrySet().iterator(), Collections.emptyList())); } } @Override public ErroneousAndValidPartitionData getErroneousAndValidTopicIdPartitions() { if (! <mask> <mask> <mask> <mask> <mask> ) { return new ErroneousAndValidPartitionData(shareFetchData); } Map<TopicIdPartition, PartitionData> erroneous = new HashMap<>(); Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> valid = new HashMap<>(); // Take the session lock and iterate over all the cached partitions. synchronized (session) { session.partitionMap().forEach(cachedSharePartition -> { TopicIdPartition topicIdPartition = new TopicIdPartition(cachedSharePartition.topicId(), new TopicPartition(cachedSharePartition.topic(), cachedSharePartition.partition())); ShareFetchRequest.SharePartitionData reqData = cachedSharePartition.reqData(); if (topicIdPartition.topic() == null) { erroneous.put(topicIdPartition, ShareFetchResponse.partitionResponse(topicIdPartition, Errors.UNKNOWN_TOPIC_ID)); } else { valid.put(topicIdPartition, reqData); } }); return new ErroneousAndValidPartitionData(erroneous, valid); } } }
|
unselected ones as they are encountered. */ private class PartitionIterator implements Iterator<Entry<TopicIdPartition, PartitionData>> { private final Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator; private final boolean updateShareContextAndRemoveUnselected; private Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> nextElement; public PartitionIterator(Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator, boolean updateShareContextAndRemoveUnselected) { this.iterator = iterator; this.updateShareContextAndRemoveUnselected = updateShareContextAndRemoveUnselected; } @Override public boolean hasNext() { while ((nextElement == null) && iterator.hasNext()) { Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> element = iterator.next(); TopicIdPartition topicPart = element.getKey(); ShareFetchResponseData.PartitionData respData = element.getValue(); synchronized (session) { CachedSharePartition cachedPart = session.partitionMap().find(new CachedSharePartition(topicPart)); boolean mustRespond = cachedPart.maybeUpdateResponseData(respData, updateShareContextAndRemoveUnselected); if (mustRespond) { nextElement = element; if (updateShareContextAndRemoveUnselected && ShareFetchResponse.recordsSize(respData) > 0) { // Session.partitionMap is of type ImplicitLinkedHashCollection<> which tracks the order of insertion of elements. // Since, we are updating an element in this case, we need to perform a remove and then a mustAdd to maintain the correct order session.partitionMap().remove(cachedPart); session.partitionMap().mustAdd(cachedPart); } } else { if (updateShareContextAndRemoveUnselected) { iterator.remove(); } } } } return nextElement != null; } @Override public Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> next() { if (!hasNext()) throw new NoSuchElementException(); Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> element = nextElement; nextElement = null; return element; } @Override public void remove() { throw new UnsupportedOperationException(); } } @Override public int responseSize(LinkedHashMap<TopicIdPartition, PartitionData> updates, short version) { if (! isSubsequent ) return ShareFetchResponse.sizeOf(version, updates.entrySet().iterator()); synchronized (session) { int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); if (session.epoch != expectedEpoch) { return ShareFetchResponse.sizeOf(version, Collections.emptyIterator()); } // Pass the partition iterator which updates neither the share fetch context nor the partition map. return ShareFetchResponse.sizeOf(version, new PartitionIterator(updates.entrySet().iterator(), false)); } } @Override public ShareFetchResponse updateAndGenerateResponseData(String groupId, Uuid memberId, LinkedHashMap<TopicIdPartition, ShareFetchResponseData.PartitionData> updates) { if (! isSubsequent ) { return new ShareFetchResponse(ShareFetchResponse.toMessage( Errors.NONE, 0, updates.entrySet().iterator(), Collections.emptyList())); } else { int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); int sessionEpoch; synchronized (session) { sessionEpoch = session.epoch; } if (sessionEpoch != expectedEpoch) { log.debug("Subsequent share session {} expected epoch {}, but got {}. Possible duplicate request.", session.key(), expectedEpoch, sessionEpoch); return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.INVALID_SHARE_SESSION_EPOCH, 0, Collections.emptyIterator(), Collections.emptyList())); } // Iterate over the update list using PartitionIterator. This will prune updates which don't need to be sent Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> partitionIterator = new PartitionIterator( updates.entrySet().iterator(), true); while (partitionIterator.hasNext()) { partitionIterator.next(); } log.debug("Subsequent share session context with session key {} returning {}", session.key(), partitionsToLogString(updates.keySet())); return new ShareFetchResponse(ShareFetchResponse.toMessage( Errors.NONE, 0, updates.entrySet().iterator(), Collections.emptyList())); } } @Override public ErroneousAndValidPartitionData getErroneousAndValidTopicIdPartitions() { if (! isSubsequent ) { return new ErroneousAndValidPartitionData(shareFetchData); } Map<TopicIdPartition, PartitionData> erroneous = new HashMap<>(); Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> valid = new HashMap<>(); // Take the session lock and iterate over all the cached partitions. synchronized (session) { session.partitionMap().forEach(cachedSharePartition -> { TopicIdPartition topicIdPartition = new TopicIdPartition(cachedSharePartition.topicId(), new TopicPartition(cachedSharePartition.topic(), cachedSharePartition.partition())); ShareFetchRequest.SharePartitionData reqData = cachedSharePartition.reqData(); if (topicIdPartition.topic() == null) { erroneous.put(topicIdPartition, ShareFetchResponse.partitionResponse(topicIdPartition, Errors.UNKNOWN_TOPIC_ID)); } else { valid.put(topicIdPartition, reqData); } }); return new ErroneousAndValidPartitionData(erroneous, valid); } } }
|
java
|
in this case, we need to perform a remove and then a mustAdd to maintain the correct order session.partitionMap().remove(cachedPart); session.partitionMap().mustAdd(cachedPart); } } else { if (updateShareContextAndRemoveUnselected) { iterator.remove(); } } } } return nextElement != null; } @Override public Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> next() { if (!hasNext()) throw new NoSuchElementException(); Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> element = nextElement; nextElement = null; return element; } @Override public void remove() { throw new UnsupportedOperationException(); } } @Override public int responseSize(LinkedHashMap<TopicIdPartition, PartitionData> updates, short version) { if (! <mask> <mask> <mask> <mask> <mask> ) return ShareFetchResponse.sizeOf(version, updates.entrySet().iterator()); synchronized (session) { int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); if (session.epoch != expectedEpoch) { return ShareFetchResponse.sizeOf(version, Collections.emptyIterator()); } // Pass the partition iterator which updates neither the share fetch context nor the partition map. return ShareFetchResponse.sizeOf(version, new PartitionIterator(updates.entrySet().iterator(), false)); } } @Override public ShareFetchResponse updateAndGenerateResponseData(String groupId, Uuid memberId, LinkedHashMap<TopicIdPartition, ShareFetchResponseData.PartitionData> updates) { if (! <mask> <mask> <mask> <mask> <mask> ) { return new ShareFetchResponse(ShareFetchResponse.toMessage( Errors.NONE, 0, updates.entrySet().iterator(), Collections.emptyList())); } else { int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); int sessionEpoch; synchronized (session) { sessionEpoch = session.epoch; } if (sessionEpoch != expectedEpoch) { log.debug("Subsequent share session {} expected epoch {}, but got {}. Possible duplicate request.", session.key(), expectedEpoch, sessionEpoch); return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.INVALID_SHARE_SESSION_EPOCH, 0, Collections.emptyIterator(), Collections.emptyList())); } // Iterate over the update list using PartitionIterator. This will prune updates which don't need to be sent Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> partitionIterator = new PartitionIterator( updates.entrySet().iterator(), true); while (partitionIterator.hasNext()) { partitionIterator.next(); } log.debug("Subsequent share session context with session key {} returning {}", session.key(), partitionsToLogString(updates.keySet())); return new ShareFetchResponse(ShareFetchResponse.toMessage( Errors.NONE, 0, updates.entrySet().iterator(), Collections.emptyList())); } } @Override public ErroneousAndValidPartitionData getErroneousAndValidTopicIdPartitions() { if (! <mask> <mask> <mask> <mask> <mask> ) { return new ErroneousAndValidPartitionData(shareFetchData); } Map<TopicIdPartition, PartitionData> erroneous = new HashMap<>(); Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> valid = new HashMap<>(); // Take the session lock and iterate over all the cached partitions. synchronized (session) { session.partitionMap().forEach(cachedSharePartition -> { TopicIdPartition topicIdPartition = new TopicIdPartition(cachedSharePartition.topicId(), new TopicPartition(cachedSharePartition.topic(), cachedSharePartition.partition())); ShareFetchRequest.SharePartitionData reqData = cachedSharePartition.reqData(); if (topicIdPartition.topic() == null) { erroneous.put(topicIdPartition, ShareFetchResponse.partitionResponse(topicIdPartition, Errors.UNKNOWN_TOPIC_ID)); } else { valid.put(topicIdPartition, reqData); } }); return new ErroneousAndValidPartitionData(erroneous, valid); } } }
|
in this case, we need to perform a remove and then a mustAdd to maintain the correct order session.partitionMap().remove(cachedPart); session.partitionMap().mustAdd(cachedPart); } } else { if (updateShareContextAndRemoveUnselected) { iterator.remove(); } } } } return nextElement != null; } @Override public Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> next() { if (!hasNext()) throw new NoSuchElementException(); Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> element = nextElement; nextElement = null; return element; } @Override public void remove() { throw new UnsupportedOperationException(); } } @Override public int responseSize(LinkedHashMap<TopicIdPartition, PartitionData> updates, short version) { if (! isSubsequent ) return ShareFetchResponse.sizeOf(version, updates.entrySet().iterator()); synchronized (session) { int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); if (session.epoch != expectedEpoch) { return ShareFetchResponse.sizeOf(version, Collections.emptyIterator()); } // Pass the partition iterator which updates neither the share fetch context nor the partition map. return ShareFetchResponse.sizeOf(version, new PartitionIterator(updates.entrySet().iterator(), false)); } } @Override public ShareFetchResponse updateAndGenerateResponseData(String groupId, Uuid memberId, LinkedHashMap<TopicIdPartition, ShareFetchResponseData.PartitionData> updates) { if (! isSubsequent ) { return new ShareFetchResponse(ShareFetchResponse.toMessage( Errors.NONE, 0, updates.entrySet().iterator(), Collections.emptyList())); } else { int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch()); int sessionEpoch; synchronized (session) { sessionEpoch = session.epoch; } if (sessionEpoch != expectedEpoch) { log.debug("Subsequent share session {} expected epoch {}, but got {}. Possible duplicate request.", session.key(), expectedEpoch, sessionEpoch); return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.INVALID_SHARE_SESSION_EPOCH, 0, Collections.emptyIterator(), Collections.emptyList())); } // Iterate over the update list using PartitionIterator. This will prune updates which don't need to be sent Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> partitionIterator = new PartitionIterator( updates.entrySet().iterator(), true); while (partitionIterator.hasNext()) { partitionIterator.next(); } log.debug("Subsequent share session context with session key {} returning {}", session.key(), partitionsToLogString(updates.keySet())); return new ShareFetchResponse(ShareFetchResponse.toMessage( Errors.NONE, 0, updates.entrySet().iterator(), Collections.emptyList())); } } @Override public ErroneousAndValidPartitionData getErroneousAndValidTopicIdPartitions() { if (! isSubsequent ) { return new ErroneousAndValidPartitionData(shareFetchData); } Map<TopicIdPartition, PartitionData> erroneous = new HashMap<>(); Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> valid = new HashMap<>(); // Take the session lock and iterate over all the cached partitions. synchronized (session) { session.partitionMap().forEach(cachedSharePartition -> { TopicIdPartition topicIdPartition = new TopicIdPartition(cachedSharePartition.topicId(), new TopicPartition(cachedSharePartition.topic(), cachedSharePartition.partition())); ShareFetchRequest.SharePartitionData reqData = cachedSharePartition.reqData(); if (topicIdPartition.topic() == null) { erroneous.put(topicIdPartition, ShareFetchResponse.partitionResponse(topicIdPartition, Errors.UNKNOWN_TOPIC_ID)); } else { valid.put(topicIdPartition, reqData); } }); return new ErroneousAndValidPartitionData(erroneous, valid); } } }
|
java
|
file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.scheduler; import org.apache.flink.runtime.clusterframework.types.AllocationID; import org.apache.flink.runtime.clusterframework.types.ResourceProfile; import org.apache.flink.runtime.clusterframework.types.SlotProfile; import org.apache.flink.runtime.clusterframework.types.SlotProfileTestingUtils; import org.apache.flink.runtime.executiongraph.ExecutionAttemptID; import org.apache.flink.runtime.jobmanager.scheduler.SlotSharingGroup; import org.apache.flink.runtime.jobmaster.LogicalSlot; import org.apache.flink.runtime.jobmaster.SlotRequestId; import org.apache.flink.runtime.jobmaster.TestingPayload; import org.apache.flink.runtime.jobmaster.slotpool.DummyPayload; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequest; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequestBulk; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequestBulkChecker; import org.apache.flink.runtime.scheduler.SharedSlotProfileRetriever.SharedSlotProfileRetrieverFactory; import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID; import org.apache.flink.util.FlinkException; import org.apache.flink.util.function.BiConsumerWithException; import org.junit.jupiter.api.Test; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createExecutionAttemptId; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createRandomExecutionVertexId; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** Test suite for {@link SlotSharingExecutionSlotAllocator}. */ class SlotSharingExecutionSlotAllocatorTest { private static final Duration ALLOCATION_TIMEOUT = Duration.ofMillis(100L); private static final ResourceProfile RESOURCE_PROFILE = ResourceProfile.fromResources(3, 5); private static final ExecutionVertexID EV1 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV2 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV3 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV4 = createRandomExecutionVertexId(); @Test void testSlotProfileRequestAskedBulkAndGroup() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).build(); ExecutionSlotSharingGroup executionSlotSharingGroup = context.getSlotSharingStrategy().getExecutionSlotSharingGroup(EV1); context.allocateSlotsFor(EV1, EV2); List<Set<ExecutionVertexID>> askedBulks = context.getSlotProfileRetrieverFactory().getAskedBulks(); assertThat(askedBulks).hasSize(1); assertThat(askedBulks.get(0)).containsExactlyInAnyOrder(EV1, EV2); assertThat(context.getSlotProfileRetrieverFactory().getAskedGroups()) .containsExactly(executionSlotSharingGroup); } @Test void testSlotRequestProfile() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2, EV3).build(); ResourceProfile physicalsSlotResourceProfile = RESOURCE_PROFILE.multiply(3); context.allocateSlotsFor(EV1, EV2); Optional<PhysicalSlotRequest> slotRequest = context.getSlotProvider().getRequests().values().stream().findFirst(); assertThat(slotRequest).isPresent(); assertThat(slotRequest.get().getSlotProfile().getPhysicalSlotResourceProfile()) .isEqualTo(physicalsSlotResourceProfile); } @Test void testAllocatePhysicalSlotForNewSharedSlot() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).addGroup(EV3, EV4).build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV1, EV2, EV3, EV4); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); assertThat(assignIds).containsExactlyInAnyOrder(EV1, EV2, EV3, EV4); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testAllocateLogicalSlotFromAvailableSharedSlot() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).build(); context.allocateSlotsFor(EV1); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV2); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); // execution 0 from the first allocateSlotsFor call and execution 1 from the second // allocateSlotsFor call // share a slot, therefore only one physical slot allocation should happen assertThat(assignIds).containsExactly(EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); } @Test void testDuplicateAllocationDoesNotRecreateLogicalSlotFuture() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1).build(); ExecutionSlotAssignment assignment1 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); ExecutionSlotAssignment assignment2 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); assertThat(assignment1.getLogicalSlotFuture().get()) .isSameAs(assignment2.getLogicalSlotFuture().get()); } @Test void testFailedPhysicalSlotRequestFailsLogicalSlotFuturesAndRemovesSharedSlot() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1) .withPhysicalSlotProvider( TestingPhysicalSlotProvider .createWithoutImmediatePhysicalSlotCreation()) .build(); CompletableFuture<LogicalSlot> logicalSlotFuture = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1) .getLogicalSlotFuture(); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(logicalSlotFuture).isNotDone(); context.getSlotProvider() .getResponses() .get(slotRequestId) .completeExceptionally(new Throwable()); assertThat(logicalSlotFuture).isCompletedExceptionally(); // next allocation allocates new shared slot context.allocateSlotsFor(EV1); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testSlotWillBeOccupiedIndefinitelyFalse() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(false); } @Test void testSlotWillBeOccupiedIndefinitelyTrue() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(true); } private static void testSlotWillBeOccupiedIndefinitely(boolean slotWillBeOccupiedIndefinitely) throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1) .setSlotWillBeOccupiedIndefinitely(slotWillBeOccupiedIndefinitely) .build(); context.allocateSlotsFor(EV1); PhysicalSlotRequest slotRequest = context.getSlotProvider().getFirstRequestOrFail(); assertThat(slotRequest.willSlotBeOccupiedIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); TestingPhysicalSlot physicalSlot = context.getSlotProvider().getResponses().get(slotRequest.getSlotRequestId()).get(); assertThat(physicalSlot.getPayload()).isNotNull(); assertThat(physicalSlot.getPayload().willOccupySlotIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); } @Test void testReturningLogicalSlotsRemovesSharedSlot() throws
|
file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.scheduler; import org.apache.flink.runtime.clusterframework.types.AllocationID; import org.apache.flink.runtime.clusterframework.types.ResourceProfile; import org.apache.flink.runtime.clusterframework.types.SlotProfile; import org.apache.flink.runtime.clusterframework.types.SlotProfileTestingUtils; import org.apache.flink.runtime.executiongraph.ExecutionAttemptID; import org.apache.flink.runtime.jobmanager.scheduler.SlotSharingGroup; import org.apache.flink.runtime.jobmaster.LogicalSlot; import org.apache.flink.runtime.jobmaster.SlotRequestId; import org.apache.flink.runtime.jobmaster.TestingPayload; import org.apache.flink.runtime.jobmaster.slotpool.DummyPayload; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequest; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequestBulk; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequestBulkChecker; import org.apache.flink.runtime.scheduler.SharedSlotProfileRetriever.SharedSlotProfileRetrieverFactory; import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID; import org.apache.flink.util.FlinkException; import org.apache.flink.util.function.BiConsumerWithException; import org.junit.jupiter.api.Test; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createExecutionAttemptId; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createRandomExecutionVertexId; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** Test suite for {@link SlotSharingExecutionSlotAllocator}. */ class SlotSharingExecutionSlotAllocatorTest { private static final Duration ALLOCATION_TIMEOUT = Duration.ofMillis(100L); private static final ResourceProfile RESOURCE_PROFILE = ResourceProfile.fromResources(3, 5); private static final ExecutionVertexID EV1 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV2 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV3 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV4 = createRandomExecutionVertexId(); @Test void testSlotProfileRequestAskedBulkAndGroup() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).build(); ExecutionSlotSharingGroup executionSlotSharingGroup = context.getSlotSharingStrategy().getExecutionSlotSharingGroup(EV1); context.allocateSlotsFor(EV1, EV2); List<Set<ExecutionVertexID>> askedBulks = context.getSlotProfileRetrieverFactory().getAskedBulks(); assertThat(askedBulks).hasSize(1); assertThat(askedBulks.get(0)).containsExactlyInAnyOrder(EV1, EV2); assertThat(context.getSlotProfileRetrieverFactory().getAskedGroups()) .containsExactly(executionSlotSharingGroup); } @Test void testSlotRequestProfile() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2, EV3).build(); ResourceProfile physicalsSlotResourceProfile = RESOURCE_PROFILE.multiply(3); context.allocateSlotsFor(EV1, EV2); Optional<PhysicalSlotRequest> slotRequest = context.getSlotProvider().getRequests().values().stream().findFirst(); assertThat(slotRequest).isPresent(); assertThat(slotRequest.get().getSlotProfile().getPhysicalSlotResourceProfile()) .isEqualTo(physicalsSlotResourceProfile); } @Test void testAllocatePhysicalSlotForNewSharedSlot() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).addGroup(EV3, EV4).build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV1, EV2, EV3, EV4); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); assertThat(assignIds).containsExactlyInAnyOrder(EV1, EV2, EV3, EV4); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testAllocateLogicalSlotFromAvailableSharedSlot() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).build(); context.allocateSlotsFor(EV1); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV2); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); // execution 0 from the first allocateSlotsFor call and execution 1 from the second // allocateSlotsFor call // share a slot, therefore only one physical slot allocation should happen assertThat(assignIds).containsExactly(EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); } @Test void testDuplicateAllocationDoesNotRecreateLogicalSlotFuture() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1).build(); ExecutionSlotAssignment assignment1 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); ExecutionSlotAssignment assignment2 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); assertThat(assignment1.getLogicalSlotFuture().get()) .isSameAs(assignment2.getLogicalSlotFuture().get()); } @Test void testFailedPhysicalSlotRequestFailsLogicalSlotFuturesAndRemovesSharedSlot() { AllocationContext context = AllocationContext. newBuilder () .addGroup(EV1) .withPhysicalSlotProvider( TestingPhysicalSlotProvider .createWithoutImmediatePhysicalSlotCreation()) .build(); CompletableFuture<LogicalSlot> logicalSlotFuture = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1) .getLogicalSlotFuture(); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(logicalSlotFuture).isNotDone(); context.getSlotProvider() .getResponses() .get(slotRequestId) .completeExceptionally(new Throwable()); assertThat(logicalSlotFuture).isCompletedExceptionally(); // next allocation allocates new shared slot context.allocateSlotsFor(EV1); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testSlotWillBeOccupiedIndefinitelyFalse() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(false); } @Test void testSlotWillBeOccupiedIndefinitelyTrue() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(true); } private static void testSlotWillBeOccupiedIndefinitely(boolean slotWillBeOccupiedIndefinitely) throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. newBuilder () .addGroup(EV1) .setSlotWillBeOccupiedIndefinitely(slotWillBeOccupiedIndefinitely) .build(); context.allocateSlotsFor(EV1); PhysicalSlotRequest slotRequest = context.getSlotProvider().getFirstRequestOrFail(); assertThat(slotRequest.willSlotBeOccupiedIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); TestingPhysicalSlot physicalSlot = context.getSlotProvider().getResponses().get(slotRequest.getSlotRequestId()).get(); assertThat(physicalSlot.getPayload()).isNotNull(); assertThat(physicalSlot.getPayload().willOccupySlotIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); } @Test void testReturningLogicalSlotsRemovesSharedSlot() throws
|
java
|
(the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.scheduler; import org.apache.flink.runtime.clusterframework.types.AllocationID; import org.apache.flink.runtime.clusterframework.types.ResourceProfile; import org.apache.flink.runtime.clusterframework.types.SlotProfile; import org.apache.flink.runtime.clusterframework.types.SlotProfileTestingUtils; import org.apache.flink.runtime.executiongraph.ExecutionAttemptID; import org.apache.flink.runtime.jobmanager.scheduler.SlotSharingGroup; import org.apache.flink.runtime.jobmaster.LogicalSlot; import org.apache.flink.runtime.jobmaster.SlotRequestId; import org.apache.flink.runtime.jobmaster.TestingPayload; import org.apache.flink.runtime.jobmaster.slotpool.DummyPayload; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequest; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequestBulk; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequestBulkChecker; import org.apache.flink.runtime.scheduler.SharedSlotProfileRetriever.SharedSlotProfileRetrieverFactory; import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID; import org.apache.flink.util.FlinkException; import org.apache.flink.util.function.BiConsumerWithException; import org.junit.jupiter.api.Test; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createExecutionAttemptId; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createRandomExecutionVertexId; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** Test suite for {@link SlotSharingExecutionSlotAllocator}. */ class SlotSharingExecutionSlotAllocatorTest { private static final Duration ALLOCATION_TIMEOUT = Duration.ofMillis(100L); private static final ResourceProfile RESOURCE_PROFILE = ResourceProfile.fromResources(3, 5); private static final ExecutionVertexID EV1 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV2 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV3 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV4 = createRandomExecutionVertexId(); @Test void testSlotProfileRequestAskedBulkAndGroup() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).build(); ExecutionSlotSharingGroup executionSlotSharingGroup = context.getSlotSharingStrategy().getExecutionSlotSharingGroup(EV1); context.allocateSlotsFor(EV1, EV2); List<Set<ExecutionVertexID>> askedBulks = context.getSlotProfileRetrieverFactory().getAskedBulks(); assertThat(askedBulks).hasSize(1); assertThat(askedBulks.get(0)).containsExactlyInAnyOrder(EV1, EV2); assertThat(context.getSlotProfileRetrieverFactory().getAskedGroups()) .containsExactly(executionSlotSharingGroup); } @Test void testSlotRequestProfile() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2, EV3).build(); ResourceProfile physicalsSlotResourceProfile = RESOURCE_PROFILE.multiply(3); context.allocateSlotsFor(EV1, EV2); Optional<PhysicalSlotRequest> slotRequest = context.getSlotProvider().getRequests().values().stream().findFirst(); assertThat(slotRequest).isPresent(); assertThat(slotRequest.get().getSlotProfile().getPhysicalSlotResourceProfile()) .isEqualTo(physicalsSlotResourceProfile); } @Test void testAllocatePhysicalSlotForNewSharedSlot() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).addGroup(EV3, EV4).build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV1, EV2, EV3, EV4); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); assertThat(assignIds).containsExactlyInAnyOrder(EV1, EV2, EV3, EV4); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testAllocateLogicalSlotFromAvailableSharedSlot() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).build(); context.allocateSlotsFor(EV1); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV2); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); // execution 0 from the first allocateSlotsFor call and execution 1 from the second // allocateSlotsFor call // share a slot, therefore only one physical slot allocation should happen assertThat(assignIds).containsExactly(EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); } @Test void testDuplicateAllocationDoesNotRecreateLogicalSlotFuture() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1).build(); ExecutionSlotAssignment assignment1 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); ExecutionSlotAssignment assignment2 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); assertThat(assignment1.getLogicalSlotFuture().get()) .isSameAs(assignment2.getLogicalSlotFuture().get()); } @Test void testFailedPhysicalSlotRequestFailsLogicalSlotFuturesAndRemovesSharedSlot() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1) .withPhysicalSlotProvider( TestingPhysicalSlotProvider .createWithoutImmediatePhysicalSlotCreation()) .build(); CompletableFuture<LogicalSlot> logicalSlotFuture = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1) .getLogicalSlotFuture(); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(logicalSlotFuture).isNotDone(); context.getSlotProvider() .getResponses() .get(slotRequestId) .completeExceptionally(new Throwable()); assertThat(logicalSlotFuture).isCompletedExceptionally(); // next allocation allocates new shared slot context.allocateSlotsFor(EV1); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testSlotWillBeOccupiedIndefinitelyFalse() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(false); } @Test void testSlotWillBeOccupiedIndefinitelyTrue() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(true); } private static void testSlotWillBeOccupiedIndefinitely(boolean slotWillBeOccupiedIndefinitely) throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1) .setSlotWillBeOccupiedIndefinitely(slotWillBeOccupiedIndefinitely) .build(); context.allocateSlotsFor(EV1); PhysicalSlotRequest slotRequest = context.getSlotProvider().getFirstRequestOrFail(); assertThat(slotRequest.willSlotBeOccupiedIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); TestingPhysicalSlot physicalSlot = context.getSlotProvider().getResponses().get(slotRequest.getSlotRequestId()).get(); assertThat(physicalSlot.getPayload()).isNotNull(); assertThat(physicalSlot.getPayload().willOccupySlotIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); } @Test void testReturningLogicalSlotsRemovesSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, true, (context, assignment) -> assignment.getLogicalSlotFuture().get().releaseSlot(null)); } @Test void testLogicalSlotCancelsPhysicalSlotRequestAndRemovesSharedSlot() throws Exception { //
|
(the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.scheduler; import org.apache.flink.runtime.clusterframework.types.AllocationID; import org.apache.flink.runtime.clusterframework.types.ResourceProfile; import org.apache.flink.runtime.clusterframework.types.SlotProfile; import org.apache.flink.runtime.clusterframework.types.SlotProfileTestingUtils; import org.apache.flink.runtime.executiongraph.ExecutionAttemptID; import org.apache.flink.runtime.jobmanager.scheduler.SlotSharingGroup; import org.apache.flink.runtime.jobmaster.LogicalSlot; import org.apache.flink.runtime.jobmaster.SlotRequestId; import org.apache.flink.runtime.jobmaster.TestingPayload; import org.apache.flink.runtime.jobmaster.slotpool.DummyPayload; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequest; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequestBulk; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequestBulkChecker; import org.apache.flink.runtime.scheduler.SharedSlotProfileRetriever.SharedSlotProfileRetrieverFactory; import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID; import org.apache.flink.util.FlinkException; import org.apache.flink.util.function.BiConsumerWithException; import org.junit.jupiter.api.Test; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createExecutionAttemptId; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createRandomExecutionVertexId; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** Test suite for {@link SlotSharingExecutionSlotAllocator}. */ class SlotSharingExecutionSlotAllocatorTest { private static final Duration ALLOCATION_TIMEOUT = Duration.ofMillis(100L); private static final ResourceProfile RESOURCE_PROFILE = ResourceProfile.fromResources(3, 5); private static final ExecutionVertexID EV1 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV2 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV3 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV4 = createRandomExecutionVertexId(); @Test void testSlotProfileRequestAskedBulkAndGroup() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).build(); ExecutionSlotSharingGroup executionSlotSharingGroup = context.getSlotSharingStrategy().getExecutionSlotSharingGroup(EV1); context.allocateSlotsFor(EV1, EV2); List<Set<ExecutionVertexID>> askedBulks = context.getSlotProfileRetrieverFactory().getAskedBulks(); assertThat(askedBulks).hasSize(1); assertThat(askedBulks.get(0)).containsExactlyInAnyOrder(EV1, EV2); assertThat(context.getSlotProfileRetrieverFactory().getAskedGroups()) .containsExactly(executionSlotSharingGroup); } @Test void testSlotRequestProfile() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2, EV3).build(); ResourceProfile physicalsSlotResourceProfile = RESOURCE_PROFILE.multiply(3); context.allocateSlotsFor(EV1, EV2); Optional<PhysicalSlotRequest> slotRequest = context.getSlotProvider().getRequests().values().stream().findFirst(); assertThat(slotRequest).isPresent(); assertThat(slotRequest.get().getSlotProfile().getPhysicalSlotResourceProfile()) .isEqualTo(physicalsSlotResourceProfile); } @Test void testAllocatePhysicalSlotForNewSharedSlot() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).addGroup(EV3, EV4).build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV1, EV2, EV3, EV4); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); assertThat(assignIds).containsExactlyInAnyOrder(EV1, EV2, EV3, EV4); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testAllocateLogicalSlotFromAvailableSharedSlot() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).build(); context.allocateSlotsFor(EV1); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV2); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); // execution 0 from the first allocateSlotsFor call and execution 1 from the second // allocateSlotsFor call // share a slot, therefore only one physical slot allocation should happen assertThat(assignIds).containsExactly(EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); } @Test void testDuplicateAllocationDoesNotRecreateLogicalSlotFuture() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1).build(); ExecutionSlotAssignment assignment1 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); ExecutionSlotAssignment assignment2 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); assertThat(assignment1.getLogicalSlotFuture().get()) .isSameAs(assignment2.getLogicalSlotFuture().get()); } @Test void testFailedPhysicalSlotRequestFailsLogicalSlotFuturesAndRemovesSharedSlot() { AllocationContext context = AllocationContext. newBuilder () .addGroup(EV1) .withPhysicalSlotProvider( TestingPhysicalSlotProvider .createWithoutImmediatePhysicalSlotCreation()) .build(); CompletableFuture<LogicalSlot> logicalSlotFuture = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1) .getLogicalSlotFuture(); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(logicalSlotFuture).isNotDone(); context.getSlotProvider() .getResponses() .get(slotRequestId) .completeExceptionally(new Throwable()); assertThat(logicalSlotFuture).isCompletedExceptionally(); // next allocation allocates new shared slot context.allocateSlotsFor(EV1); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testSlotWillBeOccupiedIndefinitelyFalse() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(false); } @Test void testSlotWillBeOccupiedIndefinitelyTrue() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(true); } private static void testSlotWillBeOccupiedIndefinitely(boolean slotWillBeOccupiedIndefinitely) throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. newBuilder () .addGroup(EV1) .setSlotWillBeOccupiedIndefinitely(slotWillBeOccupiedIndefinitely) .build(); context.allocateSlotsFor(EV1); PhysicalSlotRequest slotRequest = context.getSlotProvider().getFirstRequestOrFail(); assertThat(slotRequest.willSlotBeOccupiedIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); TestingPhysicalSlot physicalSlot = context.getSlotProvider().getResponses().get(slotRequest.getSlotRequestId()).get(); assertThat(physicalSlot.getPayload()).isNotNull(); assertThat(physicalSlot.getPayload().willOccupySlotIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); } @Test void testReturningLogicalSlotsRemovesSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, true, (context, assignment) -> assignment.getLogicalSlotFuture().get().releaseSlot(null)); } @Test void testLogicalSlotCancelsPhysicalSlotRequestAndRemovesSharedSlot() throws Exception { //
|
java
|
* http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.scheduler; import org.apache.flink.runtime.clusterframework.types.AllocationID; import org.apache.flink.runtime.clusterframework.types.ResourceProfile; import org.apache.flink.runtime.clusterframework.types.SlotProfile; import org.apache.flink.runtime.clusterframework.types.SlotProfileTestingUtils; import org.apache.flink.runtime.executiongraph.ExecutionAttemptID; import org.apache.flink.runtime.jobmanager.scheduler.SlotSharingGroup; import org.apache.flink.runtime.jobmaster.LogicalSlot; import org.apache.flink.runtime.jobmaster.SlotRequestId; import org.apache.flink.runtime.jobmaster.TestingPayload; import org.apache.flink.runtime.jobmaster.slotpool.DummyPayload; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequest; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequestBulk; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequestBulkChecker; import org.apache.flink.runtime.scheduler.SharedSlotProfileRetriever.SharedSlotProfileRetrieverFactory; import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID; import org.apache.flink.util.FlinkException; import org.apache.flink.util.function.BiConsumerWithException; import org.junit.jupiter.api.Test; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createExecutionAttemptId; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createRandomExecutionVertexId; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** Test suite for {@link SlotSharingExecutionSlotAllocator}. */ class SlotSharingExecutionSlotAllocatorTest { private static final Duration ALLOCATION_TIMEOUT = Duration.ofMillis(100L); private static final ResourceProfile RESOURCE_PROFILE = ResourceProfile.fromResources(3, 5); private static final ExecutionVertexID EV1 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV2 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV3 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV4 = createRandomExecutionVertexId(); @Test void testSlotProfileRequestAskedBulkAndGroup() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).build(); ExecutionSlotSharingGroup executionSlotSharingGroup = context.getSlotSharingStrategy().getExecutionSlotSharingGroup(EV1); context.allocateSlotsFor(EV1, EV2); List<Set<ExecutionVertexID>> askedBulks = context.getSlotProfileRetrieverFactory().getAskedBulks(); assertThat(askedBulks).hasSize(1); assertThat(askedBulks.get(0)).containsExactlyInAnyOrder(EV1, EV2); assertThat(context.getSlotProfileRetrieverFactory().getAskedGroups()) .containsExactly(executionSlotSharingGroup); } @Test void testSlotRequestProfile() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2, EV3).build(); ResourceProfile physicalsSlotResourceProfile = RESOURCE_PROFILE.multiply(3); context.allocateSlotsFor(EV1, EV2); Optional<PhysicalSlotRequest> slotRequest = context.getSlotProvider().getRequests().values().stream().findFirst(); assertThat(slotRequest).isPresent(); assertThat(slotRequest.get().getSlotProfile().getPhysicalSlotResourceProfile()) .isEqualTo(physicalsSlotResourceProfile); } @Test void testAllocatePhysicalSlotForNewSharedSlot() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).addGroup(EV3, EV4).build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV1, EV2, EV3, EV4); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); assertThat(assignIds).containsExactlyInAnyOrder(EV1, EV2, EV3, EV4); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testAllocateLogicalSlotFromAvailableSharedSlot() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).build(); context.allocateSlotsFor(EV1); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV2); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); // execution 0 from the first allocateSlotsFor call and execution 1 from the second // allocateSlotsFor call // share a slot, therefore only one physical slot allocation should happen assertThat(assignIds).containsExactly(EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); } @Test void testDuplicateAllocationDoesNotRecreateLogicalSlotFuture() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1).build(); ExecutionSlotAssignment assignment1 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); ExecutionSlotAssignment assignment2 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); assertThat(assignment1.getLogicalSlotFuture().get()) .isSameAs(assignment2.getLogicalSlotFuture().get()); } @Test void testFailedPhysicalSlotRequestFailsLogicalSlotFuturesAndRemovesSharedSlot() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1) .withPhysicalSlotProvider( TestingPhysicalSlotProvider .createWithoutImmediatePhysicalSlotCreation()) .build(); CompletableFuture<LogicalSlot> logicalSlotFuture = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1) .getLogicalSlotFuture(); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(logicalSlotFuture).isNotDone(); context.getSlotProvider() .getResponses() .get(slotRequestId) .completeExceptionally(new Throwable()); assertThat(logicalSlotFuture).isCompletedExceptionally(); // next allocation allocates new shared slot context.allocateSlotsFor(EV1); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testSlotWillBeOccupiedIndefinitelyFalse() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(false); } @Test void testSlotWillBeOccupiedIndefinitelyTrue() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(true); } private static void testSlotWillBeOccupiedIndefinitely(boolean slotWillBeOccupiedIndefinitely) throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1) .setSlotWillBeOccupiedIndefinitely(slotWillBeOccupiedIndefinitely) .build(); context.allocateSlotsFor(EV1); PhysicalSlotRequest slotRequest = context.getSlotProvider().getFirstRequestOrFail(); assertThat(slotRequest.willSlotBeOccupiedIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); TestingPhysicalSlot physicalSlot = context.getSlotProvider().getResponses().get(slotRequest.getSlotRequestId()).get(); assertThat(physicalSlot.getPayload()).isNotNull(); assertThat(physicalSlot.getPayload().willOccupySlotIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); } @Test void testReturningLogicalSlotsRemovesSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, true, (context, assignment) -> assignment.getLogicalSlotFuture().get().releaseSlot(null)); } @Test void testLogicalSlotCancelsPhysicalSlotRequestAndRemovesSharedSlot() throws Exception { // physical slot request is not completed and does not complete logical requests testLogicalSlotRequestCancellationOrRelease( true, true, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assertThatThrownBy( () -> { context.getAllocator() .cancel(assignment.getExecutionAttemptId());
|
* http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.scheduler; import org.apache.flink.runtime.clusterframework.types.AllocationID; import org.apache.flink.runtime.clusterframework.types.ResourceProfile; import org.apache.flink.runtime.clusterframework.types.SlotProfile; import org.apache.flink.runtime.clusterframework.types.SlotProfileTestingUtils; import org.apache.flink.runtime.executiongraph.ExecutionAttemptID; import org.apache.flink.runtime.jobmanager.scheduler.SlotSharingGroup; import org.apache.flink.runtime.jobmaster.LogicalSlot; import org.apache.flink.runtime.jobmaster.SlotRequestId; import org.apache.flink.runtime.jobmaster.TestingPayload; import org.apache.flink.runtime.jobmaster.slotpool.DummyPayload; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequest; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequestBulk; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequestBulkChecker; import org.apache.flink.runtime.scheduler.SharedSlotProfileRetriever.SharedSlotProfileRetrieverFactory; import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID; import org.apache.flink.util.FlinkException; import org.apache.flink.util.function.BiConsumerWithException; import org.junit.jupiter.api.Test; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createExecutionAttemptId; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createRandomExecutionVertexId; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** Test suite for {@link SlotSharingExecutionSlotAllocator}. */ class SlotSharingExecutionSlotAllocatorTest { private static final Duration ALLOCATION_TIMEOUT = Duration.ofMillis(100L); private static final ResourceProfile RESOURCE_PROFILE = ResourceProfile.fromResources(3, 5); private static final ExecutionVertexID EV1 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV2 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV3 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV4 = createRandomExecutionVertexId(); @Test void testSlotProfileRequestAskedBulkAndGroup() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).build(); ExecutionSlotSharingGroup executionSlotSharingGroup = context.getSlotSharingStrategy().getExecutionSlotSharingGroup(EV1); context.allocateSlotsFor(EV1, EV2); List<Set<ExecutionVertexID>> askedBulks = context.getSlotProfileRetrieverFactory().getAskedBulks(); assertThat(askedBulks).hasSize(1); assertThat(askedBulks.get(0)).containsExactlyInAnyOrder(EV1, EV2); assertThat(context.getSlotProfileRetrieverFactory().getAskedGroups()) .containsExactly(executionSlotSharingGroup); } @Test void testSlotRequestProfile() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2, EV3).build(); ResourceProfile physicalsSlotResourceProfile = RESOURCE_PROFILE.multiply(3); context.allocateSlotsFor(EV1, EV2); Optional<PhysicalSlotRequest> slotRequest = context.getSlotProvider().getRequests().values().stream().findFirst(); assertThat(slotRequest).isPresent(); assertThat(slotRequest.get().getSlotProfile().getPhysicalSlotResourceProfile()) .isEqualTo(physicalsSlotResourceProfile); } @Test void testAllocatePhysicalSlotForNewSharedSlot() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).addGroup(EV3, EV4).build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV1, EV2, EV3, EV4); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); assertThat(assignIds).containsExactlyInAnyOrder(EV1, EV2, EV3, EV4); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testAllocateLogicalSlotFromAvailableSharedSlot() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).build(); context.allocateSlotsFor(EV1); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV2); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); // execution 0 from the first allocateSlotsFor call and execution 1 from the second // allocateSlotsFor call // share a slot, therefore only one physical slot allocation should happen assertThat(assignIds).containsExactly(EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); } @Test void testDuplicateAllocationDoesNotRecreateLogicalSlotFuture() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1).build(); ExecutionSlotAssignment assignment1 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); ExecutionSlotAssignment assignment2 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); assertThat(assignment1.getLogicalSlotFuture().get()) .isSameAs(assignment2.getLogicalSlotFuture().get()); } @Test void testFailedPhysicalSlotRequestFailsLogicalSlotFuturesAndRemovesSharedSlot() { AllocationContext context = AllocationContext. newBuilder () .addGroup(EV1) .withPhysicalSlotProvider( TestingPhysicalSlotProvider .createWithoutImmediatePhysicalSlotCreation()) .build(); CompletableFuture<LogicalSlot> logicalSlotFuture = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1) .getLogicalSlotFuture(); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(logicalSlotFuture).isNotDone(); context.getSlotProvider() .getResponses() .get(slotRequestId) .completeExceptionally(new Throwable()); assertThat(logicalSlotFuture).isCompletedExceptionally(); // next allocation allocates new shared slot context.allocateSlotsFor(EV1); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testSlotWillBeOccupiedIndefinitelyFalse() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(false); } @Test void testSlotWillBeOccupiedIndefinitelyTrue() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(true); } private static void testSlotWillBeOccupiedIndefinitely(boolean slotWillBeOccupiedIndefinitely) throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. newBuilder () .addGroup(EV1) .setSlotWillBeOccupiedIndefinitely(slotWillBeOccupiedIndefinitely) .build(); context.allocateSlotsFor(EV1); PhysicalSlotRequest slotRequest = context.getSlotProvider().getFirstRequestOrFail(); assertThat(slotRequest.willSlotBeOccupiedIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); TestingPhysicalSlot physicalSlot = context.getSlotProvider().getResponses().get(slotRequest.getSlotRequestId()).get(); assertThat(physicalSlot.getPayload()).isNotNull(); assertThat(physicalSlot.getPayload().willOccupySlotIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); } @Test void testReturningLogicalSlotsRemovesSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, true, (context, assignment) -> assignment.getLogicalSlotFuture().get().releaseSlot(null)); } @Test void testLogicalSlotCancelsPhysicalSlotRequestAndRemovesSharedSlot() throws Exception { // physical slot request is not completed and does not complete logical requests testLogicalSlotRequestCancellationOrRelease( true, true, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assertThatThrownBy( () -> { context.getAllocator() .cancel(assignment.getExecutionAttemptId());
|
java
|
OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.scheduler; import org.apache.flink.runtime.clusterframework.types.AllocationID; import org.apache.flink.runtime.clusterframework.types.ResourceProfile; import org.apache.flink.runtime.clusterframework.types.SlotProfile; import org.apache.flink.runtime.clusterframework.types.SlotProfileTestingUtils; import org.apache.flink.runtime.executiongraph.ExecutionAttemptID; import org.apache.flink.runtime.jobmanager.scheduler.SlotSharingGroup; import org.apache.flink.runtime.jobmaster.LogicalSlot; import org.apache.flink.runtime.jobmaster.SlotRequestId; import org.apache.flink.runtime.jobmaster.TestingPayload; import org.apache.flink.runtime.jobmaster.slotpool.DummyPayload; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequest; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequestBulk; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequestBulkChecker; import org.apache.flink.runtime.scheduler.SharedSlotProfileRetriever.SharedSlotProfileRetrieverFactory; import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID; import org.apache.flink.util.FlinkException; import org.apache.flink.util.function.BiConsumerWithException; import org.junit.jupiter.api.Test; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createExecutionAttemptId; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createRandomExecutionVertexId; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** Test suite for {@link SlotSharingExecutionSlotAllocator}. */ class SlotSharingExecutionSlotAllocatorTest { private static final Duration ALLOCATION_TIMEOUT = Duration.ofMillis(100L); private static final ResourceProfile RESOURCE_PROFILE = ResourceProfile.fromResources(3, 5); private static final ExecutionVertexID EV1 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV2 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV3 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV4 = createRandomExecutionVertexId(); @Test void testSlotProfileRequestAskedBulkAndGroup() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).build(); ExecutionSlotSharingGroup executionSlotSharingGroup = context.getSlotSharingStrategy().getExecutionSlotSharingGroup(EV1); context.allocateSlotsFor(EV1, EV2); List<Set<ExecutionVertexID>> askedBulks = context.getSlotProfileRetrieverFactory().getAskedBulks(); assertThat(askedBulks).hasSize(1); assertThat(askedBulks.get(0)).containsExactlyInAnyOrder(EV1, EV2); assertThat(context.getSlotProfileRetrieverFactory().getAskedGroups()) .containsExactly(executionSlotSharingGroup); } @Test void testSlotRequestProfile() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2, EV3).build(); ResourceProfile physicalsSlotResourceProfile = RESOURCE_PROFILE.multiply(3); context.allocateSlotsFor(EV1, EV2); Optional<PhysicalSlotRequest> slotRequest = context.getSlotProvider().getRequests().values().stream().findFirst(); assertThat(slotRequest).isPresent(); assertThat(slotRequest.get().getSlotProfile().getPhysicalSlotResourceProfile()) .isEqualTo(physicalsSlotResourceProfile); } @Test void testAllocatePhysicalSlotForNewSharedSlot() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).addGroup(EV3, EV4).build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV1, EV2, EV3, EV4); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); assertThat(assignIds).containsExactlyInAnyOrder(EV1, EV2, EV3, EV4); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testAllocateLogicalSlotFromAvailableSharedSlot() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).build(); context.allocateSlotsFor(EV1); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV2); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); // execution 0 from the first allocateSlotsFor call and execution 1 from the second // allocateSlotsFor call // share a slot, therefore only one physical slot allocation should happen assertThat(assignIds).containsExactly(EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); } @Test void testDuplicateAllocationDoesNotRecreateLogicalSlotFuture() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1).build(); ExecutionSlotAssignment assignment1 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); ExecutionSlotAssignment assignment2 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); assertThat(assignment1.getLogicalSlotFuture().get()) .isSameAs(assignment2.getLogicalSlotFuture().get()); } @Test void testFailedPhysicalSlotRequestFailsLogicalSlotFuturesAndRemovesSharedSlot() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1) .withPhysicalSlotProvider( TestingPhysicalSlotProvider .createWithoutImmediatePhysicalSlotCreation()) .build(); CompletableFuture<LogicalSlot> logicalSlotFuture = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1) .getLogicalSlotFuture(); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(logicalSlotFuture).isNotDone(); context.getSlotProvider() .getResponses() .get(slotRequestId) .completeExceptionally(new Throwable()); assertThat(logicalSlotFuture).isCompletedExceptionally(); // next allocation allocates new shared slot context.allocateSlotsFor(EV1); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testSlotWillBeOccupiedIndefinitelyFalse() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(false); } @Test void testSlotWillBeOccupiedIndefinitelyTrue() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(true); } private static void testSlotWillBeOccupiedIndefinitely(boolean slotWillBeOccupiedIndefinitely) throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1) .setSlotWillBeOccupiedIndefinitely(slotWillBeOccupiedIndefinitely) .build(); context.allocateSlotsFor(EV1); PhysicalSlotRequest slotRequest = context.getSlotProvider().getFirstRequestOrFail(); assertThat(slotRequest.willSlotBeOccupiedIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); TestingPhysicalSlot physicalSlot = context.getSlotProvider().getResponses().get(slotRequest.getSlotRequestId()).get(); assertThat(physicalSlot.getPayload()).isNotNull(); assertThat(physicalSlot.getPayload().willOccupySlotIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); } @Test void testReturningLogicalSlotsRemovesSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, true, (context, assignment) -> assignment.getLogicalSlotFuture().get().releaseSlot(null)); } @Test void testLogicalSlotCancelsPhysicalSlotRequestAndRemovesSharedSlot() throws Exception { // physical slot request is not completed and does not complete logical requests testLogicalSlotRequestCancellationOrRelease( true, true, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assertThatThrownBy( () -> { context.getAllocator() .cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }) .as("The logical future must finish with the cancellation exception.") .hasCauseInstanceOf(CancellationException.class); }); } @Test void testCompletedLogicalSlotCancelationDoesNotCancelPhysicalSlotRequestAndDoesNotRemoveSharedSlot() throws Exception { // physical slot request is completed and completes logical requests
|
OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.scheduler; import org.apache.flink.runtime.clusterframework.types.AllocationID; import org.apache.flink.runtime.clusterframework.types.ResourceProfile; import org.apache.flink.runtime.clusterframework.types.SlotProfile; import org.apache.flink.runtime.clusterframework.types.SlotProfileTestingUtils; import org.apache.flink.runtime.executiongraph.ExecutionAttemptID; import org.apache.flink.runtime.jobmanager.scheduler.SlotSharingGroup; import org.apache.flink.runtime.jobmaster.LogicalSlot; import org.apache.flink.runtime.jobmaster.SlotRequestId; import org.apache.flink.runtime.jobmaster.TestingPayload; import org.apache.flink.runtime.jobmaster.slotpool.DummyPayload; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequest; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequestBulk; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequestBulkChecker; import org.apache.flink.runtime.scheduler.SharedSlotProfileRetriever.SharedSlotProfileRetrieverFactory; import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID; import org.apache.flink.util.FlinkException; import org.apache.flink.util.function.BiConsumerWithException; import org.junit.jupiter.api.Test; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createExecutionAttemptId; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createRandomExecutionVertexId; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** Test suite for {@link SlotSharingExecutionSlotAllocator}. */ class SlotSharingExecutionSlotAllocatorTest { private static final Duration ALLOCATION_TIMEOUT = Duration.ofMillis(100L); private static final ResourceProfile RESOURCE_PROFILE = ResourceProfile.fromResources(3, 5); private static final ExecutionVertexID EV1 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV2 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV3 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV4 = createRandomExecutionVertexId(); @Test void testSlotProfileRequestAskedBulkAndGroup() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).build(); ExecutionSlotSharingGroup executionSlotSharingGroup = context.getSlotSharingStrategy().getExecutionSlotSharingGroup(EV1); context.allocateSlotsFor(EV1, EV2); List<Set<ExecutionVertexID>> askedBulks = context.getSlotProfileRetrieverFactory().getAskedBulks(); assertThat(askedBulks).hasSize(1); assertThat(askedBulks.get(0)).containsExactlyInAnyOrder(EV1, EV2); assertThat(context.getSlotProfileRetrieverFactory().getAskedGroups()) .containsExactly(executionSlotSharingGroup); } @Test void testSlotRequestProfile() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2, EV3).build(); ResourceProfile physicalsSlotResourceProfile = RESOURCE_PROFILE.multiply(3); context.allocateSlotsFor(EV1, EV2); Optional<PhysicalSlotRequest> slotRequest = context.getSlotProvider().getRequests().values().stream().findFirst(); assertThat(slotRequest).isPresent(); assertThat(slotRequest.get().getSlotProfile().getPhysicalSlotResourceProfile()) .isEqualTo(physicalsSlotResourceProfile); } @Test void testAllocatePhysicalSlotForNewSharedSlot() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).addGroup(EV3, EV4).build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV1, EV2, EV3, EV4); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); assertThat(assignIds).containsExactlyInAnyOrder(EV1, EV2, EV3, EV4); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testAllocateLogicalSlotFromAvailableSharedSlot() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).build(); context.allocateSlotsFor(EV1); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV2); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); // execution 0 from the first allocateSlotsFor call and execution 1 from the second // allocateSlotsFor call // share a slot, therefore only one physical slot allocation should happen assertThat(assignIds).containsExactly(EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); } @Test void testDuplicateAllocationDoesNotRecreateLogicalSlotFuture() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1).build(); ExecutionSlotAssignment assignment1 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); ExecutionSlotAssignment assignment2 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); assertThat(assignment1.getLogicalSlotFuture().get()) .isSameAs(assignment2.getLogicalSlotFuture().get()); } @Test void testFailedPhysicalSlotRequestFailsLogicalSlotFuturesAndRemovesSharedSlot() { AllocationContext context = AllocationContext. newBuilder () .addGroup(EV1) .withPhysicalSlotProvider( TestingPhysicalSlotProvider .createWithoutImmediatePhysicalSlotCreation()) .build(); CompletableFuture<LogicalSlot> logicalSlotFuture = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1) .getLogicalSlotFuture(); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(logicalSlotFuture).isNotDone(); context.getSlotProvider() .getResponses() .get(slotRequestId) .completeExceptionally(new Throwable()); assertThat(logicalSlotFuture).isCompletedExceptionally(); // next allocation allocates new shared slot context.allocateSlotsFor(EV1); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testSlotWillBeOccupiedIndefinitelyFalse() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(false); } @Test void testSlotWillBeOccupiedIndefinitelyTrue() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(true); } private static void testSlotWillBeOccupiedIndefinitely(boolean slotWillBeOccupiedIndefinitely) throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. newBuilder () .addGroup(EV1) .setSlotWillBeOccupiedIndefinitely(slotWillBeOccupiedIndefinitely) .build(); context.allocateSlotsFor(EV1); PhysicalSlotRequest slotRequest = context.getSlotProvider().getFirstRequestOrFail(); assertThat(slotRequest.willSlotBeOccupiedIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); TestingPhysicalSlot physicalSlot = context.getSlotProvider().getResponses().get(slotRequest.getSlotRequestId()).get(); assertThat(physicalSlot.getPayload()).isNotNull(); assertThat(physicalSlot.getPayload().willOccupySlotIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); } @Test void testReturningLogicalSlotsRemovesSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, true, (context, assignment) -> assignment.getLogicalSlotFuture().get().releaseSlot(null)); } @Test void testLogicalSlotCancelsPhysicalSlotRequestAndRemovesSharedSlot() throws Exception { // physical slot request is not completed and does not complete logical requests testLogicalSlotRequestCancellationOrRelease( true, true, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assertThatThrownBy( () -> { context.getAllocator() .cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }) .as("The logical future must finish with the cancellation exception.") .hasCauseInstanceOf(CancellationException.class); }); } @Test void testCompletedLogicalSlotCancelationDoesNotCancelPhysicalSlotRequestAndDoesNotRemoveSharedSlot() throws Exception { // physical slot request is completed and completes logical requests
|
java
|
import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID; import org.apache.flink.util.FlinkException; import org.apache.flink.util.function.BiConsumerWithException; import org.junit.jupiter.api.Test; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createExecutionAttemptId; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createRandomExecutionVertexId; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** Test suite for {@link SlotSharingExecutionSlotAllocator}. */ class SlotSharingExecutionSlotAllocatorTest { private static final Duration ALLOCATION_TIMEOUT = Duration.ofMillis(100L); private static final ResourceProfile RESOURCE_PROFILE = ResourceProfile.fromResources(3, 5); private static final ExecutionVertexID EV1 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV2 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV3 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV4 = createRandomExecutionVertexId(); @Test void testSlotProfileRequestAskedBulkAndGroup() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).build(); ExecutionSlotSharingGroup executionSlotSharingGroup = context.getSlotSharingStrategy().getExecutionSlotSharingGroup(EV1); context.allocateSlotsFor(EV1, EV2); List<Set<ExecutionVertexID>> askedBulks = context.getSlotProfileRetrieverFactory().getAskedBulks(); assertThat(askedBulks).hasSize(1); assertThat(askedBulks.get(0)).containsExactlyInAnyOrder(EV1, EV2); assertThat(context.getSlotProfileRetrieverFactory().getAskedGroups()) .containsExactly(executionSlotSharingGroup); } @Test void testSlotRequestProfile() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2, EV3).build(); ResourceProfile physicalsSlotResourceProfile = RESOURCE_PROFILE.multiply(3); context.allocateSlotsFor(EV1, EV2); Optional<PhysicalSlotRequest> slotRequest = context.getSlotProvider().getRequests().values().stream().findFirst(); assertThat(slotRequest).isPresent(); assertThat(slotRequest.get().getSlotProfile().getPhysicalSlotResourceProfile()) .isEqualTo(physicalsSlotResourceProfile); } @Test void testAllocatePhysicalSlotForNewSharedSlot() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).addGroup(EV3, EV4).build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV1, EV2, EV3, EV4); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); assertThat(assignIds).containsExactlyInAnyOrder(EV1, EV2, EV3, EV4); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testAllocateLogicalSlotFromAvailableSharedSlot() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).build(); context.allocateSlotsFor(EV1); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV2); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); // execution 0 from the first allocateSlotsFor call and execution 1 from the second // allocateSlotsFor call // share a slot, therefore only one physical slot allocation should happen assertThat(assignIds).containsExactly(EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); } @Test void testDuplicateAllocationDoesNotRecreateLogicalSlotFuture() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1).build(); ExecutionSlotAssignment assignment1 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); ExecutionSlotAssignment assignment2 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); assertThat(assignment1.getLogicalSlotFuture().get()) .isSameAs(assignment2.getLogicalSlotFuture().get()); } @Test void testFailedPhysicalSlotRequestFailsLogicalSlotFuturesAndRemovesSharedSlot() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1) .withPhysicalSlotProvider( TestingPhysicalSlotProvider .createWithoutImmediatePhysicalSlotCreation()) .build(); CompletableFuture<LogicalSlot> logicalSlotFuture = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1) .getLogicalSlotFuture(); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(logicalSlotFuture).isNotDone(); context.getSlotProvider() .getResponses() .get(slotRequestId) .completeExceptionally(new Throwable()); assertThat(logicalSlotFuture).isCompletedExceptionally(); // next allocation allocates new shared slot context.allocateSlotsFor(EV1); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testSlotWillBeOccupiedIndefinitelyFalse() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(false); } @Test void testSlotWillBeOccupiedIndefinitelyTrue() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(true); } private static void testSlotWillBeOccupiedIndefinitely(boolean slotWillBeOccupiedIndefinitely) throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1) .setSlotWillBeOccupiedIndefinitely(slotWillBeOccupiedIndefinitely) .build(); context.allocateSlotsFor(EV1); PhysicalSlotRequest slotRequest = context.getSlotProvider().getFirstRequestOrFail(); assertThat(slotRequest.willSlotBeOccupiedIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); TestingPhysicalSlot physicalSlot = context.getSlotProvider().getResponses().get(slotRequest.getSlotRequestId()).get(); assertThat(physicalSlot.getPayload()).isNotNull(); assertThat(physicalSlot.getPayload().willOccupySlotIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); } @Test void testReturningLogicalSlotsRemovesSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, true, (context, assignment) -> assignment.getLogicalSlotFuture().get().releaseSlot(null)); } @Test void testLogicalSlotCancelsPhysicalSlotRequestAndRemovesSharedSlot() throws Exception { // physical slot request is not completed and does not complete logical requests testLogicalSlotRequestCancellationOrRelease( true, true, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assertThatThrownBy( () -> { context.getAllocator() .cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }) .as("The logical future must finish with the cancellation exception.") .hasCauseInstanceOf(CancellationException.class); }); } @Test void testCompletedLogicalSlotCancelationDoesNotCancelPhysicalSlotRequestAndDoesNotRemoveSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, false, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }); } private static void testLogicalSlotRequestCancellationOrRelease( boolean completePhysicalSlotFutureManually, boolean cancelsPhysicalSlotRequestAndRemovesSharedSlot, BiConsumerWithException<AllocationContext, ExecutionSlotAssignment, Exception> cancelOrReleaseAction) throws Exception { AllocationContext.Builder allocationContextBuilder = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2, EV3); if (completePhysicalSlotFutureManually) { allocationContextBuilder.withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation()); } AllocationContext context = allocationContextBuilder.build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments = context.allocateSlotsFor(EV1, EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); // cancel or release only
|
import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID; import org.apache.flink.util.FlinkException; import org.apache.flink.util.function.BiConsumerWithException; import org.junit.jupiter.api.Test; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createExecutionAttemptId; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createRandomExecutionVertexId; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** Test suite for {@link SlotSharingExecutionSlotAllocator}. */ class SlotSharingExecutionSlotAllocatorTest { private static final Duration ALLOCATION_TIMEOUT = Duration.ofMillis(100L); private static final ResourceProfile RESOURCE_PROFILE = ResourceProfile.fromResources(3, 5); private static final ExecutionVertexID EV1 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV2 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV3 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV4 = createRandomExecutionVertexId(); @Test void testSlotProfileRequestAskedBulkAndGroup() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).build(); ExecutionSlotSharingGroup executionSlotSharingGroup = context.getSlotSharingStrategy().getExecutionSlotSharingGroup(EV1); context.allocateSlotsFor(EV1, EV2); List<Set<ExecutionVertexID>> askedBulks = context.getSlotProfileRetrieverFactory().getAskedBulks(); assertThat(askedBulks).hasSize(1); assertThat(askedBulks.get(0)).containsExactlyInAnyOrder(EV1, EV2); assertThat(context.getSlotProfileRetrieverFactory().getAskedGroups()) .containsExactly(executionSlotSharingGroup); } @Test void testSlotRequestProfile() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2, EV3).build(); ResourceProfile physicalsSlotResourceProfile = RESOURCE_PROFILE.multiply(3); context.allocateSlotsFor(EV1, EV2); Optional<PhysicalSlotRequest> slotRequest = context.getSlotProvider().getRequests().values().stream().findFirst(); assertThat(slotRequest).isPresent(); assertThat(slotRequest.get().getSlotProfile().getPhysicalSlotResourceProfile()) .isEqualTo(physicalsSlotResourceProfile); } @Test void testAllocatePhysicalSlotForNewSharedSlot() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).addGroup(EV3, EV4).build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV1, EV2, EV3, EV4); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); assertThat(assignIds).containsExactlyInAnyOrder(EV1, EV2, EV3, EV4); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testAllocateLogicalSlotFromAvailableSharedSlot() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).build(); context.allocateSlotsFor(EV1); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV2); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); // execution 0 from the first allocateSlotsFor call and execution 1 from the second // allocateSlotsFor call // share a slot, therefore only one physical slot allocation should happen assertThat(assignIds).containsExactly(EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); } @Test void testDuplicateAllocationDoesNotRecreateLogicalSlotFuture() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1).build(); ExecutionSlotAssignment assignment1 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); ExecutionSlotAssignment assignment2 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); assertThat(assignment1.getLogicalSlotFuture().get()) .isSameAs(assignment2.getLogicalSlotFuture().get()); } @Test void testFailedPhysicalSlotRequestFailsLogicalSlotFuturesAndRemovesSharedSlot() { AllocationContext context = AllocationContext. newBuilder () .addGroup(EV1) .withPhysicalSlotProvider( TestingPhysicalSlotProvider .createWithoutImmediatePhysicalSlotCreation()) .build(); CompletableFuture<LogicalSlot> logicalSlotFuture = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1) .getLogicalSlotFuture(); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(logicalSlotFuture).isNotDone(); context.getSlotProvider() .getResponses() .get(slotRequestId) .completeExceptionally(new Throwable()); assertThat(logicalSlotFuture).isCompletedExceptionally(); // next allocation allocates new shared slot context.allocateSlotsFor(EV1); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testSlotWillBeOccupiedIndefinitelyFalse() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(false); } @Test void testSlotWillBeOccupiedIndefinitelyTrue() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(true); } private static void testSlotWillBeOccupiedIndefinitely(boolean slotWillBeOccupiedIndefinitely) throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. newBuilder () .addGroup(EV1) .setSlotWillBeOccupiedIndefinitely(slotWillBeOccupiedIndefinitely) .build(); context.allocateSlotsFor(EV1); PhysicalSlotRequest slotRequest = context.getSlotProvider().getFirstRequestOrFail(); assertThat(slotRequest.willSlotBeOccupiedIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); TestingPhysicalSlot physicalSlot = context.getSlotProvider().getResponses().get(slotRequest.getSlotRequestId()).get(); assertThat(physicalSlot.getPayload()).isNotNull(); assertThat(physicalSlot.getPayload().willOccupySlotIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); } @Test void testReturningLogicalSlotsRemovesSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, true, (context, assignment) -> assignment.getLogicalSlotFuture().get().releaseSlot(null)); } @Test void testLogicalSlotCancelsPhysicalSlotRequestAndRemovesSharedSlot() throws Exception { // physical slot request is not completed and does not complete logical requests testLogicalSlotRequestCancellationOrRelease( true, true, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assertThatThrownBy( () -> { context.getAllocator() .cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }) .as("The logical future must finish with the cancellation exception.") .hasCauseInstanceOf(CancellationException.class); }); } @Test void testCompletedLogicalSlotCancelationDoesNotCancelPhysicalSlotRequestAndDoesNotRemoveSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, false, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }); } private static void testLogicalSlotRequestCancellationOrRelease( boolean completePhysicalSlotFutureManually, boolean cancelsPhysicalSlotRequestAndRemovesSharedSlot, BiConsumerWithException<AllocationContext, ExecutionSlotAssignment, Exception> cancelOrReleaseAction) throws Exception { AllocationContext.Builder allocationContextBuilder = AllocationContext. newBuilder ().addGroup(EV1, EV2, EV3); if (completePhysicalSlotFutureManually) { allocationContextBuilder.withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation()); } AllocationContext context = allocationContextBuilder.build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments = context.allocateSlotsFor(EV1, EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); // cancel or release only
|
java
|
java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createExecutionAttemptId; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createRandomExecutionVertexId; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** Test suite for {@link SlotSharingExecutionSlotAllocator}. */ class SlotSharingExecutionSlotAllocatorTest { private static final Duration ALLOCATION_TIMEOUT = Duration.ofMillis(100L); private static final ResourceProfile RESOURCE_PROFILE = ResourceProfile.fromResources(3, 5); private static final ExecutionVertexID EV1 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV2 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV3 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV4 = createRandomExecutionVertexId(); @Test void testSlotProfileRequestAskedBulkAndGroup() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).build(); ExecutionSlotSharingGroup executionSlotSharingGroup = context.getSlotSharingStrategy().getExecutionSlotSharingGroup(EV1); context.allocateSlotsFor(EV1, EV2); List<Set<ExecutionVertexID>> askedBulks = context.getSlotProfileRetrieverFactory().getAskedBulks(); assertThat(askedBulks).hasSize(1); assertThat(askedBulks.get(0)).containsExactlyInAnyOrder(EV1, EV2); assertThat(context.getSlotProfileRetrieverFactory().getAskedGroups()) .containsExactly(executionSlotSharingGroup); } @Test void testSlotRequestProfile() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2, EV3).build(); ResourceProfile physicalsSlotResourceProfile = RESOURCE_PROFILE.multiply(3); context.allocateSlotsFor(EV1, EV2); Optional<PhysicalSlotRequest> slotRequest = context.getSlotProvider().getRequests().values().stream().findFirst(); assertThat(slotRequest).isPresent(); assertThat(slotRequest.get().getSlotProfile().getPhysicalSlotResourceProfile()) .isEqualTo(physicalsSlotResourceProfile); } @Test void testAllocatePhysicalSlotForNewSharedSlot() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).addGroup(EV3, EV4).build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV1, EV2, EV3, EV4); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); assertThat(assignIds).containsExactlyInAnyOrder(EV1, EV2, EV3, EV4); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testAllocateLogicalSlotFromAvailableSharedSlot() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).build(); context.allocateSlotsFor(EV1); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV2); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); // execution 0 from the first allocateSlotsFor call and execution 1 from the second // allocateSlotsFor call // share a slot, therefore only one physical slot allocation should happen assertThat(assignIds).containsExactly(EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); } @Test void testDuplicateAllocationDoesNotRecreateLogicalSlotFuture() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1).build(); ExecutionSlotAssignment assignment1 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); ExecutionSlotAssignment assignment2 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); assertThat(assignment1.getLogicalSlotFuture().get()) .isSameAs(assignment2.getLogicalSlotFuture().get()); } @Test void testFailedPhysicalSlotRequestFailsLogicalSlotFuturesAndRemovesSharedSlot() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1) .withPhysicalSlotProvider( TestingPhysicalSlotProvider .createWithoutImmediatePhysicalSlotCreation()) .build(); CompletableFuture<LogicalSlot> logicalSlotFuture = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1) .getLogicalSlotFuture(); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(logicalSlotFuture).isNotDone(); context.getSlotProvider() .getResponses() .get(slotRequestId) .completeExceptionally(new Throwable()); assertThat(logicalSlotFuture).isCompletedExceptionally(); // next allocation allocates new shared slot context.allocateSlotsFor(EV1); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testSlotWillBeOccupiedIndefinitelyFalse() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(false); } @Test void testSlotWillBeOccupiedIndefinitelyTrue() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(true); } private static void testSlotWillBeOccupiedIndefinitely(boolean slotWillBeOccupiedIndefinitely) throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1) .setSlotWillBeOccupiedIndefinitely(slotWillBeOccupiedIndefinitely) .build(); context.allocateSlotsFor(EV1); PhysicalSlotRequest slotRequest = context.getSlotProvider().getFirstRequestOrFail(); assertThat(slotRequest.willSlotBeOccupiedIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); TestingPhysicalSlot physicalSlot = context.getSlotProvider().getResponses().get(slotRequest.getSlotRequestId()).get(); assertThat(physicalSlot.getPayload()).isNotNull(); assertThat(physicalSlot.getPayload().willOccupySlotIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); } @Test void testReturningLogicalSlotsRemovesSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, true, (context, assignment) -> assignment.getLogicalSlotFuture().get().releaseSlot(null)); } @Test void testLogicalSlotCancelsPhysicalSlotRequestAndRemovesSharedSlot() throws Exception { // physical slot request is not completed and does not complete logical requests testLogicalSlotRequestCancellationOrRelease( true, true, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assertThatThrownBy( () -> { context.getAllocator() .cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }) .as("The logical future must finish with the cancellation exception.") .hasCauseInstanceOf(CancellationException.class); }); } @Test void testCompletedLogicalSlotCancelationDoesNotCancelPhysicalSlotRequestAndDoesNotRemoveSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, false, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }); } private static void testLogicalSlotRequestCancellationOrRelease( boolean completePhysicalSlotFutureManually, boolean cancelsPhysicalSlotRequestAndRemovesSharedSlot, BiConsumerWithException<AllocationContext, ExecutionSlotAssignment, Exception> cancelOrReleaseAction) throws Exception { AllocationContext.Builder allocationContextBuilder = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2, EV3); if (completePhysicalSlotFutureManually) { allocationContextBuilder.withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation()); } AllocationContext context = allocationContextBuilder.build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments = context.allocateSlotsFor(EV1, EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); // cancel or release only one sharing logical slots cancelOrReleaseAction.accept(context, getAssignmentByExecutionVertexId(assignments, EV1)); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignmentsAfterOneCancellation = context.allocateSlotsFor(EV1, EV2); // there should be no more physical slot allocations, as
|
java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createExecutionAttemptId; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createRandomExecutionVertexId; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** Test suite for {@link SlotSharingExecutionSlotAllocator}. */ class SlotSharingExecutionSlotAllocatorTest { private static final Duration ALLOCATION_TIMEOUT = Duration.ofMillis(100L); private static final ResourceProfile RESOURCE_PROFILE = ResourceProfile.fromResources(3, 5); private static final ExecutionVertexID EV1 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV2 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV3 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV4 = createRandomExecutionVertexId(); @Test void testSlotProfileRequestAskedBulkAndGroup() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).build(); ExecutionSlotSharingGroup executionSlotSharingGroup = context.getSlotSharingStrategy().getExecutionSlotSharingGroup(EV1); context.allocateSlotsFor(EV1, EV2); List<Set<ExecutionVertexID>> askedBulks = context.getSlotProfileRetrieverFactory().getAskedBulks(); assertThat(askedBulks).hasSize(1); assertThat(askedBulks.get(0)).containsExactlyInAnyOrder(EV1, EV2); assertThat(context.getSlotProfileRetrieverFactory().getAskedGroups()) .containsExactly(executionSlotSharingGroup); } @Test void testSlotRequestProfile() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2, EV3).build(); ResourceProfile physicalsSlotResourceProfile = RESOURCE_PROFILE.multiply(3); context.allocateSlotsFor(EV1, EV2); Optional<PhysicalSlotRequest> slotRequest = context.getSlotProvider().getRequests().values().stream().findFirst(); assertThat(slotRequest).isPresent(); assertThat(slotRequest.get().getSlotProfile().getPhysicalSlotResourceProfile()) .isEqualTo(physicalsSlotResourceProfile); } @Test void testAllocatePhysicalSlotForNewSharedSlot() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).addGroup(EV3, EV4).build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV1, EV2, EV3, EV4); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); assertThat(assignIds).containsExactlyInAnyOrder(EV1, EV2, EV3, EV4); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testAllocateLogicalSlotFromAvailableSharedSlot() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).build(); context.allocateSlotsFor(EV1); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV2); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); // execution 0 from the first allocateSlotsFor call and execution 1 from the second // allocateSlotsFor call // share a slot, therefore only one physical slot allocation should happen assertThat(assignIds).containsExactly(EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); } @Test void testDuplicateAllocationDoesNotRecreateLogicalSlotFuture() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1).build(); ExecutionSlotAssignment assignment1 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); ExecutionSlotAssignment assignment2 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); assertThat(assignment1.getLogicalSlotFuture().get()) .isSameAs(assignment2.getLogicalSlotFuture().get()); } @Test void testFailedPhysicalSlotRequestFailsLogicalSlotFuturesAndRemovesSharedSlot() { AllocationContext context = AllocationContext. newBuilder () .addGroup(EV1) .withPhysicalSlotProvider( TestingPhysicalSlotProvider .createWithoutImmediatePhysicalSlotCreation()) .build(); CompletableFuture<LogicalSlot> logicalSlotFuture = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1) .getLogicalSlotFuture(); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(logicalSlotFuture).isNotDone(); context.getSlotProvider() .getResponses() .get(slotRequestId) .completeExceptionally(new Throwable()); assertThat(logicalSlotFuture).isCompletedExceptionally(); // next allocation allocates new shared slot context.allocateSlotsFor(EV1); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testSlotWillBeOccupiedIndefinitelyFalse() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(false); } @Test void testSlotWillBeOccupiedIndefinitelyTrue() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(true); } private static void testSlotWillBeOccupiedIndefinitely(boolean slotWillBeOccupiedIndefinitely) throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. newBuilder () .addGroup(EV1) .setSlotWillBeOccupiedIndefinitely(slotWillBeOccupiedIndefinitely) .build(); context.allocateSlotsFor(EV1); PhysicalSlotRequest slotRequest = context.getSlotProvider().getFirstRequestOrFail(); assertThat(slotRequest.willSlotBeOccupiedIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); TestingPhysicalSlot physicalSlot = context.getSlotProvider().getResponses().get(slotRequest.getSlotRequestId()).get(); assertThat(physicalSlot.getPayload()).isNotNull(); assertThat(physicalSlot.getPayload().willOccupySlotIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); } @Test void testReturningLogicalSlotsRemovesSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, true, (context, assignment) -> assignment.getLogicalSlotFuture().get().releaseSlot(null)); } @Test void testLogicalSlotCancelsPhysicalSlotRequestAndRemovesSharedSlot() throws Exception { // physical slot request is not completed and does not complete logical requests testLogicalSlotRequestCancellationOrRelease( true, true, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assertThatThrownBy( () -> { context.getAllocator() .cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }) .as("The logical future must finish with the cancellation exception.") .hasCauseInstanceOf(CancellationException.class); }); } @Test void testCompletedLogicalSlotCancelationDoesNotCancelPhysicalSlotRequestAndDoesNotRemoveSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, false, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }); } private static void testLogicalSlotRequestCancellationOrRelease( boolean completePhysicalSlotFutureManually, boolean cancelsPhysicalSlotRequestAndRemovesSharedSlot, BiConsumerWithException<AllocationContext, ExecutionSlotAssignment, Exception> cancelOrReleaseAction) throws Exception { AllocationContext.Builder allocationContextBuilder = AllocationContext. newBuilder ().addGroup(EV1, EV2, EV3); if (completePhysicalSlotFutureManually) { allocationContextBuilder.withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation()); } AllocationContext context = allocationContextBuilder.build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments = context.allocateSlotsFor(EV1, EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); // cancel or release only one sharing logical slots cancelOrReleaseAction.accept(context, getAssignmentByExecutionVertexId(assignments, EV1)); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignmentsAfterOneCancellation = context.allocateSlotsFor(EV1, EV2); // there should be no more physical slot allocations, as
|
java
|
createRandomExecutionVertexId(); private static final ExecutionVertexID EV3 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV4 = createRandomExecutionVertexId(); @Test void testSlotProfileRequestAskedBulkAndGroup() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).build(); ExecutionSlotSharingGroup executionSlotSharingGroup = context.getSlotSharingStrategy().getExecutionSlotSharingGroup(EV1); context.allocateSlotsFor(EV1, EV2); List<Set<ExecutionVertexID>> askedBulks = context.getSlotProfileRetrieverFactory().getAskedBulks(); assertThat(askedBulks).hasSize(1); assertThat(askedBulks.get(0)).containsExactlyInAnyOrder(EV1, EV2); assertThat(context.getSlotProfileRetrieverFactory().getAskedGroups()) .containsExactly(executionSlotSharingGroup); } @Test void testSlotRequestProfile() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2, EV3).build(); ResourceProfile physicalsSlotResourceProfile = RESOURCE_PROFILE.multiply(3); context.allocateSlotsFor(EV1, EV2); Optional<PhysicalSlotRequest> slotRequest = context.getSlotProvider().getRequests().values().stream().findFirst(); assertThat(slotRequest).isPresent(); assertThat(slotRequest.get().getSlotProfile().getPhysicalSlotResourceProfile()) .isEqualTo(physicalsSlotResourceProfile); } @Test void testAllocatePhysicalSlotForNewSharedSlot() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).addGroup(EV3, EV4).build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV1, EV2, EV3, EV4); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); assertThat(assignIds).containsExactlyInAnyOrder(EV1, EV2, EV3, EV4); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testAllocateLogicalSlotFromAvailableSharedSlot() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).build(); context.allocateSlotsFor(EV1); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV2); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); // execution 0 from the first allocateSlotsFor call and execution 1 from the second // allocateSlotsFor call // share a slot, therefore only one physical slot allocation should happen assertThat(assignIds).containsExactly(EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); } @Test void testDuplicateAllocationDoesNotRecreateLogicalSlotFuture() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1).build(); ExecutionSlotAssignment assignment1 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); ExecutionSlotAssignment assignment2 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); assertThat(assignment1.getLogicalSlotFuture().get()) .isSameAs(assignment2.getLogicalSlotFuture().get()); } @Test void testFailedPhysicalSlotRequestFailsLogicalSlotFuturesAndRemovesSharedSlot() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1) .withPhysicalSlotProvider( TestingPhysicalSlotProvider .createWithoutImmediatePhysicalSlotCreation()) .build(); CompletableFuture<LogicalSlot> logicalSlotFuture = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1) .getLogicalSlotFuture(); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(logicalSlotFuture).isNotDone(); context.getSlotProvider() .getResponses() .get(slotRequestId) .completeExceptionally(new Throwable()); assertThat(logicalSlotFuture).isCompletedExceptionally(); // next allocation allocates new shared slot context.allocateSlotsFor(EV1); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testSlotWillBeOccupiedIndefinitelyFalse() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(false); } @Test void testSlotWillBeOccupiedIndefinitelyTrue() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(true); } private static void testSlotWillBeOccupiedIndefinitely(boolean slotWillBeOccupiedIndefinitely) throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1) .setSlotWillBeOccupiedIndefinitely(slotWillBeOccupiedIndefinitely) .build(); context.allocateSlotsFor(EV1); PhysicalSlotRequest slotRequest = context.getSlotProvider().getFirstRequestOrFail(); assertThat(slotRequest.willSlotBeOccupiedIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); TestingPhysicalSlot physicalSlot = context.getSlotProvider().getResponses().get(slotRequest.getSlotRequestId()).get(); assertThat(physicalSlot.getPayload()).isNotNull(); assertThat(physicalSlot.getPayload().willOccupySlotIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); } @Test void testReturningLogicalSlotsRemovesSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, true, (context, assignment) -> assignment.getLogicalSlotFuture().get().releaseSlot(null)); } @Test void testLogicalSlotCancelsPhysicalSlotRequestAndRemovesSharedSlot() throws Exception { // physical slot request is not completed and does not complete logical requests testLogicalSlotRequestCancellationOrRelease( true, true, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assertThatThrownBy( () -> { context.getAllocator() .cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }) .as("The logical future must finish with the cancellation exception.") .hasCauseInstanceOf(CancellationException.class); }); } @Test void testCompletedLogicalSlotCancelationDoesNotCancelPhysicalSlotRequestAndDoesNotRemoveSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, false, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }); } private static void testLogicalSlotRequestCancellationOrRelease( boolean completePhysicalSlotFutureManually, boolean cancelsPhysicalSlotRequestAndRemovesSharedSlot, BiConsumerWithException<AllocationContext, ExecutionSlotAssignment, Exception> cancelOrReleaseAction) throws Exception { AllocationContext.Builder allocationContextBuilder = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2, EV3); if (completePhysicalSlotFutureManually) { allocationContextBuilder.withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation()); } AllocationContext context = allocationContextBuilder.build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments = context.allocateSlotsFor(EV1, EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); // cancel or release only one sharing logical slots cancelOrReleaseAction.accept(context, getAssignmentByExecutionVertexId(assignments, EV1)); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignmentsAfterOneCancellation = context.allocateSlotsFor(EV1, EV2); // there should be no more physical slot allocations, as the first logical slot reuses the // previous shared slot assertThat(context.getSlotProvider().getRequests()).hasSize(1); // cancel or release all sharing logical slots for (ExecutionSlotAssignment assignment : assignmentsAfterOneCancellation.values()) { cancelOrReleaseAction.accept(context, assignment); } SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(context.getSlotProvider().getCancellations().containsKey(slotRequestId)) .isEqualTo(cancelsPhysicalSlotRequestAndRemovesSharedSlot); context.allocateSlotsFor(EV3); // there should be one more physical slot allocation if the first allocation should be // removed with all logical slots int expectedNumberOfRequests = cancelsPhysicalSlotRequestAndRemovesSharedSlot ? 2 : 1; assertThat(context.getSlotProvider().getRequests()).hasSize(expectedNumberOfRequests);
|
createRandomExecutionVertexId(); private static final ExecutionVertexID EV3 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV4 = createRandomExecutionVertexId(); @Test void testSlotProfileRequestAskedBulkAndGroup() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).build(); ExecutionSlotSharingGroup executionSlotSharingGroup = context.getSlotSharingStrategy().getExecutionSlotSharingGroup(EV1); context.allocateSlotsFor(EV1, EV2); List<Set<ExecutionVertexID>> askedBulks = context.getSlotProfileRetrieverFactory().getAskedBulks(); assertThat(askedBulks).hasSize(1); assertThat(askedBulks.get(0)).containsExactlyInAnyOrder(EV1, EV2); assertThat(context.getSlotProfileRetrieverFactory().getAskedGroups()) .containsExactly(executionSlotSharingGroup); } @Test void testSlotRequestProfile() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2, EV3).build(); ResourceProfile physicalsSlotResourceProfile = RESOURCE_PROFILE.multiply(3); context.allocateSlotsFor(EV1, EV2); Optional<PhysicalSlotRequest> slotRequest = context.getSlotProvider().getRequests().values().stream().findFirst(); assertThat(slotRequest).isPresent(); assertThat(slotRequest.get().getSlotProfile().getPhysicalSlotResourceProfile()) .isEqualTo(physicalsSlotResourceProfile); } @Test void testAllocatePhysicalSlotForNewSharedSlot() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).addGroup(EV3, EV4).build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV1, EV2, EV3, EV4); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); assertThat(assignIds).containsExactlyInAnyOrder(EV1, EV2, EV3, EV4); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testAllocateLogicalSlotFromAvailableSharedSlot() { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).build(); context.allocateSlotsFor(EV1); Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments = context.allocateSlotsFor(EV2); Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values()); // execution 0 from the first allocateSlotsFor call and execution 1 from the second // allocateSlotsFor call // share a slot, therefore only one physical slot allocation should happen assertThat(assignIds).containsExactly(EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); } @Test void testDuplicateAllocationDoesNotRecreateLogicalSlotFuture() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1).build(); ExecutionSlotAssignment assignment1 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); ExecutionSlotAssignment assignment2 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); assertThat(assignment1.getLogicalSlotFuture().get()) .isSameAs(assignment2.getLogicalSlotFuture().get()); } @Test void testFailedPhysicalSlotRequestFailsLogicalSlotFuturesAndRemovesSharedSlot() { AllocationContext context = AllocationContext. newBuilder () .addGroup(EV1) .withPhysicalSlotProvider( TestingPhysicalSlotProvider .createWithoutImmediatePhysicalSlotCreation()) .build(); CompletableFuture<LogicalSlot> logicalSlotFuture = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1) .getLogicalSlotFuture(); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(logicalSlotFuture).isNotDone(); context.getSlotProvider() .getResponses() .get(slotRequestId) .completeExceptionally(new Throwable()); assertThat(logicalSlotFuture).isCompletedExceptionally(); // next allocation allocates new shared slot context.allocateSlotsFor(EV1); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testSlotWillBeOccupiedIndefinitelyFalse() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(false); } @Test void testSlotWillBeOccupiedIndefinitelyTrue() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(true); } private static void testSlotWillBeOccupiedIndefinitely(boolean slotWillBeOccupiedIndefinitely) throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. newBuilder () .addGroup(EV1) .setSlotWillBeOccupiedIndefinitely(slotWillBeOccupiedIndefinitely) .build(); context.allocateSlotsFor(EV1); PhysicalSlotRequest slotRequest = context.getSlotProvider().getFirstRequestOrFail(); assertThat(slotRequest.willSlotBeOccupiedIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); TestingPhysicalSlot physicalSlot = context.getSlotProvider().getResponses().get(slotRequest.getSlotRequestId()).get(); assertThat(physicalSlot.getPayload()).isNotNull(); assertThat(physicalSlot.getPayload().willOccupySlotIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); } @Test void testReturningLogicalSlotsRemovesSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, true, (context, assignment) -> assignment.getLogicalSlotFuture().get().releaseSlot(null)); } @Test void testLogicalSlotCancelsPhysicalSlotRequestAndRemovesSharedSlot() throws Exception { // physical slot request is not completed and does not complete logical requests testLogicalSlotRequestCancellationOrRelease( true, true, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assertThatThrownBy( () -> { context.getAllocator() .cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }) .as("The logical future must finish with the cancellation exception.") .hasCauseInstanceOf(CancellationException.class); }); } @Test void testCompletedLogicalSlotCancelationDoesNotCancelPhysicalSlotRequestAndDoesNotRemoveSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, false, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }); } private static void testLogicalSlotRequestCancellationOrRelease( boolean completePhysicalSlotFutureManually, boolean cancelsPhysicalSlotRequestAndRemovesSharedSlot, BiConsumerWithException<AllocationContext, ExecutionSlotAssignment, Exception> cancelOrReleaseAction) throws Exception { AllocationContext.Builder allocationContextBuilder = AllocationContext. newBuilder ().addGroup(EV1, EV2, EV3); if (completePhysicalSlotFutureManually) { allocationContextBuilder.withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation()); } AllocationContext context = allocationContextBuilder.build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments = context.allocateSlotsFor(EV1, EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); // cancel or release only one sharing logical slots cancelOrReleaseAction.accept(context, getAssignmentByExecutionVertexId(assignments, EV1)); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignmentsAfterOneCancellation = context.allocateSlotsFor(EV1, EV2); // there should be no more physical slot allocations, as the first logical slot reuses the // previous shared slot assertThat(context.getSlotProvider().getRequests()).hasSize(1); // cancel or release all sharing logical slots for (ExecutionSlotAssignment assignment : assignmentsAfterOneCancellation.values()) { cancelOrReleaseAction.accept(context, assignment); } SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(context.getSlotProvider().getCancellations().containsKey(slotRequestId)) .isEqualTo(cancelsPhysicalSlotRequestAndRemovesSharedSlot); context.allocateSlotsFor(EV3); // there should be one more physical slot allocation if the first allocation should be // removed with all logical slots int expectedNumberOfRequests = cancelsPhysicalSlotRequestAndRemovesSharedSlot ? 2 : 1; assertThat(context.getSlotProvider().getRequests()).hasSize(expectedNumberOfRequests);
|
java
|
share a slot, therefore only one physical slot allocation should happen assertThat(assignIds).containsExactly(EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); } @Test void testDuplicateAllocationDoesNotRecreateLogicalSlotFuture() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1).build(); ExecutionSlotAssignment assignment1 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); ExecutionSlotAssignment assignment2 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); assertThat(assignment1.getLogicalSlotFuture().get()) .isSameAs(assignment2.getLogicalSlotFuture().get()); } @Test void testFailedPhysicalSlotRequestFailsLogicalSlotFuturesAndRemovesSharedSlot() { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1) .withPhysicalSlotProvider( TestingPhysicalSlotProvider .createWithoutImmediatePhysicalSlotCreation()) .build(); CompletableFuture<LogicalSlot> logicalSlotFuture = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1) .getLogicalSlotFuture(); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(logicalSlotFuture).isNotDone(); context.getSlotProvider() .getResponses() .get(slotRequestId) .completeExceptionally(new Throwable()); assertThat(logicalSlotFuture).isCompletedExceptionally(); // next allocation allocates new shared slot context.allocateSlotsFor(EV1); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testSlotWillBeOccupiedIndefinitelyFalse() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(false); } @Test void testSlotWillBeOccupiedIndefinitelyTrue() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(true); } private static void testSlotWillBeOccupiedIndefinitely(boolean slotWillBeOccupiedIndefinitely) throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1) .setSlotWillBeOccupiedIndefinitely(slotWillBeOccupiedIndefinitely) .build(); context.allocateSlotsFor(EV1); PhysicalSlotRequest slotRequest = context.getSlotProvider().getFirstRequestOrFail(); assertThat(slotRequest.willSlotBeOccupiedIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); TestingPhysicalSlot physicalSlot = context.getSlotProvider().getResponses().get(slotRequest.getSlotRequestId()).get(); assertThat(physicalSlot.getPayload()).isNotNull(); assertThat(physicalSlot.getPayload().willOccupySlotIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); } @Test void testReturningLogicalSlotsRemovesSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, true, (context, assignment) -> assignment.getLogicalSlotFuture().get().releaseSlot(null)); } @Test void testLogicalSlotCancelsPhysicalSlotRequestAndRemovesSharedSlot() throws Exception { // physical slot request is not completed and does not complete logical requests testLogicalSlotRequestCancellationOrRelease( true, true, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assertThatThrownBy( () -> { context.getAllocator() .cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }) .as("The logical future must finish with the cancellation exception.") .hasCauseInstanceOf(CancellationException.class); }); } @Test void testCompletedLogicalSlotCancelationDoesNotCancelPhysicalSlotRequestAndDoesNotRemoveSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, false, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }); } private static void testLogicalSlotRequestCancellationOrRelease( boolean completePhysicalSlotFutureManually, boolean cancelsPhysicalSlotRequestAndRemovesSharedSlot, BiConsumerWithException<AllocationContext, ExecutionSlotAssignment, Exception> cancelOrReleaseAction) throws Exception { AllocationContext.Builder allocationContextBuilder = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2, EV3); if (completePhysicalSlotFutureManually) { allocationContextBuilder.withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation()); } AllocationContext context = allocationContextBuilder.build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments = context.allocateSlotsFor(EV1, EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); // cancel or release only one sharing logical slots cancelOrReleaseAction.accept(context, getAssignmentByExecutionVertexId(assignments, EV1)); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignmentsAfterOneCancellation = context.allocateSlotsFor(EV1, EV2); // there should be no more physical slot allocations, as the first logical slot reuses the // previous shared slot assertThat(context.getSlotProvider().getRequests()).hasSize(1); // cancel or release all sharing logical slots for (ExecutionSlotAssignment assignment : assignmentsAfterOneCancellation.values()) { cancelOrReleaseAction.accept(context, assignment); } SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(context.getSlotProvider().getCancellations().containsKey(slotRequestId)) .isEqualTo(cancelsPhysicalSlotRequestAndRemovesSharedSlot); context.allocateSlotsFor(EV3); // there should be one more physical slot allocation if the first allocation should be // removed with all logical slots int expectedNumberOfRequests = cancelsPhysicalSlotRequestAndRemovesSharedSlot ? 2 : 1; assertThat(context.getSlotProvider().getRequests()).hasSize(expectedNumberOfRequests); } @Test void testPhysicalSlotReleaseLogicalSlots() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments = context.allocateSlotsFor(EV1, EV2); List<TestingPayload> payloads = assignments.values().stream() .map( assignment -> { TestingPayload payload = new TestingPayload(); assignment .getLogicalSlotFuture() .thenAccept( logicalSlot -> logicalSlot.tryAssignPayload(payload)); return payload; }) .collect(Collectors.toList()); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); TestingPhysicalSlot physicalSlot = context.getSlotProvider().getFirstResponseOrFail().get(); assertThat(payloads.stream().allMatch(payload -> payload.getTerminalStateFuture().isDone())) .isFalse(); assertThat(physicalSlot.getPayload()).isNotNull(); physicalSlot.getPayload().release(new Throwable()); assertThat(payloads.stream().allMatch(payload -> payload.getTerminalStateFuture().isDone())) .isTrue(); assertThat(context.getSlotProvider().getCancellations()).containsKey(slotRequestId); context.allocateSlotsFor(EV1, EV2); // there should be one more physical slot allocation, as the first allocation should be // removed after releasing all logical slots assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testSchedulePendingRequestBulkTimeoutCheck() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); PhysicalSlotRequestBulk bulk = bulkChecker.getBulk(); assertThat(bulk.getPendingRequests()).hasSize(2); assertThat(bulk.getPendingRequests()) .containsExactlyInAnyOrder(RESOURCE_PROFILE.multiply(2), RESOURCE_PROFILE); assertThat(bulk.getAllocationIdsOfFulfilledRequests()).isEmpty(); assertThat(bulkChecker.getTimeout()).isEqualTo(ALLOCATION_TIMEOUT); } @Test void testRequestFulfilledInBulk() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); AllocationID allocationId = new AllocationID(); ResourceProfile
|
share a slot, therefore only one physical slot allocation should happen assertThat(assignIds).containsExactly(EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); } @Test void testDuplicateAllocationDoesNotRecreateLogicalSlotFuture() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1).build(); ExecutionSlotAssignment assignment1 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); ExecutionSlotAssignment assignment2 = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1); assertThat(assignment1.getLogicalSlotFuture().get()) .isSameAs(assignment2.getLogicalSlotFuture().get()); } @Test void testFailedPhysicalSlotRequestFailsLogicalSlotFuturesAndRemovesSharedSlot() { AllocationContext context = AllocationContext. newBuilder () .addGroup(EV1) .withPhysicalSlotProvider( TestingPhysicalSlotProvider .createWithoutImmediatePhysicalSlotCreation()) .build(); CompletableFuture<LogicalSlot> logicalSlotFuture = getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1) .getLogicalSlotFuture(); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(logicalSlotFuture).isNotDone(); context.getSlotProvider() .getResponses() .get(slotRequestId) .completeExceptionally(new Throwable()); assertThat(logicalSlotFuture).isCompletedExceptionally(); // next allocation allocates new shared slot context.allocateSlotsFor(EV1); assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testSlotWillBeOccupiedIndefinitelyFalse() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(false); } @Test void testSlotWillBeOccupiedIndefinitelyTrue() throws ExecutionException, InterruptedException { testSlotWillBeOccupiedIndefinitely(true); } private static void testSlotWillBeOccupiedIndefinitely(boolean slotWillBeOccupiedIndefinitely) throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. newBuilder () .addGroup(EV1) .setSlotWillBeOccupiedIndefinitely(slotWillBeOccupiedIndefinitely) .build(); context.allocateSlotsFor(EV1); PhysicalSlotRequest slotRequest = context.getSlotProvider().getFirstRequestOrFail(); assertThat(slotRequest.willSlotBeOccupiedIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); TestingPhysicalSlot physicalSlot = context.getSlotProvider().getResponses().get(slotRequest.getSlotRequestId()).get(); assertThat(physicalSlot.getPayload()).isNotNull(); assertThat(physicalSlot.getPayload().willOccupySlotIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); } @Test void testReturningLogicalSlotsRemovesSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, true, (context, assignment) -> assignment.getLogicalSlotFuture().get().releaseSlot(null)); } @Test void testLogicalSlotCancelsPhysicalSlotRequestAndRemovesSharedSlot() throws Exception { // physical slot request is not completed and does not complete logical requests testLogicalSlotRequestCancellationOrRelease( true, true, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assertThatThrownBy( () -> { context.getAllocator() .cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }) .as("The logical future must finish with the cancellation exception.") .hasCauseInstanceOf(CancellationException.class); }); } @Test void testCompletedLogicalSlotCancelationDoesNotCancelPhysicalSlotRequestAndDoesNotRemoveSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, false, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }); } private static void testLogicalSlotRequestCancellationOrRelease( boolean completePhysicalSlotFutureManually, boolean cancelsPhysicalSlotRequestAndRemovesSharedSlot, BiConsumerWithException<AllocationContext, ExecutionSlotAssignment, Exception> cancelOrReleaseAction) throws Exception { AllocationContext.Builder allocationContextBuilder = AllocationContext. newBuilder ().addGroup(EV1, EV2, EV3); if (completePhysicalSlotFutureManually) { allocationContextBuilder.withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation()); } AllocationContext context = allocationContextBuilder.build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments = context.allocateSlotsFor(EV1, EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); // cancel or release only one sharing logical slots cancelOrReleaseAction.accept(context, getAssignmentByExecutionVertexId(assignments, EV1)); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignmentsAfterOneCancellation = context.allocateSlotsFor(EV1, EV2); // there should be no more physical slot allocations, as the first logical slot reuses the // previous shared slot assertThat(context.getSlotProvider().getRequests()).hasSize(1); // cancel or release all sharing logical slots for (ExecutionSlotAssignment assignment : assignmentsAfterOneCancellation.values()) { cancelOrReleaseAction.accept(context, assignment); } SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(context.getSlotProvider().getCancellations().containsKey(slotRequestId)) .isEqualTo(cancelsPhysicalSlotRequestAndRemovesSharedSlot); context.allocateSlotsFor(EV3); // there should be one more physical slot allocation if the first allocation should be // removed with all logical slots int expectedNumberOfRequests = cancelsPhysicalSlotRequestAndRemovesSharedSlot ? 2 : 1; assertThat(context.getSlotProvider().getRequests()).hasSize(expectedNumberOfRequests); } @Test void testPhysicalSlotReleaseLogicalSlots() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments = context.allocateSlotsFor(EV1, EV2); List<TestingPayload> payloads = assignments.values().stream() .map( assignment -> { TestingPayload payload = new TestingPayload(); assignment .getLogicalSlotFuture() .thenAccept( logicalSlot -> logicalSlot.tryAssignPayload(payload)); return payload; }) .collect(Collectors.toList()); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); TestingPhysicalSlot physicalSlot = context.getSlotProvider().getFirstResponseOrFail().get(); assertThat(payloads.stream().allMatch(payload -> payload.getTerminalStateFuture().isDone())) .isFalse(); assertThat(physicalSlot.getPayload()).isNotNull(); physicalSlot.getPayload().release(new Throwable()); assertThat(payloads.stream().allMatch(payload -> payload.getTerminalStateFuture().isDone())) .isTrue(); assertThat(context.getSlotProvider().getCancellations()).containsKey(slotRequestId); context.allocateSlotsFor(EV1, EV2); // there should be one more physical slot allocation, as the first allocation should be // removed after releasing all logical slots assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testSchedulePendingRequestBulkTimeoutCheck() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); PhysicalSlotRequestBulk bulk = bulkChecker.getBulk(); assertThat(bulk.getPendingRequests()).hasSize(2); assertThat(bulk.getPendingRequests()) .containsExactlyInAnyOrder(RESOURCE_PROFILE.multiply(2), RESOURCE_PROFILE); assertThat(bulk.getAllocationIdsOfFulfilledRequests()).isEmpty(); assertThat(bulkChecker.getTimeout()).isEqualTo(ALLOCATION_TIMEOUT); } @Test void testRequestFulfilledInBulk() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); AllocationID allocationId = new AllocationID(); ResourceProfile
|
java
|
physicalSlot = context.getSlotProvider().getResponses().get(slotRequest.getSlotRequestId()).get(); assertThat(physicalSlot.getPayload()).isNotNull(); assertThat(physicalSlot.getPayload().willOccupySlotIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); } @Test void testReturningLogicalSlotsRemovesSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, true, (context, assignment) -> assignment.getLogicalSlotFuture().get().releaseSlot(null)); } @Test void testLogicalSlotCancelsPhysicalSlotRequestAndRemovesSharedSlot() throws Exception { // physical slot request is not completed and does not complete logical requests testLogicalSlotRequestCancellationOrRelease( true, true, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assertThatThrownBy( () -> { context.getAllocator() .cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }) .as("The logical future must finish with the cancellation exception.") .hasCauseInstanceOf(CancellationException.class); }); } @Test void testCompletedLogicalSlotCancelationDoesNotCancelPhysicalSlotRequestAndDoesNotRemoveSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, false, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }); } private static void testLogicalSlotRequestCancellationOrRelease( boolean completePhysicalSlotFutureManually, boolean cancelsPhysicalSlotRequestAndRemovesSharedSlot, BiConsumerWithException<AllocationContext, ExecutionSlotAssignment, Exception> cancelOrReleaseAction) throws Exception { AllocationContext.Builder allocationContextBuilder = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2, EV3); if (completePhysicalSlotFutureManually) { allocationContextBuilder.withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation()); } AllocationContext context = allocationContextBuilder.build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments = context.allocateSlotsFor(EV1, EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); // cancel or release only one sharing logical slots cancelOrReleaseAction.accept(context, getAssignmentByExecutionVertexId(assignments, EV1)); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignmentsAfterOneCancellation = context.allocateSlotsFor(EV1, EV2); // there should be no more physical slot allocations, as the first logical slot reuses the // previous shared slot assertThat(context.getSlotProvider().getRequests()).hasSize(1); // cancel or release all sharing logical slots for (ExecutionSlotAssignment assignment : assignmentsAfterOneCancellation.values()) { cancelOrReleaseAction.accept(context, assignment); } SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(context.getSlotProvider().getCancellations().containsKey(slotRequestId)) .isEqualTo(cancelsPhysicalSlotRequestAndRemovesSharedSlot); context.allocateSlotsFor(EV3); // there should be one more physical slot allocation if the first allocation should be // removed with all logical slots int expectedNumberOfRequests = cancelsPhysicalSlotRequestAndRemovesSharedSlot ? 2 : 1; assertThat(context.getSlotProvider().getRequests()).hasSize(expectedNumberOfRequests); } @Test void testPhysicalSlotReleaseLogicalSlots() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().addGroup(EV1, EV2).build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments = context.allocateSlotsFor(EV1, EV2); List<TestingPayload> payloads = assignments.values().stream() .map( assignment -> { TestingPayload payload = new TestingPayload(); assignment .getLogicalSlotFuture() .thenAccept( logicalSlot -> logicalSlot.tryAssignPayload(payload)); return payload; }) .collect(Collectors.toList()); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); TestingPhysicalSlot physicalSlot = context.getSlotProvider().getFirstResponseOrFail().get(); assertThat(payloads.stream().allMatch(payload -> payload.getTerminalStateFuture().isDone())) .isFalse(); assertThat(physicalSlot.getPayload()).isNotNull(); physicalSlot.getPayload().release(new Throwable()); assertThat(payloads.stream().allMatch(payload -> payload.getTerminalStateFuture().isDone())) .isTrue(); assertThat(context.getSlotProvider().getCancellations()).containsKey(slotRequestId); context.allocateSlotsFor(EV1, EV2); // there should be one more physical slot allocation, as the first allocation should be // removed after releasing all logical slots assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testSchedulePendingRequestBulkTimeoutCheck() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); PhysicalSlotRequestBulk bulk = bulkChecker.getBulk(); assertThat(bulk.getPendingRequests()).hasSize(2); assertThat(bulk.getPendingRequests()) .containsExactlyInAnyOrder(RESOURCE_PROFILE.multiply(2), RESOURCE_PROFILE); assertThat(bulk.getAllocationIdsOfFulfilledRequests()).isEmpty(); assertThat(bulkChecker.getTimeout()).isEqualTo(ALLOCATION_TIMEOUT); } @Test void testRequestFulfilledInBulk() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); AllocationID allocationId = new AllocationID(); ResourceProfile pendingSlotResourceProfile = fulfilOneOfTwoSlotRequestsAndGetPendingProfile(context, allocationId); PhysicalSlotRequestBulk bulk = bulkChecker.getBulk(); assertThat(bulk.getPendingRequests()).hasSize(1); assertThat(bulk.getPendingRequests()).containsExactly(pendingSlotResourceProfile); assertThat(bulk.getAllocationIdsOfFulfilledRequests()).hasSize(1); assertThat(bulk.getAllocationIdsOfFulfilledRequests()).containsExactly(allocationId); } @Test void testRequestBulkCancel() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); // allocate 2 physical slots for 2 groups Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments1 = context.allocateSlotsFor(EV1, EV3); fulfilOneOfTwoSlotRequestsAndGetPendingProfile(context, new AllocationID()); PhysicalSlotRequestBulk bulk1 = bulkChecker.getBulk(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments2 = context.allocateSlotsFor(EV2); // cancelling of (EV1, EV3) releases assignments1 and only one physical slot for EV3 // the second physical slot is held by sharing EV2 from the next bulk bulk1.cancel(new Throwable()); // return completed logical slot to clear shared slot and release physical slot assertThat(assignments1).hasSize(2); CompletableFuture<LogicalSlot> ev1slot = getAssignmentByExecutionVertexId(assignments1, EV1).getLogicalSlotFuture(); boolean ev1failed = ev1slot.isCompletedExceptionally(); CompletableFuture<LogicalSlot> ev3slot = getAssignmentByExecutionVertexId(assignments1, EV3).getLogicalSlotFuture(); boolean ev3failed = ev3slot.isCompletedExceptionally(); LogicalSlot slot = ev1failed ? ev3slot.join() : ev1slot.join(); releaseLogicalSlot(slot); // EV3 needs
|
physicalSlot = context.getSlotProvider().getResponses().get(slotRequest.getSlotRequestId()).get(); assertThat(physicalSlot.getPayload()).isNotNull(); assertThat(physicalSlot.getPayload().willOccupySlotIndefinitely()) .isEqualTo(slotWillBeOccupiedIndefinitely); } @Test void testReturningLogicalSlotsRemovesSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, true, (context, assignment) -> assignment.getLogicalSlotFuture().get().releaseSlot(null)); } @Test void testLogicalSlotCancelsPhysicalSlotRequestAndRemovesSharedSlot() throws Exception { // physical slot request is not completed and does not complete logical requests testLogicalSlotRequestCancellationOrRelease( true, true, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assertThatThrownBy( () -> { context.getAllocator() .cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }) .as("The logical future must finish with the cancellation exception.") .hasCauseInstanceOf(CancellationException.class); }); } @Test void testCompletedLogicalSlotCancelationDoesNotCancelPhysicalSlotRequestAndDoesNotRemoveSharedSlot() throws Exception { // physical slot request is completed and completes logical requests testLogicalSlotRequestCancellationOrRelease( false, false, (context, assignment) -> { context.getAllocator().cancel(assignment.getExecutionAttemptId()); assignment.getLogicalSlotFuture().get(); }); } private static void testLogicalSlotRequestCancellationOrRelease( boolean completePhysicalSlotFutureManually, boolean cancelsPhysicalSlotRequestAndRemovesSharedSlot, BiConsumerWithException<AllocationContext, ExecutionSlotAssignment, Exception> cancelOrReleaseAction) throws Exception { AllocationContext.Builder allocationContextBuilder = AllocationContext. newBuilder ().addGroup(EV1, EV2, EV3); if (completePhysicalSlotFutureManually) { allocationContextBuilder.withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation()); } AllocationContext context = allocationContextBuilder.build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments = context.allocateSlotsFor(EV1, EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(1); // cancel or release only one sharing logical slots cancelOrReleaseAction.accept(context, getAssignmentByExecutionVertexId(assignments, EV1)); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignmentsAfterOneCancellation = context.allocateSlotsFor(EV1, EV2); // there should be no more physical slot allocations, as the first logical slot reuses the // previous shared slot assertThat(context.getSlotProvider().getRequests()).hasSize(1); // cancel or release all sharing logical slots for (ExecutionSlotAssignment assignment : assignmentsAfterOneCancellation.values()) { cancelOrReleaseAction.accept(context, assignment); } SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); assertThat(context.getSlotProvider().getCancellations().containsKey(slotRequestId)) .isEqualTo(cancelsPhysicalSlotRequestAndRemovesSharedSlot); context.allocateSlotsFor(EV3); // there should be one more physical slot allocation if the first allocation should be // removed with all logical slots int expectedNumberOfRequests = cancelsPhysicalSlotRequestAndRemovesSharedSlot ? 2 : 1; assertThat(context.getSlotProvider().getRequests()).hasSize(expectedNumberOfRequests); } @Test void testPhysicalSlotReleaseLogicalSlots() throws ExecutionException, InterruptedException { AllocationContext context = AllocationContext. newBuilder ().addGroup(EV1, EV2).build(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments = context.allocateSlotsFor(EV1, EV2); List<TestingPayload> payloads = assignments.values().stream() .map( assignment -> { TestingPayload payload = new TestingPayload(); assignment .getLogicalSlotFuture() .thenAccept( logicalSlot -> logicalSlot.tryAssignPayload(payload)); return payload; }) .collect(Collectors.toList()); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); TestingPhysicalSlot physicalSlot = context.getSlotProvider().getFirstResponseOrFail().get(); assertThat(payloads.stream().allMatch(payload -> payload.getTerminalStateFuture().isDone())) .isFalse(); assertThat(physicalSlot.getPayload()).isNotNull(); physicalSlot.getPayload().release(new Throwable()); assertThat(payloads.stream().allMatch(payload -> payload.getTerminalStateFuture().isDone())) .isTrue(); assertThat(context.getSlotProvider().getCancellations()).containsKey(slotRequestId); context.allocateSlotsFor(EV1, EV2); // there should be one more physical slot allocation, as the first allocation should be // removed after releasing all logical slots assertThat(context.getSlotProvider().getRequests()).hasSize(2); } @Test void testSchedulePendingRequestBulkTimeoutCheck() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); PhysicalSlotRequestBulk bulk = bulkChecker.getBulk(); assertThat(bulk.getPendingRequests()).hasSize(2); assertThat(bulk.getPendingRequests()) .containsExactlyInAnyOrder(RESOURCE_PROFILE.multiply(2), RESOURCE_PROFILE); assertThat(bulk.getAllocationIdsOfFulfilledRequests()).isEmpty(); assertThat(bulkChecker.getTimeout()).isEqualTo(ALLOCATION_TIMEOUT); } @Test void testRequestFulfilledInBulk() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); AllocationID allocationId = new AllocationID(); ResourceProfile pendingSlotResourceProfile = fulfilOneOfTwoSlotRequestsAndGetPendingProfile(context, allocationId); PhysicalSlotRequestBulk bulk = bulkChecker.getBulk(); assertThat(bulk.getPendingRequests()).hasSize(1); assertThat(bulk.getPendingRequests()).containsExactly(pendingSlotResourceProfile); assertThat(bulk.getAllocationIdsOfFulfilledRequests()).hasSize(1); assertThat(bulk.getAllocationIdsOfFulfilledRequests()).containsExactly(allocationId); } @Test void testRequestBulkCancel() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); // allocate 2 physical slots for 2 groups Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments1 = context.allocateSlotsFor(EV1, EV3); fulfilOneOfTwoSlotRequestsAndGetPendingProfile(context, new AllocationID()); PhysicalSlotRequestBulk bulk1 = bulkChecker.getBulk(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments2 = context.allocateSlotsFor(EV2); // cancelling of (EV1, EV3) releases assignments1 and only one physical slot for EV3 // the second physical slot is held by sharing EV2 from the next bulk bulk1.cancel(new Throwable()); // return completed logical slot to clear shared slot and release physical slot assertThat(assignments1).hasSize(2); CompletableFuture<LogicalSlot> ev1slot = getAssignmentByExecutionVertexId(assignments1, EV1).getLogicalSlotFuture(); boolean ev1failed = ev1slot.isCompletedExceptionally(); CompletableFuture<LogicalSlot> ev3slot = getAssignmentByExecutionVertexId(assignments1, EV3).getLogicalSlotFuture(); boolean ev3failed = ev3slot.isCompletedExceptionally(); LogicalSlot slot = ev1failed ? ev3slot.join() : ev1slot.join(); releaseLogicalSlot(slot); // EV3 needs
|
java
|
TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); PhysicalSlotRequestBulk bulk = bulkChecker.getBulk(); assertThat(bulk.getPendingRequests()).hasSize(2); assertThat(bulk.getPendingRequests()) .containsExactlyInAnyOrder(RESOURCE_PROFILE.multiply(2), RESOURCE_PROFILE); assertThat(bulk.getAllocationIdsOfFulfilledRequests()).isEmpty(); assertThat(bulkChecker.getTimeout()).isEqualTo(ALLOCATION_TIMEOUT); } @Test void testRequestFulfilledInBulk() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); AllocationID allocationId = new AllocationID(); ResourceProfile pendingSlotResourceProfile = fulfilOneOfTwoSlotRequestsAndGetPendingProfile(context, allocationId); PhysicalSlotRequestBulk bulk = bulkChecker.getBulk(); assertThat(bulk.getPendingRequests()).hasSize(1); assertThat(bulk.getPendingRequests()).containsExactly(pendingSlotResourceProfile); assertThat(bulk.getAllocationIdsOfFulfilledRequests()).hasSize(1); assertThat(bulk.getAllocationIdsOfFulfilledRequests()).containsExactly(allocationId); } @Test void testRequestBulkCancel() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); // allocate 2 physical slots for 2 groups Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments1 = context.allocateSlotsFor(EV1, EV3); fulfilOneOfTwoSlotRequestsAndGetPendingProfile(context, new AllocationID()); PhysicalSlotRequestBulk bulk1 = bulkChecker.getBulk(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments2 = context.allocateSlotsFor(EV2); // cancelling of (EV1, EV3) releases assignments1 and only one physical slot for EV3 // the second physical slot is held by sharing EV2 from the next bulk bulk1.cancel(new Throwable()); // return completed logical slot to clear shared slot and release physical slot assertThat(assignments1).hasSize(2); CompletableFuture<LogicalSlot> ev1slot = getAssignmentByExecutionVertexId(assignments1, EV1).getLogicalSlotFuture(); boolean ev1failed = ev1slot.isCompletedExceptionally(); CompletableFuture<LogicalSlot> ev3slot = getAssignmentByExecutionVertexId(assignments1, EV3).getLogicalSlotFuture(); boolean ev3failed = ev3slot.isCompletedExceptionally(); LogicalSlot slot = ev1failed ? ev3slot.join() : ev1slot.join(); releaseLogicalSlot(slot); // EV3 needs again a physical slot, therefore there are 3 requests overall context.allocateSlotsFor(EV1, EV3); assertThat(context.getSlotProvider().getRequests()).hasSize(3); // either EV1 or EV3 logical slot future is fulfilled before cancellation assertThat(ev1failed).isNotEqualTo(ev3failed); assertThat(assignments2).hasSize(1); assertThat(getAssignmentByExecutionVertexId(assignments2, EV2).getLogicalSlotFuture()) .isNotCompletedExceptionally(); } private static void releaseLogicalSlot(LogicalSlot slot) { slot.tryAssignPayload(new DummyPayload(CompletableFuture.completedFuture(null))); slot.releaseSlot(new Throwable()); } @Test void testBulkClearIfPhysicalSlotRequestFails() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); context.getSlotProvider() .getResultForRequestId(slotRequestId) .completeExceptionally(new Throwable()); PhysicalSlotRequestBulk bulk = bulkChecker.getBulk(); assertThat(bulk.getPendingRequests()).isEmpty(); } @Test void failLogicalSlotsIfPhysicalSlotIsFailed() { final TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1, EV2) .withBulkChecker(bulkChecker) .withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithFailingPhysicalSlotCreation( new FlinkException("test failure"))) .build(); final Map<ExecutionAttemptID, ExecutionSlotAssignment> allocatedSlots = context.allocateSlotsFor(EV1, EV2); for (ExecutionSlotAssignment allocatedSlot : allocatedSlots.values()) { assertThat(allocatedSlot.getLogicalSlotFuture()).isCompletedExceptionally(); } assertThat(bulkChecker.getBulk().getPendingRequests()).isEmpty(); final Set<SlotRequestId> requests = context.getSlotProvider().getRequests().keySet(); assertThat(context.getSlotProvider().getCancellations().keySet()).isEqualTo(requests); } @Test void testSlotRequestProfileFromExecutionSlotSharingGroup() { final ResourceProfile resourceProfile1 = ResourceProfile.fromResources(1, 10); final ResourceProfile resourceProfile2 = ResourceProfile.fromResources(2, 20); final AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroupAndResource(resourceProfile1, EV1, EV3) .addGroupAndResource(resourceProfile2, EV2, EV4) .build(); context.allocateSlotsFor(EV1, EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(2); assertThat( context.getSlotProvider().getRequests().values().stream() .map(PhysicalSlotRequest::getSlotProfile) .map(SlotProfile::getPhysicalSlotResourceProfile) .collect(Collectors.toList())) .containsExactlyInAnyOrder(resourceProfile1, resourceProfile2); } @Test void testSlotProviderBatchSlotRequestTimeoutCheckIsDisabled() { final AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().build(); assertThat(context.getSlotProvider().isBatchSlotRequestTimeoutCheckEnabled()).isFalse(); } private static List<ExecutionVertexID> getAssignIds( Collection<ExecutionSlotAssignment> assignments) { return assignments.stream() .map(ExecutionSlotAssignment::getExecutionAttemptId) .map(ExecutionAttemptID::getExecutionVertexId) .collect(Collectors.toList()); } private static AllocationContext createBulkCheckerContextWithEv12GroupAndEv3Group( PhysicalSlotRequestBulkChecker bulkChecker) { return AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1, EV2) .addGroup(EV3) .withBulkChecker(bulkChecker) .withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation()) .build(); } private static ResourceProfile fulfilOneOfTwoSlotRequestsAndGetPendingProfile( AllocationContext context, AllocationID allocationId) { Map<SlotRequestId, PhysicalSlotRequest> requests = context.getSlotProvider().getRequests(); List<SlotRequestId> slotRequestIds = new ArrayList<>(requests.keySet()); assertThat(slotRequestIds).hasSize(2); SlotRequestId slotRequestId1 = slotRequestIds.get(0); SlotRequestId slotRequestId2 = slotRequestIds.get(1); context.getSlotProvider() .getResultForRequestId(slotRequestId1) .complete(TestingPhysicalSlot.builder().withAllocationID(allocationId).build()); return requests.get(slotRequestId2).getSlotProfile().getPhysicalSlotResourceProfile(); } private static ExecutionSlotAssignment getAssignmentByExecutionVertexId( Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments, ExecutionVertexID executionVertexId) { return assignments.entrySet().stream() .filter(entry -> entry.getKey().getExecutionVertexId().equals(executionVertexId)) .map(Map.Entry::getValue) .collect(Collectors.toList()) .get(0); } private static class AllocationContext { private final TestingPhysicalSlotProvider slotProvider; private final TestingSlotSharingStrategy slotSharingStrategy; private final SlotSharingExecutionSlotAllocator allocator; private final TestingSharedSlotProfileRetrieverFactory slotProfileRetrieverFactory; private AllocationContext( TestingPhysicalSlotProvider slotProvider, TestingSlotSharingStrategy slotSharingStrategy, SlotSharingExecutionSlotAllocator allocator, TestingSharedSlotProfileRetrieverFactory slotProfileRetrieverFactory) { this.slotProvider = slotProvider; this.slotSharingStrategy = slotSharingStrategy; this.allocator = allocator; this.slotProfileRetrieverFactory = slotProfileRetrieverFactory; } private SlotSharingExecutionSlotAllocator getAllocator() { return allocator; } private Map<ExecutionAttemptID, ExecutionSlotAssignment> allocateSlotsFor( ExecutionVertexID... ids) { return allocator.allocateSlotsFor( Arrays.stream(ids) .map( executionVertexId -> createExecutionAttemptId(executionVertexId, 0)) .collect(Collectors.toList())); } private TestingSlotSharingStrategy getSlotSharingStrategy() { return slotSharingStrategy; } private TestingPhysicalSlotProvider
|
TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); PhysicalSlotRequestBulk bulk = bulkChecker.getBulk(); assertThat(bulk.getPendingRequests()).hasSize(2); assertThat(bulk.getPendingRequests()) .containsExactlyInAnyOrder(RESOURCE_PROFILE.multiply(2), RESOURCE_PROFILE); assertThat(bulk.getAllocationIdsOfFulfilledRequests()).isEmpty(); assertThat(bulkChecker.getTimeout()).isEqualTo(ALLOCATION_TIMEOUT); } @Test void testRequestFulfilledInBulk() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); AllocationID allocationId = new AllocationID(); ResourceProfile pendingSlotResourceProfile = fulfilOneOfTwoSlotRequestsAndGetPendingProfile(context, allocationId); PhysicalSlotRequestBulk bulk = bulkChecker.getBulk(); assertThat(bulk.getPendingRequests()).hasSize(1); assertThat(bulk.getPendingRequests()).containsExactly(pendingSlotResourceProfile); assertThat(bulk.getAllocationIdsOfFulfilledRequests()).hasSize(1); assertThat(bulk.getAllocationIdsOfFulfilledRequests()).containsExactly(allocationId); } @Test void testRequestBulkCancel() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); // allocate 2 physical slots for 2 groups Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments1 = context.allocateSlotsFor(EV1, EV3); fulfilOneOfTwoSlotRequestsAndGetPendingProfile(context, new AllocationID()); PhysicalSlotRequestBulk bulk1 = bulkChecker.getBulk(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments2 = context.allocateSlotsFor(EV2); // cancelling of (EV1, EV3) releases assignments1 and only one physical slot for EV3 // the second physical slot is held by sharing EV2 from the next bulk bulk1.cancel(new Throwable()); // return completed logical slot to clear shared slot and release physical slot assertThat(assignments1).hasSize(2); CompletableFuture<LogicalSlot> ev1slot = getAssignmentByExecutionVertexId(assignments1, EV1).getLogicalSlotFuture(); boolean ev1failed = ev1slot.isCompletedExceptionally(); CompletableFuture<LogicalSlot> ev3slot = getAssignmentByExecutionVertexId(assignments1, EV3).getLogicalSlotFuture(); boolean ev3failed = ev3slot.isCompletedExceptionally(); LogicalSlot slot = ev1failed ? ev3slot.join() : ev1slot.join(); releaseLogicalSlot(slot); // EV3 needs again a physical slot, therefore there are 3 requests overall context.allocateSlotsFor(EV1, EV3); assertThat(context.getSlotProvider().getRequests()).hasSize(3); // either EV1 or EV3 logical slot future is fulfilled before cancellation assertThat(ev1failed).isNotEqualTo(ev3failed); assertThat(assignments2).hasSize(1); assertThat(getAssignmentByExecutionVertexId(assignments2, EV2).getLogicalSlotFuture()) .isNotCompletedExceptionally(); } private static void releaseLogicalSlot(LogicalSlot slot) { slot.tryAssignPayload(new DummyPayload(CompletableFuture.completedFuture(null))); slot.releaseSlot(new Throwable()); } @Test void testBulkClearIfPhysicalSlotRequestFails() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); context.getSlotProvider() .getResultForRequestId(slotRequestId) .completeExceptionally(new Throwable()); PhysicalSlotRequestBulk bulk = bulkChecker.getBulk(); assertThat(bulk.getPendingRequests()).isEmpty(); } @Test void failLogicalSlotsIfPhysicalSlotIsFailed() { final TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = AllocationContext. newBuilder () .addGroup(EV1, EV2) .withBulkChecker(bulkChecker) .withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithFailingPhysicalSlotCreation( new FlinkException("test failure"))) .build(); final Map<ExecutionAttemptID, ExecutionSlotAssignment> allocatedSlots = context.allocateSlotsFor(EV1, EV2); for (ExecutionSlotAssignment allocatedSlot : allocatedSlots.values()) { assertThat(allocatedSlot.getLogicalSlotFuture()).isCompletedExceptionally(); } assertThat(bulkChecker.getBulk().getPendingRequests()).isEmpty(); final Set<SlotRequestId> requests = context.getSlotProvider().getRequests().keySet(); assertThat(context.getSlotProvider().getCancellations().keySet()).isEqualTo(requests); } @Test void testSlotRequestProfileFromExecutionSlotSharingGroup() { final ResourceProfile resourceProfile1 = ResourceProfile.fromResources(1, 10); final ResourceProfile resourceProfile2 = ResourceProfile.fromResources(2, 20); final AllocationContext context = AllocationContext. newBuilder () .addGroupAndResource(resourceProfile1, EV1, EV3) .addGroupAndResource(resourceProfile2, EV2, EV4) .build(); context.allocateSlotsFor(EV1, EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(2); assertThat( context.getSlotProvider().getRequests().values().stream() .map(PhysicalSlotRequest::getSlotProfile) .map(SlotProfile::getPhysicalSlotResourceProfile) .collect(Collectors.toList())) .containsExactlyInAnyOrder(resourceProfile1, resourceProfile2); } @Test void testSlotProviderBatchSlotRequestTimeoutCheckIsDisabled() { final AllocationContext context = AllocationContext. newBuilder ().build(); assertThat(context.getSlotProvider().isBatchSlotRequestTimeoutCheckEnabled()).isFalse(); } private static List<ExecutionVertexID> getAssignIds( Collection<ExecutionSlotAssignment> assignments) { return assignments.stream() .map(ExecutionSlotAssignment::getExecutionAttemptId) .map(ExecutionAttemptID::getExecutionVertexId) .collect(Collectors.toList()); } private static AllocationContext createBulkCheckerContextWithEv12GroupAndEv3Group( PhysicalSlotRequestBulkChecker bulkChecker) { return AllocationContext. newBuilder () .addGroup(EV1, EV2) .addGroup(EV3) .withBulkChecker(bulkChecker) .withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation()) .build(); } private static ResourceProfile fulfilOneOfTwoSlotRequestsAndGetPendingProfile( AllocationContext context, AllocationID allocationId) { Map<SlotRequestId, PhysicalSlotRequest> requests = context.getSlotProvider().getRequests(); List<SlotRequestId> slotRequestIds = new ArrayList<>(requests.keySet()); assertThat(slotRequestIds).hasSize(2); SlotRequestId slotRequestId1 = slotRequestIds.get(0); SlotRequestId slotRequestId2 = slotRequestIds.get(1); context.getSlotProvider() .getResultForRequestId(slotRequestId1) .complete(TestingPhysicalSlot.builder().withAllocationID(allocationId).build()); return requests.get(slotRequestId2).getSlotProfile().getPhysicalSlotResourceProfile(); } private static ExecutionSlotAssignment getAssignmentByExecutionVertexId( Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments, ExecutionVertexID executionVertexId) { return assignments.entrySet().stream() .filter(entry -> entry.getKey().getExecutionVertexId().equals(executionVertexId)) .map(Map.Entry::getValue) .collect(Collectors.toList()) .get(0); } private static class AllocationContext { private final TestingPhysicalSlotProvider slotProvider; private final TestingSlotSharingStrategy slotSharingStrategy; private final SlotSharingExecutionSlotAllocator allocator; private final TestingSharedSlotProfileRetrieverFactory slotProfileRetrieverFactory; private AllocationContext( TestingPhysicalSlotProvider slotProvider, TestingSlotSharingStrategy slotSharingStrategy, SlotSharingExecutionSlotAllocator allocator, TestingSharedSlotProfileRetrieverFactory slotProfileRetrieverFactory) { this.slotProvider = slotProvider; this.slotSharingStrategy = slotSharingStrategy; this.allocator = allocator; this.slotProfileRetrieverFactory = slotProfileRetrieverFactory; } private SlotSharingExecutionSlotAllocator getAllocator() { return allocator; } private Map<ExecutionAttemptID, ExecutionSlotAssignment> allocateSlotsFor( ExecutionVertexID... ids) { return allocator.allocateSlotsFor( Arrays.stream(ids) .map( executionVertexId -> createExecutionAttemptId(executionVertexId, 0)) .collect(Collectors.toList())); } private TestingSlotSharingStrategy getSlotSharingStrategy() { return slotSharingStrategy; } private TestingPhysicalSlotProvider
|
java
|
{ TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); // allocate 2 physical slots for 2 groups Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments1 = context.allocateSlotsFor(EV1, EV3); fulfilOneOfTwoSlotRequestsAndGetPendingProfile(context, new AllocationID()); PhysicalSlotRequestBulk bulk1 = bulkChecker.getBulk(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments2 = context.allocateSlotsFor(EV2); // cancelling of (EV1, EV3) releases assignments1 and only one physical slot for EV3 // the second physical slot is held by sharing EV2 from the next bulk bulk1.cancel(new Throwable()); // return completed logical slot to clear shared slot and release physical slot assertThat(assignments1).hasSize(2); CompletableFuture<LogicalSlot> ev1slot = getAssignmentByExecutionVertexId(assignments1, EV1).getLogicalSlotFuture(); boolean ev1failed = ev1slot.isCompletedExceptionally(); CompletableFuture<LogicalSlot> ev3slot = getAssignmentByExecutionVertexId(assignments1, EV3).getLogicalSlotFuture(); boolean ev3failed = ev3slot.isCompletedExceptionally(); LogicalSlot slot = ev1failed ? ev3slot.join() : ev1slot.join(); releaseLogicalSlot(slot); // EV3 needs again a physical slot, therefore there are 3 requests overall context.allocateSlotsFor(EV1, EV3); assertThat(context.getSlotProvider().getRequests()).hasSize(3); // either EV1 or EV3 logical slot future is fulfilled before cancellation assertThat(ev1failed).isNotEqualTo(ev3failed); assertThat(assignments2).hasSize(1); assertThat(getAssignmentByExecutionVertexId(assignments2, EV2).getLogicalSlotFuture()) .isNotCompletedExceptionally(); } private static void releaseLogicalSlot(LogicalSlot slot) { slot.tryAssignPayload(new DummyPayload(CompletableFuture.completedFuture(null))); slot.releaseSlot(new Throwable()); } @Test void testBulkClearIfPhysicalSlotRequestFails() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); context.getSlotProvider() .getResultForRequestId(slotRequestId) .completeExceptionally(new Throwable()); PhysicalSlotRequestBulk bulk = bulkChecker.getBulk(); assertThat(bulk.getPendingRequests()).isEmpty(); } @Test void failLogicalSlotsIfPhysicalSlotIsFailed() { final TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1, EV2) .withBulkChecker(bulkChecker) .withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithFailingPhysicalSlotCreation( new FlinkException("test failure"))) .build(); final Map<ExecutionAttemptID, ExecutionSlotAssignment> allocatedSlots = context.allocateSlotsFor(EV1, EV2); for (ExecutionSlotAssignment allocatedSlot : allocatedSlots.values()) { assertThat(allocatedSlot.getLogicalSlotFuture()).isCompletedExceptionally(); } assertThat(bulkChecker.getBulk().getPendingRequests()).isEmpty(); final Set<SlotRequestId> requests = context.getSlotProvider().getRequests().keySet(); assertThat(context.getSlotProvider().getCancellations().keySet()).isEqualTo(requests); } @Test void testSlotRequestProfileFromExecutionSlotSharingGroup() { final ResourceProfile resourceProfile1 = ResourceProfile.fromResources(1, 10); final ResourceProfile resourceProfile2 = ResourceProfile.fromResources(2, 20); final AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroupAndResource(resourceProfile1, EV1, EV3) .addGroupAndResource(resourceProfile2, EV2, EV4) .build(); context.allocateSlotsFor(EV1, EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(2); assertThat( context.getSlotProvider().getRequests().values().stream() .map(PhysicalSlotRequest::getSlotProfile) .map(SlotProfile::getPhysicalSlotResourceProfile) .collect(Collectors.toList())) .containsExactlyInAnyOrder(resourceProfile1, resourceProfile2); } @Test void testSlotProviderBatchSlotRequestTimeoutCheckIsDisabled() { final AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().build(); assertThat(context.getSlotProvider().isBatchSlotRequestTimeoutCheckEnabled()).isFalse(); } private static List<ExecutionVertexID> getAssignIds( Collection<ExecutionSlotAssignment> assignments) { return assignments.stream() .map(ExecutionSlotAssignment::getExecutionAttemptId) .map(ExecutionAttemptID::getExecutionVertexId) .collect(Collectors.toList()); } private static AllocationContext createBulkCheckerContextWithEv12GroupAndEv3Group( PhysicalSlotRequestBulkChecker bulkChecker) { return AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1, EV2) .addGroup(EV3) .withBulkChecker(bulkChecker) .withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation()) .build(); } private static ResourceProfile fulfilOneOfTwoSlotRequestsAndGetPendingProfile( AllocationContext context, AllocationID allocationId) { Map<SlotRequestId, PhysicalSlotRequest> requests = context.getSlotProvider().getRequests(); List<SlotRequestId> slotRequestIds = new ArrayList<>(requests.keySet()); assertThat(slotRequestIds).hasSize(2); SlotRequestId slotRequestId1 = slotRequestIds.get(0); SlotRequestId slotRequestId2 = slotRequestIds.get(1); context.getSlotProvider() .getResultForRequestId(slotRequestId1) .complete(TestingPhysicalSlot.builder().withAllocationID(allocationId).build()); return requests.get(slotRequestId2).getSlotProfile().getPhysicalSlotResourceProfile(); } private static ExecutionSlotAssignment getAssignmentByExecutionVertexId( Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments, ExecutionVertexID executionVertexId) { return assignments.entrySet().stream() .filter(entry -> entry.getKey().getExecutionVertexId().equals(executionVertexId)) .map(Map.Entry::getValue) .collect(Collectors.toList()) .get(0); } private static class AllocationContext { private final TestingPhysicalSlotProvider slotProvider; private final TestingSlotSharingStrategy slotSharingStrategy; private final SlotSharingExecutionSlotAllocator allocator; private final TestingSharedSlotProfileRetrieverFactory slotProfileRetrieverFactory; private AllocationContext( TestingPhysicalSlotProvider slotProvider, TestingSlotSharingStrategy slotSharingStrategy, SlotSharingExecutionSlotAllocator allocator, TestingSharedSlotProfileRetrieverFactory slotProfileRetrieverFactory) { this.slotProvider = slotProvider; this.slotSharingStrategy = slotSharingStrategy; this.allocator = allocator; this.slotProfileRetrieverFactory = slotProfileRetrieverFactory; } private SlotSharingExecutionSlotAllocator getAllocator() { return allocator; } private Map<ExecutionAttemptID, ExecutionSlotAssignment> allocateSlotsFor( ExecutionVertexID... ids) { return allocator.allocateSlotsFor( Arrays.stream(ids) .map( executionVertexId -> createExecutionAttemptId(executionVertexId, 0)) .collect(Collectors.toList())); } private TestingSlotSharingStrategy getSlotSharingStrategy() { return slotSharingStrategy; } private TestingPhysicalSlotProvider getSlotProvider() { return slotProvider; } private TestingSharedSlotProfileRetrieverFactory getSlotProfileRetrieverFactory() { return slotProfileRetrieverFactory; } private static Builder <mask> <mask> <mask> <mask> () { return new Builder(); } private static class Builder { private final Map<ExecutionVertexID[], ResourceProfile> groups = new HashMap<>(); private boolean slotWillBeOccupiedIndefinitely = false; private PhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); private TestingPhysicalSlotProvider physicalSlotProvider = TestingPhysicalSlotProvider.createWithInfiniteSlotCreation(); private Builder addGroup(ExecutionVertexID... group)
|
{ TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); // allocate 2 physical slots for 2 groups Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments1 = context.allocateSlotsFor(EV1, EV3); fulfilOneOfTwoSlotRequestsAndGetPendingProfile(context, new AllocationID()); PhysicalSlotRequestBulk bulk1 = bulkChecker.getBulk(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments2 = context.allocateSlotsFor(EV2); // cancelling of (EV1, EV3) releases assignments1 and only one physical slot for EV3 // the second physical slot is held by sharing EV2 from the next bulk bulk1.cancel(new Throwable()); // return completed logical slot to clear shared slot and release physical slot assertThat(assignments1).hasSize(2); CompletableFuture<LogicalSlot> ev1slot = getAssignmentByExecutionVertexId(assignments1, EV1).getLogicalSlotFuture(); boolean ev1failed = ev1slot.isCompletedExceptionally(); CompletableFuture<LogicalSlot> ev3slot = getAssignmentByExecutionVertexId(assignments1, EV3).getLogicalSlotFuture(); boolean ev3failed = ev3slot.isCompletedExceptionally(); LogicalSlot slot = ev1failed ? ev3slot.join() : ev1slot.join(); releaseLogicalSlot(slot); // EV3 needs again a physical slot, therefore there are 3 requests overall context.allocateSlotsFor(EV1, EV3); assertThat(context.getSlotProvider().getRequests()).hasSize(3); // either EV1 or EV3 logical slot future is fulfilled before cancellation assertThat(ev1failed).isNotEqualTo(ev3failed); assertThat(assignments2).hasSize(1); assertThat(getAssignmentByExecutionVertexId(assignments2, EV2).getLogicalSlotFuture()) .isNotCompletedExceptionally(); } private static void releaseLogicalSlot(LogicalSlot slot) { slot.tryAssignPayload(new DummyPayload(CompletableFuture.completedFuture(null))); slot.releaseSlot(new Throwable()); } @Test void testBulkClearIfPhysicalSlotRequestFails() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); context.getSlotProvider() .getResultForRequestId(slotRequestId) .completeExceptionally(new Throwable()); PhysicalSlotRequestBulk bulk = bulkChecker.getBulk(); assertThat(bulk.getPendingRequests()).isEmpty(); } @Test void failLogicalSlotsIfPhysicalSlotIsFailed() { final TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = AllocationContext. newBuilder () .addGroup(EV1, EV2) .withBulkChecker(bulkChecker) .withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithFailingPhysicalSlotCreation( new FlinkException("test failure"))) .build(); final Map<ExecutionAttemptID, ExecutionSlotAssignment> allocatedSlots = context.allocateSlotsFor(EV1, EV2); for (ExecutionSlotAssignment allocatedSlot : allocatedSlots.values()) { assertThat(allocatedSlot.getLogicalSlotFuture()).isCompletedExceptionally(); } assertThat(bulkChecker.getBulk().getPendingRequests()).isEmpty(); final Set<SlotRequestId> requests = context.getSlotProvider().getRequests().keySet(); assertThat(context.getSlotProvider().getCancellations().keySet()).isEqualTo(requests); } @Test void testSlotRequestProfileFromExecutionSlotSharingGroup() { final ResourceProfile resourceProfile1 = ResourceProfile.fromResources(1, 10); final ResourceProfile resourceProfile2 = ResourceProfile.fromResources(2, 20); final AllocationContext context = AllocationContext. newBuilder () .addGroupAndResource(resourceProfile1, EV1, EV3) .addGroupAndResource(resourceProfile2, EV2, EV4) .build(); context.allocateSlotsFor(EV1, EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(2); assertThat( context.getSlotProvider().getRequests().values().stream() .map(PhysicalSlotRequest::getSlotProfile) .map(SlotProfile::getPhysicalSlotResourceProfile) .collect(Collectors.toList())) .containsExactlyInAnyOrder(resourceProfile1, resourceProfile2); } @Test void testSlotProviderBatchSlotRequestTimeoutCheckIsDisabled() { final AllocationContext context = AllocationContext. newBuilder ().build(); assertThat(context.getSlotProvider().isBatchSlotRequestTimeoutCheckEnabled()).isFalse(); } private static List<ExecutionVertexID> getAssignIds( Collection<ExecutionSlotAssignment> assignments) { return assignments.stream() .map(ExecutionSlotAssignment::getExecutionAttemptId) .map(ExecutionAttemptID::getExecutionVertexId) .collect(Collectors.toList()); } private static AllocationContext createBulkCheckerContextWithEv12GroupAndEv3Group( PhysicalSlotRequestBulkChecker bulkChecker) { return AllocationContext. newBuilder () .addGroup(EV1, EV2) .addGroup(EV3) .withBulkChecker(bulkChecker) .withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation()) .build(); } private static ResourceProfile fulfilOneOfTwoSlotRequestsAndGetPendingProfile( AllocationContext context, AllocationID allocationId) { Map<SlotRequestId, PhysicalSlotRequest> requests = context.getSlotProvider().getRequests(); List<SlotRequestId> slotRequestIds = new ArrayList<>(requests.keySet()); assertThat(slotRequestIds).hasSize(2); SlotRequestId slotRequestId1 = slotRequestIds.get(0); SlotRequestId slotRequestId2 = slotRequestIds.get(1); context.getSlotProvider() .getResultForRequestId(slotRequestId1) .complete(TestingPhysicalSlot.builder().withAllocationID(allocationId).build()); return requests.get(slotRequestId2).getSlotProfile().getPhysicalSlotResourceProfile(); } private static ExecutionSlotAssignment getAssignmentByExecutionVertexId( Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments, ExecutionVertexID executionVertexId) { return assignments.entrySet().stream() .filter(entry -> entry.getKey().getExecutionVertexId().equals(executionVertexId)) .map(Map.Entry::getValue) .collect(Collectors.toList()) .get(0); } private static class AllocationContext { private final TestingPhysicalSlotProvider slotProvider; private final TestingSlotSharingStrategy slotSharingStrategy; private final SlotSharingExecutionSlotAllocator allocator; private final TestingSharedSlotProfileRetrieverFactory slotProfileRetrieverFactory; private AllocationContext( TestingPhysicalSlotProvider slotProvider, TestingSlotSharingStrategy slotSharingStrategy, SlotSharingExecutionSlotAllocator allocator, TestingSharedSlotProfileRetrieverFactory slotProfileRetrieverFactory) { this.slotProvider = slotProvider; this.slotSharingStrategy = slotSharingStrategy; this.allocator = allocator; this.slotProfileRetrieverFactory = slotProfileRetrieverFactory; } private SlotSharingExecutionSlotAllocator getAllocator() { return allocator; } private Map<ExecutionAttemptID, ExecutionSlotAssignment> allocateSlotsFor( ExecutionVertexID... ids) { return allocator.allocateSlotsFor( Arrays.stream(ids) .map( executionVertexId -> createExecutionAttemptId(executionVertexId, 0)) .collect(Collectors.toList())); } private TestingSlotSharingStrategy getSlotSharingStrategy() { return slotSharingStrategy; } private TestingPhysicalSlotProvider getSlotProvider() { return slotProvider; } private TestingSharedSlotProfileRetrieverFactory getSlotProfileRetrieverFactory() { return slotProfileRetrieverFactory; } private static Builder newBuilder () { return new Builder(); } private static class Builder { private final Map<ExecutionVertexID[], ResourceProfile> groups = new HashMap<>(); private boolean slotWillBeOccupiedIndefinitely = false; private PhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); private TestingPhysicalSlotProvider physicalSlotProvider = TestingPhysicalSlotProvider.createWithInfiniteSlotCreation(); private Builder addGroup(ExecutionVertexID... group)
|
java
|
= bulkChecker.getBulk(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments2 = context.allocateSlotsFor(EV2); // cancelling of (EV1, EV3) releases assignments1 and only one physical slot for EV3 // the second physical slot is held by sharing EV2 from the next bulk bulk1.cancel(new Throwable()); // return completed logical slot to clear shared slot and release physical slot assertThat(assignments1).hasSize(2); CompletableFuture<LogicalSlot> ev1slot = getAssignmentByExecutionVertexId(assignments1, EV1).getLogicalSlotFuture(); boolean ev1failed = ev1slot.isCompletedExceptionally(); CompletableFuture<LogicalSlot> ev3slot = getAssignmentByExecutionVertexId(assignments1, EV3).getLogicalSlotFuture(); boolean ev3failed = ev3slot.isCompletedExceptionally(); LogicalSlot slot = ev1failed ? ev3slot.join() : ev1slot.join(); releaseLogicalSlot(slot); // EV3 needs again a physical slot, therefore there are 3 requests overall context.allocateSlotsFor(EV1, EV3); assertThat(context.getSlotProvider().getRequests()).hasSize(3); // either EV1 or EV3 logical slot future is fulfilled before cancellation assertThat(ev1failed).isNotEqualTo(ev3failed); assertThat(assignments2).hasSize(1); assertThat(getAssignmentByExecutionVertexId(assignments2, EV2).getLogicalSlotFuture()) .isNotCompletedExceptionally(); } private static void releaseLogicalSlot(LogicalSlot slot) { slot.tryAssignPayload(new DummyPayload(CompletableFuture.completedFuture(null))); slot.releaseSlot(new Throwable()); } @Test void testBulkClearIfPhysicalSlotRequestFails() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); context.getSlotProvider() .getResultForRequestId(slotRequestId) .completeExceptionally(new Throwable()); PhysicalSlotRequestBulk bulk = bulkChecker.getBulk(); assertThat(bulk.getPendingRequests()).isEmpty(); } @Test void failLogicalSlotsIfPhysicalSlotIsFailed() { final TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1, EV2) .withBulkChecker(bulkChecker) .withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithFailingPhysicalSlotCreation( new FlinkException("test failure"))) .build(); final Map<ExecutionAttemptID, ExecutionSlotAssignment> allocatedSlots = context.allocateSlotsFor(EV1, EV2); for (ExecutionSlotAssignment allocatedSlot : allocatedSlots.values()) { assertThat(allocatedSlot.getLogicalSlotFuture()).isCompletedExceptionally(); } assertThat(bulkChecker.getBulk().getPendingRequests()).isEmpty(); final Set<SlotRequestId> requests = context.getSlotProvider().getRequests().keySet(); assertThat(context.getSlotProvider().getCancellations().keySet()).isEqualTo(requests); } @Test void testSlotRequestProfileFromExecutionSlotSharingGroup() { final ResourceProfile resourceProfile1 = ResourceProfile.fromResources(1, 10); final ResourceProfile resourceProfile2 = ResourceProfile.fromResources(2, 20); final AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroupAndResource(resourceProfile1, EV1, EV3) .addGroupAndResource(resourceProfile2, EV2, EV4) .build(); context.allocateSlotsFor(EV1, EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(2); assertThat( context.getSlotProvider().getRequests().values().stream() .map(PhysicalSlotRequest::getSlotProfile) .map(SlotProfile::getPhysicalSlotResourceProfile) .collect(Collectors.toList())) .containsExactlyInAnyOrder(resourceProfile1, resourceProfile2); } @Test void testSlotProviderBatchSlotRequestTimeoutCheckIsDisabled() { final AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().build(); assertThat(context.getSlotProvider().isBatchSlotRequestTimeoutCheckEnabled()).isFalse(); } private static List<ExecutionVertexID> getAssignIds( Collection<ExecutionSlotAssignment> assignments) { return assignments.stream() .map(ExecutionSlotAssignment::getExecutionAttemptId) .map(ExecutionAttemptID::getExecutionVertexId) .collect(Collectors.toList()); } private static AllocationContext createBulkCheckerContextWithEv12GroupAndEv3Group( PhysicalSlotRequestBulkChecker bulkChecker) { return AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1, EV2) .addGroup(EV3) .withBulkChecker(bulkChecker) .withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation()) .build(); } private static ResourceProfile fulfilOneOfTwoSlotRequestsAndGetPendingProfile( AllocationContext context, AllocationID allocationId) { Map<SlotRequestId, PhysicalSlotRequest> requests = context.getSlotProvider().getRequests(); List<SlotRequestId> slotRequestIds = new ArrayList<>(requests.keySet()); assertThat(slotRequestIds).hasSize(2); SlotRequestId slotRequestId1 = slotRequestIds.get(0); SlotRequestId slotRequestId2 = slotRequestIds.get(1); context.getSlotProvider() .getResultForRequestId(slotRequestId1) .complete(TestingPhysicalSlot.builder().withAllocationID(allocationId).build()); return requests.get(slotRequestId2).getSlotProfile().getPhysicalSlotResourceProfile(); } private static ExecutionSlotAssignment getAssignmentByExecutionVertexId( Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments, ExecutionVertexID executionVertexId) { return assignments.entrySet().stream() .filter(entry -> entry.getKey().getExecutionVertexId().equals(executionVertexId)) .map(Map.Entry::getValue) .collect(Collectors.toList()) .get(0); } private static class AllocationContext { private final TestingPhysicalSlotProvider slotProvider; private final TestingSlotSharingStrategy slotSharingStrategy; private final SlotSharingExecutionSlotAllocator allocator; private final TestingSharedSlotProfileRetrieverFactory slotProfileRetrieverFactory; private AllocationContext( TestingPhysicalSlotProvider slotProvider, TestingSlotSharingStrategy slotSharingStrategy, SlotSharingExecutionSlotAllocator allocator, TestingSharedSlotProfileRetrieverFactory slotProfileRetrieverFactory) { this.slotProvider = slotProvider; this.slotSharingStrategy = slotSharingStrategy; this.allocator = allocator; this.slotProfileRetrieverFactory = slotProfileRetrieverFactory; } private SlotSharingExecutionSlotAllocator getAllocator() { return allocator; } private Map<ExecutionAttemptID, ExecutionSlotAssignment> allocateSlotsFor( ExecutionVertexID... ids) { return allocator.allocateSlotsFor( Arrays.stream(ids) .map( executionVertexId -> createExecutionAttemptId(executionVertexId, 0)) .collect(Collectors.toList())); } private TestingSlotSharingStrategy getSlotSharingStrategy() { return slotSharingStrategy; } private TestingPhysicalSlotProvider getSlotProvider() { return slotProvider; } private TestingSharedSlotProfileRetrieverFactory getSlotProfileRetrieverFactory() { return slotProfileRetrieverFactory; } private static Builder <mask> <mask> <mask> <mask> () { return new Builder(); } private static class Builder { private final Map<ExecutionVertexID[], ResourceProfile> groups = new HashMap<>(); private boolean slotWillBeOccupiedIndefinitely = false; private PhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); private TestingPhysicalSlotProvider physicalSlotProvider = TestingPhysicalSlotProvider.createWithInfiniteSlotCreation(); private Builder addGroup(ExecutionVertexID... group) { groups.put(group, ResourceProfile.UNKNOWN); return this; } private Builder addGroupAndResource( ResourceProfile resourceProfile, ExecutionVertexID... group) { groups.put(group, resourceProfile); return this; } private Builder setSlotWillBeOccupiedIndefinitely( boolean slotWillBeOccupiedIndefinitely) { this.slotWillBeOccupiedIndefinitely = slotWillBeOccupiedIndefinitely; return
|
= bulkChecker.getBulk(); Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments2 = context.allocateSlotsFor(EV2); // cancelling of (EV1, EV3) releases assignments1 and only one physical slot for EV3 // the second physical slot is held by sharing EV2 from the next bulk bulk1.cancel(new Throwable()); // return completed logical slot to clear shared slot and release physical slot assertThat(assignments1).hasSize(2); CompletableFuture<LogicalSlot> ev1slot = getAssignmentByExecutionVertexId(assignments1, EV1).getLogicalSlotFuture(); boolean ev1failed = ev1slot.isCompletedExceptionally(); CompletableFuture<LogicalSlot> ev3slot = getAssignmentByExecutionVertexId(assignments1, EV3).getLogicalSlotFuture(); boolean ev3failed = ev3slot.isCompletedExceptionally(); LogicalSlot slot = ev1failed ? ev3slot.join() : ev1slot.join(); releaseLogicalSlot(slot); // EV3 needs again a physical slot, therefore there are 3 requests overall context.allocateSlotsFor(EV1, EV3); assertThat(context.getSlotProvider().getRequests()).hasSize(3); // either EV1 or EV3 logical slot future is fulfilled before cancellation assertThat(ev1failed).isNotEqualTo(ev3failed); assertThat(assignments2).hasSize(1); assertThat(getAssignmentByExecutionVertexId(assignments2, EV2).getLogicalSlotFuture()) .isNotCompletedExceptionally(); } private static void releaseLogicalSlot(LogicalSlot slot) { slot.tryAssignPayload(new DummyPayload(CompletableFuture.completedFuture(null))); slot.releaseSlot(new Throwable()); } @Test void testBulkClearIfPhysicalSlotRequestFails() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); context.getSlotProvider() .getResultForRequestId(slotRequestId) .completeExceptionally(new Throwable()); PhysicalSlotRequestBulk bulk = bulkChecker.getBulk(); assertThat(bulk.getPendingRequests()).isEmpty(); } @Test void failLogicalSlotsIfPhysicalSlotIsFailed() { final TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = AllocationContext. newBuilder () .addGroup(EV1, EV2) .withBulkChecker(bulkChecker) .withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithFailingPhysicalSlotCreation( new FlinkException("test failure"))) .build(); final Map<ExecutionAttemptID, ExecutionSlotAssignment> allocatedSlots = context.allocateSlotsFor(EV1, EV2); for (ExecutionSlotAssignment allocatedSlot : allocatedSlots.values()) { assertThat(allocatedSlot.getLogicalSlotFuture()).isCompletedExceptionally(); } assertThat(bulkChecker.getBulk().getPendingRequests()).isEmpty(); final Set<SlotRequestId> requests = context.getSlotProvider().getRequests().keySet(); assertThat(context.getSlotProvider().getCancellations().keySet()).isEqualTo(requests); } @Test void testSlotRequestProfileFromExecutionSlotSharingGroup() { final ResourceProfile resourceProfile1 = ResourceProfile.fromResources(1, 10); final ResourceProfile resourceProfile2 = ResourceProfile.fromResources(2, 20); final AllocationContext context = AllocationContext. newBuilder () .addGroupAndResource(resourceProfile1, EV1, EV3) .addGroupAndResource(resourceProfile2, EV2, EV4) .build(); context.allocateSlotsFor(EV1, EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(2); assertThat( context.getSlotProvider().getRequests().values().stream() .map(PhysicalSlotRequest::getSlotProfile) .map(SlotProfile::getPhysicalSlotResourceProfile) .collect(Collectors.toList())) .containsExactlyInAnyOrder(resourceProfile1, resourceProfile2); } @Test void testSlotProviderBatchSlotRequestTimeoutCheckIsDisabled() { final AllocationContext context = AllocationContext. newBuilder ().build(); assertThat(context.getSlotProvider().isBatchSlotRequestTimeoutCheckEnabled()).isFalse(); } private static List<ExecutionVertexID> getAssignIds( Collection<ExecutionSlotAssignment> assignments) { return assignments.stream() .map(ExecutionSlotAssignment::getExecutionAttemptId) .map(ExecutionAttemptID::getExecutionVertexId) .collect(Collectors.toList()); } private static AllocationContext createBulkCheckerContextWithEv12GroupAndEv3Group( PhysicalSlotRequestBulkChecker bulkChecker) { return AllocationContext. newBuilder () .addGroup(EV1, EV2) .addGroup(EV3) .withBulkChecker(bulkChecker) .withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation()) .build(); } private static ResourceProfile fulfilOneOfTwoSlotRequestsAndGetPendingProfile( AllocationContext context, AllocationID allocationId) { Map<SlotRequestId, PhysicalSlotRequest> requests = context.getSlotProvider().getRequests(); List<SlotRequestId> slotRequestIds = new ArrayList<>(requests.keySet()); assertThat(slotRequestIds).hasSize(2); SlotRequestId slotRequestId1 = slotRequestIds.get(0); SlotRequestId slotRequestId2 = slotRequestIds.get(1); context.getSlotProvider() .getResultForRequestId(slotRequestId1) .complete(TestingPhysicalSlot.builder().withAllocationID(allocationId).build()); return requests.get(slotRequestId2).getSlotProfile().getPhysicalSlotResourceProfile(); } private static ExecutionSlotAssignment getAssignmentByExecutionVertexId( Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments, ExecutionVertexID executionVertexId) { return assignments.entrySet().stream() .filter(entry -> entry.getKey().getExecutionVertexId().equals(executionVertexId)) .map(Map.Entry::getValue) .collect(Collectors.toList()) .get(0); } private static class AllocationContext { private final TestingPhysicalSlotProvider slotProvider; private final TestingSlotSharingStrategy slotSharingStrategy; private final SlotSharingExecutionSlotAllocator allocator; private final TestingSharedSlotProfileRetrieverFactory slotProfileRetrieverFactory; private AllocationContext( TestingPhysicalSlotProvider slotProvider, TestingSlotSharingStrategy slotSharingStrategy, SlotSharingExecutionSlotAllocator allocator, TestingSharedSlotProfileRetrieverFactory slotProfileRetrieverFactory) { this.slotProvider = slotProvider; this.slotSharingStrategy = slotSharingStrategy; this.allocator = allocator; this.slotProfileRetrieverFactory = slotProfileRetrieverFactory; } private SlotSharingExecutionSlotAllocator getAllocator() { return allocator; } private Map<ExecutionAttemptID, ExecutionSlotAssignment> allocateSlotsFor( ExecutionVertexID... ids) { return allocator.allocateSlotsFor( Arrays.stream(ids) .map( executionVertexId -> createExecutionAttemptId(executionVertexId, 0)) .collect(Collectors.toList())); } private TestingSlotSharingStrategy getSlotSharingStrategy() { return slotSharingStrategy; } private TestingPhysicalSlotProvider getSlotProvider() { return slotProvider; } private TestingSharedSlotProfileRetrieverFactory getSlotProfileRetrieverFactory() { return slotProfileRetrieverFactory; } private static Builder newBuilder () { return new Builder(); } private static class Builder { private final Map<ExecutionVertexID[], ResourceProfile> groups = new HashMap<>(); private boolean slotWillBeOccupiedIndefinitely = false; private PhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); private TestingPhysicalSlotProvider physicalSlotProvider = TestingPhysicalSlotProvider.createWithInfiniteSlotCreation(); private Builder addGroup(ExecutionVertexID... group) { groups.put(group, ResourceProfile.UNKNOWN); return this; } private Builder addGroupAndResource( ResourceProfile resourceProfile, ExecutionVertexID... group) { groups.put(group, resourceProfile); return this; } private Builder setSlotWillBeOccupiedIndefinitely( boolean slotWillBeOccupiedIndefinitely) { this.slotWillBeOccupiedIndefinitely = slotWillBeOccupiedIndefinitely; return
|
java
|
is held by sharing EV2 from the next bulk bulk1.cancel(new Throwable()); // return completed logical slot to clear shared slot and release physical slot assertThat(assignments1).hasSize(2); CompletableFuture<LogicalSlot> ev1slot = getAssignmentByExecutionVertexId(assignments1, EV1).getLogicalSlotFuture(); boolean ev1failed = ev1slot.isCompletedExceptionally(); CompletableFuture<LogicalSlot> ev3slot = getAssignmentByExecutionVertexId(assignments1, EV3).getLogicalSlotFuture(); boolean ev3failed = ev3slot.isCompletedExceptionally(); LogicalSlot slot = ev1failed ? ev3slot.join() : ev1slot.join(); releaseLogicalSlot(slot); // EV3 needs again a physical slot, therefore there are 3 requests overall context.allocateSlotsFor(EV1, EV3); assertThat(context.getSlotProvider().getRequests()).hasSize(3); // either EV1 or EV3 logical slot future is fulfilled before cancellation assertThat(ev1failed).isNotEqualTo(ev3failed); assertThat(assignments2).hasSize(1); assertThat(getAssignmentByExecutionVertexId(assignments2, EV2).getLogicalSlotFuture()) .isNotCompletedExceptionally(); } private static void releaseLogicalSlot(LogicalSlot slot) { slot.tryAssignPayload(new DummyPayload(CompletableFuture.completedFuture(null))); slot.releaseSlot(new Throwable()); } @Test void testBulkClearIfPhysicalSlotRequestFails() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); context.getSlotProvider() .getResultForRequestId(slotRequestId) .completeExceptionally(new Throwable()); PhysicalSlotRequestBulk bulk = bulkChecker.getBulk(); assertThat(bulk.getPendingRequests()).isEmpty(); } @Test void failLogicalSlotsIfPhysicalSlotIsFailed() { final TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1, EV2) .withBulkChecker(bulkChecker) .withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithFailingPhysicalSlotCreation( new FlinkException("test failure"))) .build(); final Map<ExecutionAttemptID, ExecutionSlotAssignment> allocatedSlots = context.allocateSlotsFor(EV1, EV2); for (ExecutionSlotAssignment allocatedSlot : allocatedSlots.values()) { assertThat(allocatedSlot.getLogicalSlotFuture()).isCompletedExceptionally(); } assertThat(bulkChecker.getBulk().getPendingRequests()).isEmpty(); final Set<SlotRequestId> requests = context.getSlotProvider().getRequests().keySet(); assertThat(context.getSlotProvider().getCancellations().keySet()).isEqualTo(requests); } @Test void testSlotRequestProfileFromExecutionSlotSharingGroup() { final ResourceProfile resourceProfile1 = ResourceProfile.fromResources(1, 10); final ResourceProfile resourceProfile2 = ResourceProfile.fromResources(2, 20); final AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroupAndResource(resourceProfile1, EV1, EV3) .addGroupAndResource(resourceProfile2, EV2, EV4) .build(); context.allocateSlotsFor(EV1, EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(2); assertThat( context.getSlotProvider().getRequests().values().stream() .map(PhysicalSlotRequest::getSlotProfile) .map(SlotProfile::getPhysicalSlotResourceProfile) .collect(Collectors.toList())) .containsExactlyInAnyOrder(resourceProfile1, resourceProfile2); } @Test void testSlotProviderBatchSlotRequestTimeoutCheckIsDisabled() { final AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().build(); assertThat(context.getSlotProvider().isBatchSlotRequestTimeoutCheckEnabled()).isFalse(); } private static List<ExecutionVertexID> getAssignIds( Collection<ExecutionSlotAssignment> assignments) { return assignments.stream() .map(ExecutionSlotAssignment::getExecutionAttemptId) .map(ExecutionAttemptID::getExecutionVertexId) .collect(Collectors.toList()); } private static AllocationContext createBulkCheckerContextWithEv12GroupAndEv3Group( PhysicalSlotRequestBulkChecker bulkChecker) { return AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1, EV2) .addGroup(EV3) .withBulkChecker(bulkChecker) .withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation()) .build(); } private static ResourceProfile fulfilOneOfTwoSlotRequestsAndGetPendingProfile( AllocationContext context, AllocationID allocationId) { Map<SlotRequestId, PhysicalSlotRequest> requests = context.getSlotProvider().getRequests(); List<SlotRequestId> slotRequestIds = new ArrayList<>(requests.keySet()); assertThat(slotRequestIds).hasSize(2); SlotRequestId slotRequestId1 = slotRequestIds.get(0); SlotRequestId slotRequestId2 = slotRequestIds.get(1); context.getSlotProvider() .getResultForRequestId(slotRequestId1) .complete(TestingPhysicalSlot.builder().withAllocationID(allocationId).build()); return requests.get(slotRequestId2).getSlotProfile().getPhysicalSlotResourceProfile(); } private static ExecutionSlotAssignment getAssignmentByExecutionVertexId( Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments, ExecutionVertexID executionVertexId) { return assignments.entrySet().stream() .filter(entry -> entry.getKey().getExecutionVertexId().equals(executionVertexId)) .map(Map.Entry::getValue) .collect(Collectors.toList()) .get(0); } private static class AllocationContext { private final TestingPhysicalSlotProvider slotProvider; private final TestingSlotSharingStrategy slotSharingStrategy; private final SlotSharingExecutionSlotAllocator allocator; private final TestingSharedSlotProfileRetrieverFactory slotProfileRetrieverFactory; private AllocationContext( TestingPhysicalSlotProvider slotProvider, TestingSlotSharingStrategy slotSharingStrategy, SlotSharingExecutionSlotAllocator allocator, TestingSharedSlotProfileRetrieverFactory slotProfileRetrieverFactory) { this.slotProvider = slotProvider; this.slotSharingStrategy = slotSharingStrategy; this.allocator = allocator; this.slotProfileRetrieverFactory = slotProfileRetrieverFactory; } private SlotSharingExecutionSlotAllocator getAllocator() { return allocator; } private Map<ExecutionAttemptID, ExecutionSlotAssignment> allocateSlotsFor( ExecutionVertexID... ids) { return allocator.allocateSlotsFor( Arrays.stream(ids) .map( executionVertexId -> createExecutionAttemptId(executionVertexId, 0)) .collect(Collectors.toList())); } private TestingSlotSharingStrategy getSlotSharingStrategy() { return slotSharingStrategy; } private TestingPhysicalSlotProvider getSlotProvider() { return slotProvider; } private TestingSharedSlotProfileRetrieverFactory getSlotProfileRetrieverFactory() { return slotProfileRetrieverFactory; } private static Builder <mask> <mask> <mask> <mask> () { return new Builder(); } private static class Builder { private final Map<ExecutionVertexID[], ResourceProfile> groups = new HashMap<>(); private boolean slotWillBeOccupiedIndefinitely = false; private PhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); private TestingPhysicalSlotProvider physicalSlotProvider = TestingPhysicalSlotProvider.createWithInfiniteSlotCreation(); private Builder addGroup(ExecutionVertexID... group) { groups.put(group, ResourceProfile.UNKNOWN); return this; } private Builder addGroupAndResource( ResourceProfile resourceProfile, ExecutionVertexID... group) { groups.put(group, resourceProfile); return this; } private Builder setSlotWillBeOccupiedIndefinitely( boolean slotWillBeOccupiedIndefinitely) { this.slotWillBeOccupiedIndefinitely = slotWillBeOccupiedIndefinitely; return this; } private Builder withBulkChecker(PhysicalSlotRequestBulkChecker bulkChecker) { this.bulkChecker = bulkChecker; return this; } private Builder withPhysicalSlotProvider( TestingPhysicalSlotProvider physicalSlotProvider) { this.physicalSlotProvider = physicalSlotProvider; return this; } private
|
is held by sharing EV2 from the next bulk bulk1.cancel(new Throwable()); // return completed logical slot to clear shared slot and release physical slot assertThat(assignments1).hasSize(2); CompletableFuture<LogicalSlot> ev1slot = getAssignmentByExecutionVertexId(assignments1, EV1).getLogicalSlotFuture(); boolean ev1failed = ev1slot.isCompletedExceptionally(); CompletableFuture<LogicalSlot> ev3slot = getAssignmentByExecutionVertexId(assignments1, EV3).getLogicalSlotFuture(); boolean ev3failed = ev3slot.isCompletedExceptionally(); LogicalSlot slot = ev1failed ? ev3slot.join() : ev1slot.join(); releaseLogicalSlot(slot); // EV3 needs again a physical slot, therefore there are 3 requests overall context.allocateSlotsFor(EV1, EV3); assertThat(context.getSlotProvider().getRequests()).hasSize(3); // either EV1 or EV3 logical slot future is fulfilled before cancellation assertThat(ev1failed).isNotEqualTo(ev3failed); assertThat(assignments2).hasSize(1); assertThat(getAssignmentByExecutionVertexId(assignments2, EV2).getLogicalSlotFuture()) .isNotCompletedExceptionally(); } private static void releaseLogicalSlot(LogicalSlot slot) { slot.tryAssignPayload(new DummyPayload(CompletableFuture.completedFuture(null))); slot.releaseSlot(new Throwable()); } @Test void testBulkClearIfPhysicalSlotRequestFails() { TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker); context.allocateSlotsFor(EV1, EV3); SlotRequestId slotRequestId = context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId(); context.getSlotProvider() .getResultForRequestId(slotRequestId) .completeExceptionally(new Throwable()); PhysicalSlotRequestBulk bulk = bulkChecker.getBulk(); assertThat(bulk.getPendingRequests()).isEmpty(); } @Test void failLogicalSlotsIfPhysicalSlotIsFailed() { final TestingPhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); AllocationContext context = AllocationContext. newBuilder () .addGroup(EV1, EV2) .withBulkChecker(bulkChecker) .withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithFailingPhysicalSlotCreation( new FlinkException("test failure"))) .build(); final Map<ExecutionAttemptID, ExecutionSlotAssignment> allocatedSlots = context.allocateSlotsFor(EV1, EV2); for (ExecutionSlotAssignment allocatedSlot : allocatedSlots.values()) { assertThat(allocatedSlot.getLogicalSlotFuture()).isCompletedExceptionally(); } assertThat(bulkChecker.getBulk().getPendingRequests()).isEmpty(); final Set<SlotRequestId> requests = context.getSlotProvider().getRequests().keySet(); assertThat(context.getSlotProvider().getCancellations().keySet()).isEqualTo(requests); } @Test void testSlotRequestProfileFromExecutionSlotSharingGroup() { final ResourceProfile resourceProfile1 = ResourceProfile.fromResources(1, 10); final ResourceProfile resourceProfile2 = ResourceProfile.fromResources(2, 20); final AllocationContext context = AllocationContext. newBuilder () .addGroupAndResource(resourceProfile1, EV1, EV3) .addGroupAndResource(resourceProfile2, EV2, EV4) .build(); context.allocateSlotsFor(EV1, EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(2); assertThat( context.getSlotProvider().getRequests().values().stream() .map(PhysicalSlotRequest::getSlotProfile) .map(SlotProfile::getPhysicalSlotResourceProfile) .collect(Collectors.toList())) .containsExactlyInAnyOrder(resourceProfile1, resourceProfile2); } @Test void testSlotProviderBatchSlotRequestTimeoutCheckIsDisabled() { final AllocationContext context = AllocationContext. newBuilder ().build(); assertThat(context.getSlotProvider().isBatchSlotRequestTimeoutCheckEnabled()).isFalse(); } private static List<ExecutionVertexID> getAssignIds( Collection<ExecutionSlotAssignment> assignments) { return assignments.stream() .map(ExecutionSlotAssignment::getExecutionAttemptId) .map(ExecutionAttemptID::getExecutionVertexId) .collect(Collectors.toList()); } private static AllocationContext createBulkCheckerContextWithEv12GroupAndEv3Group( PhysicalSlotRequestBulkChecker bulkChecker) { return AllocationContext. newBuilder () .addGroup(EV1, EV2) .addGroup(EV3) .withBulkChecker(bulkChecker) .withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation()) .build(); } private static ResourceProfile fulfilOneOfTwoSlotRequestsAndGetPendingProfile( AllocationContext context, AllocationID allocationId) { Map<SlotRequestId, PhysicalSlotRequest> requests = context.getSlotProvider().getRequests(); List<SlotRequestId> slotRequestIds = new ArrayList<>(requests.keySet()); assertThat(slotRequestIds).hasSize(2); SlotRequestId slotRequestId1 = slotRequestIds.get(0); SlotRequestId slotRequestId2 = slotRequestIds.get(1); context.getSlotProvider() .getResultForRequestId(slotRequestId1) .complete(TestingPhysicalSlot.builder().withAllocationID(allocationId).build()); return requests.get(slotRequestId2).getSlotProfile().getPhysicalSlotResourceProfile(); } private static ExecutionSlotAssignment getAssignmentByExecutionVertexId( Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments, ExecutionVertexID executionVertexId) { return assignments.entrySet().stream() .filter(entry -> entry.getKey().getExecutionVertexId().equals(executionVertexId)) .map(Map.Entry::getValue) .collect(Collectors.toList()) .get(0); } private static class AllocationContext { private final TestingPhysicalSlotProvider slotProvider; private final TestingSlotSharingStrategy slotSharingStrategy; private final SlotSharingExecutionSlotAllocator allocator; private final TestingSharedSlotProfileRetrieverFactory slotProfileRetrieverFactory; private AllocationContext( TestingPhysicalSlotProvider slotProvider, TestingSlotSharingStrategy slotSharingStrategy, SlotSharingExecutionSlotAllocator allocator, TestingSharedSlotProfileRetrieverFactory slotProfileRetrieverFactory) { this.slotProvider = slotProvider; this.slotSharingStrategy = slotSharingStrategy; this.allocator = allocator; this.slotProfileRetrieverFactory = slotProfileRetrieverFactory; } private SlotSharingExecutionSlotAllocator getAllocator() { return allocator; } private Map<ExecutionAttemptID, ExecutionSlotAssignment> allocateSlotsFor( ExecutionVertexID... ids) { return allocator.allocateSlotsFor( Arrays.stream(ids) .map( executionVertexId -> createExecutionAttemptId(executionVertexId, 0)) .collect(Collectors.toList())); } private TestingSlotSharingStrategy getSlotSharingStrategy() { return slotSharingStrategy; } private TestingPhysicalSlotProvider getSlotProvider() { return slotProvider; } private TestingSharedSlotProfileRetrieverFactory getSlotProfileRetrieverFactory() { return slotProfileRetrieverFactory; } private static Builder newBuilder () { return new Builder(); } private static class Builder { private final Map<ExecutionVertexID[], ResourceProfile> groups = new HashMap<>(); private boolean slotWillBeOccupiedIndefinitely = false; private PhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); private TestingPhysicalSlotProvider physicalSlotProvider = TestingPhysicalSlotProvider.createWithInfiniteSlotCreation(); private Builder addGroup(ExecutionVertexID... group) { groups.put(group, ResourceProfile.UNKNOWN); return this; } private Builder addGroupAndResource( ResourceProfile resourceProfile, ExecutionVertexID... group) { groups.put(group, resourceProfile); return this; } private Builder setSlotWillBeOccupiedIndefinitely( boolean slotWillBeOccupiedIndefinitely) { this.slotWillBeOccupiedIndefinitely = slotWillBeOccupiedIndefinitely; return this; } private Builder withBulkChecker(PhysicalSlotRequestBulkChecker bulkChecker) { this.bulkChecker = bulkChecker; return this; } private Builder withPhysicalSlotProvider( TestingPhysicalSlotProvider physicalSlotProvider) { this.physicalSlotProvider = physicalSlotProvider; return this; } private
|
java
|
context.allocateSlotsFor(EV1, EV2); for (ExecutionSlotAssignment allocatedSlot : allocatedSlots.values()) { assertThat(allocatedSlot.getLogicalSlotFuture()).isCompletedExceptionally(); } assertThat(bulkChecker.getBulk().getPendingRequests()).isEmpty(); final Set<SlotRequestId> requests = context.getSlotProvider().getRequests().keySet(); assertThat(context.getSlotProvider().getCancellations().keySet()).isEqualTo(requests); } @Test void testSlotRequestProfileFromExecutionSlotSharingGroup() { final ResourceProfile resourceProfile1 = ResourceProfile.fromResources(1, 10); final ResourceProfile resourceProfile2 = ResourceProfile.fromResources(2, 20); final AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> () .addGroupAndResource(resourceProfile1, EV1, EV3) .addGroupAndResource(resourceProfile2, EV2, EV4) .build(); context.allocateSlotsFor(EV1, EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(2); assertThat( context.getSlotProvider().getRequests().values().stream() .map(PhysicalSlotRequest::getSlotProfile) .map(SlotProfile::getPhysicalSlotResourceProfile) .collect(Collectors.toList())) .containsExactlyInAnyOrder(resourceProfile1, resourceProfile2); } @Test void testSlotProviderBatchSlotRequestTimeoutCheckIsDisabled() { final AllocationContext context = AllocationContext. <mask> <mask> <mask> <mask> ().build(); assertThat(context.getSlotProvider().isBatchSlotRequestTimeoutCheckEnabled()).isFalse(); } private static List<ExecutionVertexID> getAssignIds( Collection<ExecutionSlotAssignment> assignments) { return assignments.stream() .map(ExecutionSlotAssignment::getExecutionAttemptId) .map(ExecutionAttemptID::getExecutionVertexId) .collect(Collectors.toList()); } private static AllocationContext createBulkCheckerContextWithEv12GroupAndEv3Group( PhysicalSlotRequestBulkChecker bulkChecker) { return AllocationContext. <mask> <mask> <mask> <mask> () .addGroup(EV1, EV2) .addGroup(EV3) .withBulkChecker(bulkChecker) .withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation()) .build(); } private static ResourceProfile fulfilOneOfTwoSlotRequestsAndGetPendingProfile( AllocationContext context, AllocationID allocationId) { Map<SlotRequestId, PhysicalSlotRequest> requests = context.getSlotProvider().getRequests(); List<SlotRequestId> slotRequestIds = new ArrayList<>(requests.keySet()); assertThat(slotRequestIds).hasSize(2); SlotRequestId slotRequestId1 = slotRequestIds.get(0); SlotRequestId slotRequestId2 = slotRequestIds.get(1); context.getSlotProvider() .getResultForRequestId(slotRequestId1) .complete(TestingPhysicalSlot.builder().withAllocationID(allocationId).build()); return requests.get(slotRequestId2).getSlotProfile().getPhysicalSlotResourceProfile(); } private static ExecutionSlotAssignment getAssignmentByExecutionVertexId( Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments, ExecutionVertexID executionVertexId) { return assignments.entrySet().stream() .filter(entry -> entry.getKey().getExecutionVertexId().equals(executionVertexId)) .map(Map.Entry::getValue) .collect(Collectors.toList()) .get(0); } private static class AllocationContext { private final TestingPhysicalSlotProvider slotProvider; private final TestingSlotSharingStrategy slotSharingStrategy; private final SlotSharingExecutionSlotAllocator allocator; private final TestingSharedSlotProfileRetrieverFactory slotProfileRetrieverFactory; private AllocationContext( TestingPhysicalSlotProvider slotProvider, TestingSlotSharingStrategy slotSharingStrategy, SlotSharingExecutionSlotAllocator allocator, TestingSharedSlotProfileRetrieverFactory slotProfileRetrieverFactory) { this.slotProvider = slotProvider; this.slotSharingStrategy = slotSharingStrategy; this.allocator = allocator; this.slotProfileRetrieverFactory = slotProfileRetrieverFactory; } private SlotSharingExecutionSlotAllocator getAllocator() { return allocator; } private Map<ExecutionAttemptID, ExecutionSlotAssignment> allocateSlotsFor( ExecutionVertexID... ids) { return allocator.allocateSlotsFor( Arrays.stream(ids) .map( executionVertexId -> createExecutionAttemptId(executionVertexId, 0)) .collect(Collectors.toList())); } private TestingSlotSharingStrategy getSlotSharingStrategy() { return slotSharingStrategy; } private TestingPhysicalSlotProvider getSlotProvider() { return slotProvider; } private TestingSharedSlotProfileRetrieverFactory getSlotProfileRetrieverFactory() { return slotProfileRetrieverFactory; } private static Builder <mask> <mask> <mask> <mask> () { return new Builder(); } private static class Builder { private final Map<ExecutionVertexID[], ResourceProfile> groups = new HashMap<>(); private boolean slotWillBeOccupiedIndefinitely = false; private PhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); private TestingPhysicalSlotProvider physicalSlotProvider = TestingPhysicalSlotProvider.createWithInfiniteSlotCreation(); private Builder addGroup(ExecutionVertexID... group) { groups.put(group, ResourceProfile.UNKNOWN); return this; } private Builder addGroupAndResource( ResourceProfile resourceProfile, ExecutionVertexID... group) { groups.put(group, resourceProfile); return this; } private Builder setSlotWillBeOccupiedIndefinitely( boolean slotWillBeOccupiedIndefinitely) { this.slotWillBeOccupiedIndefinitely = slotWillBeOccupiedIndefinitely; return this; } private Builder withBulkChecker(PhysicalSlotRequestBulkChecker bulkChecker) { this.bulkChecker = bulkChecker; return this; } private Builder withPhysicalSlotProvider( TestingPhysicalSlotProvider physicalSlotProvider) { this.physicalSlotProvider = physicalSlotProvider; return this; } private AllocationContext build() { TestingSharedSlotProfileRetrieverFactory sharedSlotProfileRetrieverFactory = new TestingSharedSlotProfileRetrieverFactory(); TestingSlotSharingStrategy slotSharingStrategy = TestingSlotSharingStrategy.createWithGroupsAndResources(groups); SlotSharingExecutionSlotAllocator allocator = new SlotSharingExecutionSlotAllocator( physicalSlotProvider, slotWillBeOccupiedIndefinitely, slotSharingStrategy, sharedSlotProfileRetrieverFactory, bulkChecker, ALLOCATION_TIMEOUT, executionVertexID -> RESOURCE_PROFILE); return new AllocationContext( physicalSlotProvider, slotSharingStrategy, allocator, sharedSlotProfileRetrieverFactory); } } } private static class TestingSlotSharingStrategy implements SlotSharingStrategy { private final Map<ExecutionVertexID, ExecutionSlotSharingGroup> executionSlotSharingGroups; private TestingSlotSharingStrategy( Map<ExecutionVertexID, ExecutionSlotSharingGroup> executionSlotSharingGroups) { this.executionSlotSharingGroups = executionSlotSharingGroups; } @Override public ExecutionSlotSharingGroup getExecutionSlotSharingGroup( ExecutionVertexID executionVertexId) { return executionSlotSharingGroups.get(executionVertexId); } @Override public Set<ExecutionSlotSharingGroup> getExecutionSlotSharingGroups() { return new HashSet<>(executionSlotSharingGroups.values()); } private static TestingSlotSharingStrategy createWithGroupsAndResources( Map<ExecutionVertexID[], ResourceProfile> groupAndResources) { Map<ExecutionVertexID, ExecutionSlotSharingGroup> executionSlotSharingGroups = new HashMap<>(); for (Map.Entry<ExecutionVertexID[], ResourceProfile> groupAndResource : groupAndResources.entrySet()) { SlotSharingGroup slotSharingGroup = new SlotSharingGroup(); slotSharingGroup.setResourceProfile(groupAndResource.getValue()); ExecutionSlotSharingGroup executionSlotSharingGroup = new ExecutionSlotSharingGroup(slotSharingGroup); for (ExecutionVertexID executionVertexId : groupAndResource.getKey()) { executionSlotSharingGroup.addVertex(executionVertexId); executionSlotSharingGroups.put(executionVertexId, executionSlotSharingGroup); } } return new TestingSlotSharingStrategy(executionSlotSharingGroups); } } private static class TestingSharedSlotProfileRetrieverFactory implements SharedSlotProfileRetrieverFactory { private final List<Set<ExecutionVertexID>> askedBulks; private final List<ExecutionSlotSharingGroup> askedGroups; private TestingSharedSlotProfileRetrieverFactory() { this.askedBulks = new ArrayList<>(); this.askedGroups = new ArrayList<>(); } @Override public SharedSlotProfileRetriever createFromBulk(Set<ExecutionVertexID>
|
context.allocateSlotsFor(EV1, EV2); for (ExecutionSlotAssignment allocatedSlot : allocatedSlots.values()) { assertThat(allocatedSlot.getLogicalSlotFuture()).isCompletedExceptionally(); } assertThat(bulkChecker.getBulk().getPendingRequests()).isEmpty(); final Set<SlotRequestId> requests = context.getSlotProvider().getRequests().keySet(); assertThat(context.getSlotProvider().getCancellations().keySet()).isEqualTo(requests); } @Test void testSlotRequestProfileFromExecutionSlotSharingGroup() { final ResourceProfile resourceProfile1 = ResourceProfile.fromResources(1, 10); final ResourceProfile resourceProfile2 = ResourceProfile.fromResources(2, 20); final AllocationContext context = AllocationContext. newBuilder () .addGroupAndResource(resourceProfile1, EV1, EV3) .addGroupAndResource(resourceProfile2, EV2, EV4) .build(); context.allocateSlotsFor(EV1, EV2); assertThat(context.getSlotProvider().getRequests()).hasSize(2); assertThat( context.getSlotProvider().getRequests().values().stream() .map(PhysicalSlotRequest::getSlotProfile) .map(SlotProfile::getPhysicalSlotResourceProfile) .collect(Collectors.toList())) .containsExactlyInAnyOrder(resourceProfile1, resourceProfile2); } @Test void testSlotProviderBatchSlotRequestTimeoutCheckIsDisabled() { final AllocationContext context = AllocationContext. newBuilder ().build(); assertThat(context.getSlotProvider().isBatchSlotRequestTimeoutCheckEnabled()).isFalse(); } private static List<ExecutionVertexID> getAssignIds( Collection<ExecutionSlotAssignment> assignments) { return assignments.stream() .map(ExecutionSlotAssignment::getExecutionAttemptId) .map(ExecutionAttemptID::getExecutionVertexId) .collect(Collectors.toList()); } private static AllocationContext createBulkCheckerContextWithEv12GroupAndEv3Group( PhysicalSlotRequestBulkChecker bulkChecker) { return AllocationContext. newBuilder () .addGroup(EV1, EV2) .addGroup(EV3) .withBulkChecker(bulkChecker) .withPhysicalSlotProvider( TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation()) .build(); } private static ResourceProfile fulfilOneOfTwoSlotRequestsAndGetPendingProfile( AllocationContext context, AllocationID allocationId) { Map<SlotRequestId, PhysicalSlotRequest> requests = context.getSlotProvider().getRequests(); List<SlotRequestId> slotRequestIds = new ArrayList<>(requests.keySet()); assertThat(slotRequestIds).hasSize(2); SlotRequestId slotRequestId1 = slotRequestIds.get(0); SlotRequestId slotRequestId2 = slotRequestIds.get(1); context.getSlotProvider() .getResultForRequestId(slotRequestId1) .complete(TestingPhysicalSlot.builder().withAllocationID(allocationId).build()); return requests.get(slotRequestId2).getSlotProfile().getPhysicalSlotResourceProfile(); } private static ExecutionSlotAssignment getAssignmentByExecutionVertexId( Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments, ExecutionVertexID executionVertexId) { return assignments.entrySet().stream() .filter(entry -> entry.getKey().getExecutionVertexId().equals(executionVertexId)) .map(Map.Entry::getValue) .collect(Collectors.toList()) .get(0); } private static class AllocationContext { private final TestingPhysicalSlotProvider slotProvider; private final TestingSlotSharingStrategy slotSharingStrategy; private final SlotSharingExecutionSlotAllocator allocator; private final TestingSharedSlotProfileRetrieverFactory slotProfileRetrieverFactory; private AllocationContext( TestingPhysicalSlotProvider slotProvider, TestingSlotSharingStrategy slotSharingStrategy, SlotSharingExecutionSlotAllocator allocator, TestingSharedSlotProfileRetrieverFactory slotProfileRetrieverFactory) { this.slotProvider = slotProvider; this.slotSharingStrategy = slotSharingStrategy; this.allocator = allocator; this.slotProfileRetrieverFactory = slotProfileRetrieverFactory; } private SlotSharingExecutionSlotAllocator getAllocator() { return allocator; } private Map<ExecutionAttemptID, ExecutionSlotAssignment> allocateSlotsFor( ExecutionVertexID... ids) { return allocator.allocateSlotsFor( Arrays.stream(ids) .map( executionVertexId -> createExecutionAttemptId(executionVertexId, 0)) .collect(Collectors.toList())); } private TestingSlotSharingStrategy getSlotSharingStrategy() { return slotSharingStrategy; } private TestingPhysicalSlotProvider getSlotProvider() { return slotProvider; } private TestingSharedSlotProfileRetrieverFactory getSlotProfileRetrieverFactory() { return slotProfileRetrieverFactory; } private static Builder newBuilder () { return new Builder(); } private static class Builder { private final Map<ExecutionVertexID[], ResourceProfile> groups = new HashMap<>(); private boolean slotWillBeOccupiedIndefinitely = false; private PhysicalSlotRequestBulkChecker bulkChecker = new TestingPhysicalSlotRequestBulkChecker(); private TestingPhysicalSlotProvider physicalSlotProvider = TestingPhysicalSlotProvider.createWithInfiniteSlotCreation(); private Builder addGroup(ExecutionVertexID... group) { groups.put(group, ResourceProfile.UNKNOWN); return this; } private Builder addGroupAndResource( ResourceProfile resourceProfile, ExecutionVertexID... group) { groups.put(group, resourceProfile); return this; } private Builder setSlotWillBeOccupiedIndefinitely( boolean slotWillBeOccupiedIndefinitely) { this.slotWillBeOccupiedIndefinitely = slotWillBeOccupiedIndefinitely; return this; } private Builder withBulkChecker(PhysicalSlotRequestBulkChecker bulkChecker) { this.bulkChecker = bulkChecker; return this; } private Builder withPhysicalSlotProvider( TestingPhysicalSlotProvider physicalSlotProvider) { this.physicalSlotProvider = physicalSlotProvider; return this; } private AllocationContext build() { TestingSharedSlotProfileRetrieverFactory sharedSlotProfileRetrieverFactory = new TestingSharedSlotProfileRetrieverFactory(); TestingSlotSharingStrategy slotSharingStrategy = TestingSlotSharingStrategy.createWithGroupsAndResources(groups); SlotSharingExecutionSlotAllocator allocator = new SlotSharingExecutionSlotAllocator( physicalSlotProvider, slotWillBeOccupiedIndefinitely, slotSharingStrategy, sharedSlotProfileRetrieverFactory, bulkChecker, ALLOCATION_TIMEOUT, executionVertexID -> RESOURCE_PROFILE); return new AllocationContext( physicalSlotProvider, slotSharingStrategy, allocator, sharedSlotProfileRetrieverFactory); } } } private static class TestingSlotSharingStrategy implements SlotSharingStrategy { private final Map<ExecutionVertexID, ExecutionSlotSharingGroup> executionSlotSharingGroups; private TestingSlotSharingStrategy( Map<ExecutionVertexID, ExecutionSlotSharingGroup> executionSlotSharingGroups) { this.executionSlotSharingGroups = executionSlotSharingGroups; } @Override public ExecutionSlotSharingGroup getExecutionSlotSharingGroup( ExecutionVertexID executionVertexId) { return executionSlotSharingGroups.get(executionVertexId); } @Override public Set<ExecutionSlotSharingGroup> getExecutionSlotSharingGroups() { return new HashSet<>(executionSlotSharingGroups.values()); } private static TestingSlotSharingStrategy createWithGroupsAndResources( Map<ExecutionVertexID[], ResourceProfile> groupAndResources) { Map<ExecutionVertexID, ExecutionSlotSharingGroup> executionSlotSharingGroups = new HashMap<>(); for (Map.Entry<ExecutionVertexID[], ResourceProfile> groupAndResource : groupAndResources.entrySet()) { SlotSharingGroup slotSharingGroup = new SlotSharingGroup(); slotSharingGroup.setResourceProfile(groupAndResource.getValue()); ExecutionSlotSharingGroup executionSlotSharingGroup = new ExecutionSlotSharingGroup(slotSharingGroup); for (ExecutionVertexID executionVertexId : groupAndResource.getKey()) { executionSlotSharingGroup.addVertex(executionVertexId); executionSlotSharingGroups.put(executionVertexId, executionSlotSharingGroup); } } return new TestingSlotSharingStrategy(executionSlotSharingGroups); } } private static class TestingSharedSlotProfileRetrieverFactory implements SharedSlotProfileRetrieverFactory { private final List<Set<ExecutionVertexID>> askedBulks; private final List<ExecutionSlotSharingGroup> askedGroups; private TestingSharedSlotProfileRetrieverFactory() { this.askedBulks = new ArrayList<>(); this.askedGroups = new ArrayList<>(); } @Override public SharedSlotProfileRetriever createFromBulk(Set<ExecutionVertexID>
|
java
|
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.connect.runtime.rest; import org.apache.kafka.common.config.ConfigException; import org.apache.kafka.common.utils.Utils; import org.apache.kafka.connect.errors. <mask> <mask> <mask> <mask> ; import org.apache.kafka.connect.health.ConnectClusterDetails; import org.apache.kafka.connect.rest.ConnectRestExtension; import org.apache.kafka.connect.rest.ConnectRestExtensionContext; import org.apache.kafka.connect.runtime.Herder; import org.apache.kafka.connect.runtime.health.ConnectClusterDetailsImpl; import org.apache.kafka.connect.runtime.health.ConnectClusterStateImpl; import org.apache.kafka.connect.runtime.rest.errors. <mask> <mask> <mask> <mask> Mapper; import org.apache.kafka.connect.runtime.rest.util.SSLUtils; import com.fasterxml.jackson.jakarta.rs.json.JacksonJsonProvider; import org.eclipse.jetty.ee10.servlet.FilterHolder; import org.eclipse.jetty.ee10.servlet.ServletContextHandler; import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.eclipse.jetty.ee10.servlets.HeaderFilter; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.CustomRequestLog; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.Slf4jRequestLogWriter; import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.server.handler.CrossOriginHandler; import org.eclipse.jetty.server.handler.StatisticsHandler; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.glassfish.hk2.utilities.Binder; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.ServerProperties; import org.glassfish.jersey.servlet.ServletContainer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import jakarta.servlet.DispatcherType; import jakarta.ws.rs.core.UriBuilder; /** * Embedded server for the REST API that provides the control plane for Kafka Connect workers. */ public abstract class RestServer { // TODO: This should not be so long. However, due to potentially long rebalances that may have to wait a full // session timeout to complete, during which we cannot serve some requests. Ideally we could reduce this, but // we need to consider all possible scenarios this could fail. It might be ok to fail with a timeout in rare cases, // but currently a worker simply leaving the group can take this long as well. public static final long DEFAULT_REST_REQUEST_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(90); public static final long DEFAULT_HEALTH_CHECK_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(10); private static final Logger log = LoggerFactory.getLogger(RestServer.class); // Used to distinguish between Admin connectors and regular REST API connectors when binding admin handlers private static final String ADMIN_SERVER_CONNECTOR_NAME = "Admin"; private static final Pattern LISTENER_PATTERN = Pattern.compile("^(.*)://\\[?([0-9a-zA-Z\\-%._:]*)\\]?:(-?[0-9]+)"); private static final long GRACEFUL_SHUTDOWN_TIMEOUT_MS = 60 *
|
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.connect.runtime.rest; import org.apache.kafka.common.config.ConfigException; import org.apache.kafka.common.utils.Utils; import org.apache.kafka.connect.errors. ConnectException ; import org.apache.kafka.connect.health.ConnectClusterDetails; import org.apache.kafka.connect.rest.ConnectRestExtension; import org.apache.kafka.connect.rest.ConnectRestExtensionContext; import org.apache.kafka.connect.runtime.Herder; import org.apache.kafka.connect.runtime.health.ConnectClusterDetailsImpl; import org.apache.kafka.connect.runtime.health.ConnectClusterStateImpl; import org.apache.kafka.connect.runtime.rest.errors. ConnectException Mapper; import org.apache.kafka.connect.runtime.rest.util.SSLUtils; import com.fasterxml.jackson.jakarta.rs.json.JacksonJsonProvider; import org.eclipse.jetty.ee10.servlet.FilterHolder; import org.eclipse.jetty.ee10.servlet.ServletContextHandler; import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.eclipse.jetty.ee10.servlets.HeaderFilter; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.CustomRequestLog; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.Slf4jRequestLogWriter; import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.server.handler.CrossOriginHandler; import org.eclipse.jetty.server.handler.StatisticsHandler; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.glassfish.hk2.utilities.Binder; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.ServerProperties; import org.glassfish.jersey.servlet.ServletContainer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import jakarta.servlet.DispatcherType; import jakarta.ws.rs.core.UriBuilder; /** * Embedded server for the REST API that provides the control plane for Kafka Connect workers. */ public abstract class RestServer { // TODO: This should not be so long. However, due to potentially long rebalances that may have to wait a full // session timeout to complete, during which we cannot serve some requests. Ideally we could reduce this, but // we need to consider all possible scenarios this could fail. It might be ok to fail with a timeout in rare cases, // but currently a worker simply leaving the group can take this long as well. public static final long DEFAULT_REST_REQUEST_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(90); public static final long DEFAULT_HEALTH_CHECK_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(10); private static final Logger log = LoggerFactory.getLogger(RestServer.class); // Used to distinguish between Admin connectors and regular REST API connectors when binding admin handlers private static final String ADMIN_SERVER_CONNECTOR_NAME = "Admin"; private static final Pattern LISTENER_PATTERN = Pattern.compile("^(.*)://\\[?([0-9a-zA-Z\\-%._:]*)\\]?:(-?[0-9]+)"); private static final long GRACEFUL_SHUTDOWN_TIMEOUT_MS = 60 *
|
java
|
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.connect.runtime.rest; import org.apache.kafka.common.config.ConfigException; import org.apache.kafka.common.utils.Utils; import org.apache.kafka.connect.errors. <mask> <mask> <mask> <mask> ; import org.apache.kafka.connect.health.ConnectClusterDetails; import org.apache.kafka.connect.rest.ConnectRestExtension; import org.apache.kafka.connect.rest.ConnectRestExtensionContext; import org.apache.kafka.connect.runtime.Herder; import org.apache.kafka.connect.runtime.health.ConnectClusterDetailsImpl; import org.apache.kafka.connect.runtime.health.ConnectClusterStateImpl; import org.apache.kafka.connect.runtime.rest.errors. <mask> <mask> <mask> <mask> Mapper; import org.apache.kafka.connect.runtime.rest.util.SSLUtils; import com.fasterxml.jackson.jakarta.rs.json.JacksonJsonProvider; import org.eclipse.jetty.ee10.servlet.FilterHolder; import org.eclipse.jetty.ee10.servlet.ServletContextHandler; import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.eclipse.jetty.ee10.servlets.HeaderFilter; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.CustomRequestLog; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.Slf4jRequestLogWriter; import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.server.handler.CrossOriginHandler; import org.eclipse.jetty.server.handler.StatisticsHandler; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.glassfish.hk2.utilities.Binder; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.ServerProperties; import org.glassfish.jersey.servlet.ServletContainer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import jakarta.servlet.DispatcherType; import jakarta.ws.rs.core.UriBuilder; /** * Embedded server for the REST API that provides the control plane for Kafka Connect workers. */ public abstract class RestServer { // TODO: This should not be so long. However, due to potentially long rebalances that may have to wait a full // session timeout to complete, during which we cannot serve some requests. Ideally we could reduce this, but // we need to consider all possible scenarios this could fail. It might be ok to fail with a timeout in rare cases, // but currently a worker simply leaving the group can take this long as well. public static final long DEFAULT_REST_REQUEST_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(90); public static final long DEFAULT_HEALTH_CHECK_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(10); private static final Logger log = LoggerFactory.getLogger(RestServer.class); // Used to distinguish between Admin connectors and regular REST API connectors when binding admin handlers private static final String ADMIN_SERVER_CONNECTOR_NAME = "Admin"; private static final Pattern LISTENER_PATTERN = Pattern.compile("^(.*)://\\[?([0-9a-zA-Z\\-%._:]*)\\]?:(-?[0-9]+)"); private static final long GRACEFUL_SHUTDOWN_TIMEOUT_MS = 60 * 1000; private static final String PROTOCOL_HTTP = "http"; private static final String PROTOCOL_HTTPS = "https"; protected
|
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.connect.runtime.rest; import org.apache.kafka.common.config.ConfigException; import org.apache.kafka.common.utils.Utils; import org.apache.kafka.connect.errors. ConnectException ; import org.apache.kafka.connect.health.ConnectClusterDetails; import org.apache.kafka.connect.rest.ConnectRestExtension; import org.apache.kafka.connect.rest.ConnectRestExtensionContext; import org.apache.kafka.connect.runtime.Herder; import org.apache.kafka.connect.runtime.health.ConnectClusterDetailsImpl; import org.apache.kafka.connect.runtime.health.ConnectClusterStateImpl; import org.apache.kafka.connect.runtime.rest.errors. ConnectException Mapper; import org.apache.kafka.connect.runtime.rest.util.SSLUtils; import com.fasterxml.jackson.jakarta.rs.json.JacksonJsonProvider; import org.eclipse.jetty.ee10.servlet.FilterHolder; import org.eclipse.jetty.ee10.servlet.ServletContextHandler; import org.eclipse.jetty.ee10.servlet.ServletHolder; import org.eclipse.jetty.ee10.servlets.HeaderFilter; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.CustomRequestLog; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.Slf4jRequestLogWriter; import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.server.handler.CrossOriginHandler; import org.eclipse.jetty.server.handler.StatisticsHandler; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.glassfish.hk2.utilities.Binder; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.ServerProperties; import org.glassfish.jersey.servlet.ServletContainer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import jakarta.servlet.DispatcherType; import jakarta.ws.rs.core.UriBuilder; /** * Embedded server for the REST API that provides the control plane for Kafka Connect workers. */ public abstract class RestServer { // TODO: This should not be so long. However, due to potentially long rebalances that may have to wait a full // session timeout to complete, during which we cannot serve some requests. Ideally we could reduce this, but // we need to consider all possible scenarios this could fail. It might be ok to fail with a timeout in rare cases, // but currently a worker simply leaving the group can take this long as well. public static final long DEFAULT_REST_REQUEST_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(90); public static final long DEFAULT_HEALTH_CHECK_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(10); private static final Logger log = LoggerFactory.getLogger(RestServer.class); // Used to distinguish between Admin connectors and regular REST API connectors when binding admin handlers private static final String ADMIN_SERVER_CONNECTOR_NAME = "Admin"; private static final Pattern LISTENER_PATTERN = Pattern.compile("^(.*)://\\[?([0-9a-zA-Z\\-%._:]*)\\]?:(-?[0-9]+)"); private static final long GRACEFUL_SHUTDOWN_TIMEOUT_MS = 60 * 1000; private static final String PROTOCOL_HTTP = "http"; private static final String PROTOCOL_HTTPS = "https"; protected
|
java
|
ArrayList<>(); for (String listener : listeners) { Connector connector = createConnector(listener); connectors.add(connector); log.info("Added connector for {}", listener); } jettyServer.setConnectors(connectors.toArray(new Connector[0])); if (adminListeners != null && !adminListeners.isEmpty()) { for (String adminListener : adminListeners) { Connector conn = createConnector(adminListener, true); jettyServer.addConnector(conn); log.info("Added admin connector for {}", adminListener); } } } /** * Creates regular (non-admin) Jetty connector according to configuration */ public final Connector createConnector(String listener) { return createConnector(listener, false); } /** * Creates Jetty connector according to configuration */ public final Connector createConnector(String listener, boolean isAdmin) { Matcher listenerMatcher = LISTENER_PATTERN.matcher(listener); if (!listenerMatcher.matches()) throw new ConfigException("Listener doesn't have the right format (protocol://hostname:port)."); String protocol = listenerMatcher.group(1).toLowerCase(Locale.ENGLISH); if (!PROTOCOL_HTTP.equals(protocol) && !PROTOCOL_HTTPS.equals(protocol)) throw new ConfigException(String.format("Listener protocol must be either \"%s\" or \"%s\".", PROTOCOL_HTTP, PROTOCOL_HTTPS)); String hostname = listenerMatcher.group(2); int port = Integer.parseInt(listenerMatcher.group(3)); ServerConnector connector; if (PROTOCOL_HTTPS.equals(protocol)) { SslContextFactory.Server ssl; if (isAdmin) { ssl = SSLUtils.createServerSideSslContextFactory(config, RestServerConfig.ADMIN_LISTENERS_HTTPS_CONFIGS_PREFIX); } else { ssl = SSLUtils.createServerSideSslContextFactory(config); } connector = new ServerConnector(jettyServer, ssl); if (!isAdmin) { connector.setName(String.format("%s_%s%d", PROTOCOL_HTTPS, hostname, port)); } } else { connector = new ServerConnector(jettyServer); if (!isAdmin) { connector.setName(String.format("%s_%s%d", PROTOCOL_HTTP, hostname, port)); } } if (isAdmin) { connector.setName(ADMIN_SERVER_CONNECTOR_NAME); } if (!hostname.isEmpty()) connector.setHost(hostname); connector.setPort(port); // TODO: do we need this? connector.setIdleTimeout(requestTimeout.timeoutMs()); return connector; } public void initializeServer() { log.info("Initializing REST server"); Slf4jRequestLogWriter slf4jRequestLogWriter = new Slf4jRequestLogWriter(); slf4jRequestLogWriter.setLoggerName(RestServer.class.getCanonicalName()); CustomRequestLog requestLog = new CustomRequestLog(slf4jRequestLogWriter, CustomRequestLog.EXTENDED_NCSA_FORMAT + " %{ms}T"); jettyServer.setRequestLog(requestLog); /* Needed for graceful shutdown as per `setStopTimeout` documentation */ StatisticsHandler statsHandler = new StatisticsHandler(); statsHandler.setHandler(handlers); jettyServer.setHandler(statsHandler); jettyServer.setStopTimeout(GRACEFUL_SHUTDOWN_TIMEOUT_MS); jettyServer.setStopAtShutdown(true); try { jettyServer.start(); } catch (Exception e) { throw new <mask> <mask> <mask> <mask> ("Unable to initialize REST server", e); } log.info("REST server listening at " + jettyServer.getURI() + ", advertising URL " + advertisedUrl()); URI adminUrl = adminUrl(); if (adminUrl != null) log.info("REST admin endpoints at " + adminUrl); } protected final void initializeResources() { log.info("Initializing REST resources"); ResourceConfig resourceConfig = newResourceConfig(); Collection<Class<?>> regularResources = regularResources(); regularResources.forEach(resourceConfig::register); configureRegularResources(resourceConfig); List<String> adminListeners = config.adminListeners(); ResourceConfig adminResourceConfig; if (adminListeners != null && adminListeners.isEmpty()) { log.info("Skipping adding admin resources"); // set up adminResource but add no handlers to it adminResourceConfig = resourceConfig; } else { if (adminListeners == null) { log.info("Adding admin resources to main listener"); adminResourceConfig = resourceConfig; } else { // TODO: we need to check if these listeners are same as 'listeners' // TODO: the following code assumes that they are different log.info("Adding admin resources to admin listener"); adminResourceConfig = newResourceConfig(); } Collection<Class<?>> adminResources = adminResources(); adminResources.forEach(adminResourceConfig::register); configureAdminResources(adminResourceConfig); } ServletContainer servletContainer = new ServletContainer(resourceConfig); ServletHolder servletHolder = new ServletHolder(servletContainer); List<Handler> contextHandlers = new ArrayList<>(); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); context.addServlet(servletHolder, "/*"); contextHandlers.add(context); ServletContextHandler adminContext = null; if (adminResourceConfig != resourceConfig) { adminContext = new ServletContextHandler(ServletContextHandler.SESSIONS); ServletHolder adminServletHolder = new ServletHolder(new ServletContainer(adminResourceConfig)); adminContext.setContextPath("/"); adminContext.addServlet(adminServletHolder, "/*"); adminContext.setVirtualHosts(List.of("@" + ADMIN_SERVER_CONNECTOR_NAME)); contextHandlers.add(adminContext); } String allowedOrigins = config.allowedOrigins(); if (!Utils.isBlank(allowedOrigins)) { CrossOriginHandler crossOriginHandler = new CrossOriginHandler(); crossOriginHandler.setAllowedOriginPatterns(Set.of(allowedOrigins.split(","))); String allowedMethods = config.allowedMethods(); if (!Utils.isBlank(allowedMethods)) { crossOriginHandler.setAllowedMethods(Set.of(allowedMethods.split(","))); } // Setting to true matches the previously used CrossOriginFilter crossOriginHandler.setDeliverPreflightRequests(true); context.insertHandler(crossOriginHandler); } String headerConfig = config.responseHeaders(); if (!Utils.isBlank(headerConfig)) { configureHttpResponseHeaderFilter(context, headerConfig); } handlers.setHandlers(contextHandlers.toArray(new Handler[0])); try { context.start(); } catch (Exception e) {
|
ArrayList<>(); for (String listener : listeners) { Connector connector = createConnector(listener); connectors.add(connector); log.info("Added connector for {}", listener); } jettyServer.setConnectors(connectors.toArray(new Connector[0])); if (adminListeners != null && !adminListeners.isEmpty()) { for (String adminListener : adminListeners) { Connector conn = createConnector(adminListener, true); jettyServer.addConnector(conn); log.info("Added admin connector for {}", adminListener); } } } /** * Creates regular (non-admin) Jetty connector according to configuration */ public final Connector createConnector(String listener) { return createConnector(listener, false); } /** * Creates Jetty connector according to configuration */ public final Connector createConnector(String listener, boolean isAdmin) { Matcher listenerMatcher = LISTENER_PATTERN.matcher(listener); if (!listenerMatcher.matches()) throw new ConfigException("Listener doesn't have the right format (protocol://hostname:port)."); String protocol = listenerMatcher.group(1).toLowerCase(Locale.ENGLISH); if (!PROTOCOL_HTTP.equals(protocol) && !PROTOCOL_HTTPS.equals(protocol)) throw new ConfigException(String.format("Listener protocol must be either \"%s\" or \"%s\".", PROTOCOL_HTTP, PROTOCOL_HTTPS)); String hostname = listenerMatcher.group(2); int port = Integer.parseInt(listenerMatcher.group(3)); ServerConnector connector; if (PROTOCOL_HTTPS.equals(protocol)) { SslContextFactory.Server ssl; if (isAdmin) { ssl = SSLUtils.createServerSideSslContextFactory(config, RestServerConfig.ADMIN_LISTENERS_HTTPS_CONFIGS_PREFIX); } else { ssl = SSLUtils.createServerSideSslContextFactory(config); } connector = new ServerConnector(jettyServer, ssl); if (!isAdmin) { connector.setName(String.format("%s_%s%d", PROTOCOL_HTTPS, hostname, port)); } } else { connector = new ServerConnector(jettyServer); if (!isAdmin) { connector.setName(String.format("%s_%s%d", PROTOCOL_HTTP, hostname, port)); } } if (isAdmin) { connector.setName(ADMIN_SERVER_CONNECTOR_NAME); } if (!hostname.isEmpty()) connector.setHost(hostname); connector.setPort(port); // TODO: do we need this? connector.setIdleTimeout(requestTimeout.timeoutMs()); return connector; } public void initializeServer() { log.info("Initializing REST server"); Slf4jRequestLogWriter slf4jRequestLogWriter = new Slf4jRequestLogWriter(); slf4jRequestLogWriter.setLoggerName(RestServer.class.getCanonicalName()); CustomRequestLog requestLog = new CustomRequestLog(slf4jRequestLogWriter, CustomRequestLog.EXTENDED_NCSA_FORMAT + " %{ms}T"); jettyServer.setRequestLog(requestLog); /* Needed for graceful shutdown as per `setStopTimeout` documentation */ StatisticsHandler statsHandler = new StatisticsHandler(); statsHandler.setHandler(handlers); jettyServer.setHandler(statsHandler); jettyServer.setStopTimeout(GRACEFUL_SHUTDOWN_TIMEOUT_MS); jettyServer.setStopAtShutdown(true); try { jettyServer.start(); } catch (Exception e) { throw new ConnectException ("Unable to initialize REST server", e); } log.info("REST server listening at " + jettyServer.getURI() + ", advertising URL " + advertisedUrl()); URI adminUrl = adminUrl(); if (adminUrl != null) log.info("REST admin endpoints at " + adminUrl); } protected final void initializeResources() { log.info("Initializing REST resources"); ResourceConfig resourceConfig = newResourceConfig(); Collection<Class<?>> regularResources = regularResources(); regularResources.forEach(resourceConfig::register); configureRegularResources(resourceConfig); List<String> adminListeners = config.adminListeners(); ResourceConfig adminResourceConfig; if (adminListeners != null && adminListeners.isEmpty()) { log.info("Skipping adding admin resources"); // set up adminResource but add no handlers to it adminResourceConfig = resourceConfig; } else { if (adminListeners == null) { log.info("Adding admin resources to main listener"); adminResourceConfig = resourceConfig; } else { // TODO: we need to check if these listeners are same as 'listeners' // TODO: the following code assumes that they are different log.info("Adding admin resources to admin listener"); adminResourceConfig = newResourceConfig(); } Collection<Class<?>> adminResources = adminResources(); adminResources.forEach(adminResourceConfig::register); configureAdminResources(adminResourceConfig); } ServletContainer servletContainer = new ServletContainer(resourceConfig); ServletHolder servletHolder = new ServletHolder(servletContainer); List<Handler> contextHandlers = new ArrayList<>(); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); context.addServlet(servletHolder, "/*"); contextHandlers.add(context); ServletContextHandler adminContext = null; if (adminResourceConfig != resourceConfig) { adminContext = new ServletContextHandler(ServletContextHandler.SESSIONS); ServletHolder adminServletHolder = new ServletHolder(new ServletContainer(adminResourceConfig)); adminContext.setContextPath("/"); adminContext.addServlet(adminServletHolder, "/*"); adminContext.setVirtualHosts(List.of("@" + ADMIN_SERVER_CONNECTOR_NAME)); contextHandlers.add(adminContext); } String allowedOrigins = config.allowedOrigins(); if (!Utils.isBlank(allowedOrigins)) { CrossOriginHandler crossOriginHandler = new CrossOriginHandler(); crossOriginHandler.setAllowedOriginPatterns(Set.of(allowedOrigins.split(","))); String allowedMethods = config.allowedMethods(); if (!Utils.isBlank(allowedMethods)) { crossOriginHandler.setAllowedMethods(Set.of(allowedMethods.split(","))); } // Setting to true matches the previously used CrossOriginFilter crossOriginHandler.setDeliverPreflightRequests(true); context.insertHandler(crossOriginHandler); } String headerConfig = config.responseHeaders(); if (!Utils.isBlank(headerConfig)) { configureHttpResponseHeaderFilter(context, headerConfig); } handlers.setHandlers(contextHandlers.toArray(new Handler[0])); try { context.start(); } catch (Exception e) {
|
java
|
initialize REST server", e); } log.info("REST server listening at " + jettyServer.getURI() + ", advertising URL " + advertisedUrl()); URI adminUrl = adminUrl(); if (adminUrl != null) log.info("REST admin endpoints at " + adminUrl); } protected final void initializeResources() { log.info("Initializing REST resources"); ResourceConfig resourceConfig = newResourceConfig(); Collection<Class<?>> regularResources = regularResources(); regularResources.forEach(resourceConfig::register); configureRegularResources(resourceConfig); List<String> adminListeners = config.adminListeners(); ResourceConfig adminResourceConfig; if (adminListeners != null && adminListeners.isEmpty()) { log.info("Skipping adding admin resources"); // set up adminResource but add no handlers to it adminResourceConfig = resourceConfig; } else { if (adminListeners == null) { log.info("Adding admin resources to main listener"); adminResourceConfig = resourceConfig; } else { // TODO: we need to check if these listeners are same as 'listeners' // TODO: the following code assumes that they are different log.info("Adding admin resources to admin listener"); adminResourceConfig = newResourceConfig(); } Collection<Class<?>> adminResources = adminResources(); adminResources.forEach(adminResourceConfig::register); configureAdminResources(adminResourceConfig); } ServletContainer servletContainer = new ServletContainer(resourceConfig); ServletHolder servletHolder = new ServletHolder(servletContainer); List<Handler> contextHandlers = new ArrayList<>(); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); context.addServlet(servletHolder, "/*"); contextHandlers.add(context); ServletContextHandler adminContext = null; if (adminResourceConfig != resourceConfig) { adminContext = new ServletContextHandler(ServletContextHandler.SESSIONS); ServletHolder adminServletHolder = new ServletHolder(new ServletContainer(adminResourceConfig)); adminContext.setContextPath("/"); adminContext.addServlet(adminServletHolder, "/*"); adminContext.setVirtualHosts(List.of("@" + ADMIN_SERVER_CONNECTOR_NAME)); contextHandlers.add(adminContext); } String allowedOrigins = config.allowedOrigins(); if (!Utils.isBlank(allowedOrigins)) { CrossOriginHandler crossOriginHandler = new CrossOriginHandler(); crossOriginHandler.setAllowedOriginPatterns(Set.of(allowedOrigins.split(","))); String allowedMethods = config.allowedMethods(); if (!Utils.isBlank(allowedMethods)) { crossOriginHandler.setAllowedMethods(Set.of(allowedMethods.split(","))); } // Setting to true matches the previously used CrossOriginFilter crossOriginHandler.setDeliverPreflightRequests(true); context.insertHandler(crossOriginHandler); } String headerConfig = config.responseHeaders(); if (!Utils.isBlank(headerConfig)) { configureHttpResponseHeaderFilter(context, headerConfig); } handlers.setHandlers(contextHandlers.toArray(new Handler[0])); try { context.start(); } catch (Exception e) { throw new <mask> <mask> <mask> <mask> ("Unable to initialize REST resources", e); } if (adminResourceConfig != resourceConfig) { try { log.debug("Starting admin context"); adminContext.start(); } catch (Exception e) { throw new <mask> <mask> <mask> <mask> ("Unable to initialize Admin REST resources", e); } } log.info("REST resources initialized; server is started and ready to handle requests"); } private ResourceConfig newResourceConfig() { ResourceConfig result = new ResourceConfig(); result.register(new JacksonJsonProvider()); result.register(requestTimeout.binder()); result.register( <mask> <mask> <mask> <mask> Mapper.class); result.property(ServerProperties.WADL_FEATURE_DISABLE, true); return result; } /** * @return the resources that should be registered with the * standard (i.e., non-admin) listener for this server; may be empty, but not null */ protected abstract Collection<Class<?>> regularResources(); /** * @return the resources that should be registered with the * admin listener for this server; may be empty, but not null */ protected abstract Collection<Class<?>> adminResources(); /** * Pluggable hook to customize the regular (i.e., non-admin) resources on this server * after they have been instantiated and registered with the given {@link ResourceConfig}. * This may be used to, for example, add REST extensions via {@link #registerRestExtensions(Herder, ResourceConfig)}. * <p> * <em>N.B.: Classes do <b>not</b> need to register the resources provided in {@link #regularResources()} with * the {@link ResourceConfig} parameter in this method; they are automatically registered by the parent class.</em> * @param resourceConfig the {@link ResourceConfig} that the server's regular listeners are registered with; never null */ protected void configureRegularResources(ResourceConfig resourceConfig) { // No-op by default } /** * Pluggable hook to customize the admin resources on this server after they have been instantiated and registered * with the given
|
initialize REST server", e); } log.info("REST server listening at " + jettyServer.getURI() + ", advertising URL " + advertisedUrl()); URI adminUrl = adminUrl(); if (adminUrl != null) log.info("REST admin endpoints at " + adminUrl); } protected final void initializeResources() { log.info("Initializing REST resources"); ResourceConfig resourceConfig = newResourceConfig(); Collection<Class<?>> regularResources = regularResources(); regularResources.forEach(resourceConfig::register); configureRegularResources(resourceConfig); List<String> adminListeners = config.adminListeners(); ResourceConfig adminResourceConfig; if (adminListeners != null && adminListeners.isEmpty()) { log.info("Skipping adding admin resources"); // set up adminResource but add no handlers to it adminResourceConfig = resourceConfig; } else { if (adminListeners == null) { log.info("Adding admin resources to main listener"); adminResourceConfig = resourceConfig; } else { // TODO: we need to check if these listeners are same as 'listeners' // TODO: the following code assumes that they are different log.info("Adding admin resources to admin listener"); adminResourceConfig = newResourceConfig(); } Collection<Class<?>> adminResources = adminResources(); adminResources.forEach(adminResourceConfig::register); configureAdminResources(adminResourceConfig); } ServletContainer servletContainer = new ServletContainer(resourceConfig); ServletHolder servletHolder = new ServletHolder(servletContainer); List<Handler> contextHandlers = new ArrayList<>(); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); context.addServlet(servletHolder, "/*"); contextHandlers.add(context); ServletContextHandler adminContext = null; if (adminResourceConfig != resourceConfig) { adminContext = new ServletContextHandler(ServletContextHandler.SESSIONS); ServletHolder adminServletHolder = new ServletHolder(new ServletContainer(adminResourceConfig)); adminContext.setContextPath("/"); adminContext.addServlet(adminServletHolder, "/*"); adminContext.setVirtualHosts(List.of("@" + ADMIN_SERVER_CONNECTOR_NAME)); contextHandlers.add(adminContext); } String allowedOrigins = config.allowedOrigins(); if (!Utils.isBlank(allowedOrigins)) { CrossOriginHandler crossOriginHandler = new CrossOriginHandler(); crossOriginHandler.setAllowedOriginPatterns(Set.of(allowedOrigins.split(","))); String allowedMethods = config.allowedMethods(); if (!Utils.isBlank(allowedMethods)) { crossOriginHandler.setAllowedMethods(Set.of(allowedMethods.split(","))); } // Setting to true matches the previously used CrossOriginFilter crossOriginHandler.setDeliverPreflightRequests(true); context.insertHandler(crossOriginHandler); } String headerConfig = config.responseHeaders(); if (!Utils.isBlank(headerConfig)) { configureHttpResponseHeaderFilter(context, headerConfig); } handlers.setHandlers(contextHandlers.toArray(new Handler[0])); try { context.start(); } catch (Exception e) { throw new ConnectException ("Unable to initialize REST resources", e); } if (adminResourceConfig != resourceConfig) { try { log.debug("Starting admin context"); adminContext.start(); } catch (Exception e) { throw new ConnectException ("Unable to initialize Admin REST resources", e); } } log.info("REST resources initialized; server is started and ready to handle requests"); } private ResourceConfig newResourceConfig() { ResourceConfig result = new ResourceConfig(); result.register(new JacksonJsonProvider()); result.register(requestTimeout.binder()); result.register( ConnectException Mapper.class); result.property(ServerProperties.WADL_FEATURE_DISABLE, true); return result; } /** * @return the resources that should be registered with the * standard (i.e., non-admin) listener for this server; may be empty, but not null */ protected abstract Collection<Class<?>> regularResources(); /** * @return the resources that should be registered with the * admin listener for this server; may be empty, but not null */ protected abstract Collection<Class<?>> adminResources(); /** * Pluggable hook to customize the regular (i.e., non-admin) resources on this server * after they have been instantiated and registered with the given {@link ResourceConfig}. * This may be used to, for example, add REST extensions via {@link #registerRestExtensions(Herder, ResourceConfig)}. * <p> * <em>N.B.: Classes do <b>not</b> need to register the resources provided in {@link #regularResources()} with * the {@link ResourceConfig} parameter in this method; they are automatically registered by the parent class.</em> * @param resourceConfig the {@link ResourceConfig} that the server's regular listeners are registered with; never null */ protected void configureRegularResources(ResourceConfig resourceConfig) { // No-op by default } /** * Pluggable hook to customize the admin resources on this server after they have been instantiated and registered * with the given
|
java
|
null) log.info("REST admin endpoints at " + adminUrl); } protected final void initializeResources() { log.info("Initializing REST resources"); ResourceConfig resourceConfig = newResourceConfig(); Collection<Class<?>> regularResources = regularResources(); regularResources.forEach(resourceConfig::register); configureRegularResources(resourceConfig); List<String> adminListeners = config.adminListeners(); ResourceConfig adminResourceConfig; if (adminListeners != null && adminListeners.isEmpty()) { log.info("Skipping adding admin resources"); // set up adminResource but add no handlers to it adminResourceConfig = resourceConfig; } else { if (adminListeners == null) { log.info("Adding admin resources to main listener"); adminResourceConfig = resourceConfig; } else { // TODO: we need to check if these listeners are same as 'listeners' // TODO: the following code assumes that they are different log.info("Adding admin resources to admin listener"); adminResourceConfig = newResourceConfig(); } Collection<Class<?>> adminResources = adminResources(); adminResources.forEach(adminResourceConfig::register); configureAdminResources(adminResourceConfig); } ServletContainer servletContainer = new ServletContainer(resourceConfig); ServletHolder servletHolder = new ServletHolder(servletContainer); List<Handler> contextHandlers = new ArrayList<>(); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); context.addServlet(servletHolder, "/*"); contextHandlers.add(context); ServletContextHandler adminContext = null; if (adminResourceConfig != resourceConfig) { adminContext = new ServletContextHandler(ServletContextHandler.SESSIONS); ServletHolder adminServletHolder = new ServletHolder(new ServletContainer(adminResourceConfig)); adminContext.setContextPath("/"); adminContext.addServlet(adminServletHolder, "/*"); adminContext.setVirtualHosts(List.of("@" + ADMIN_SERVER_CONNECTOR_NAME)); contextHandlers.add(adminContext); } String allowedOrigins = config.allowedOrigins(); if (!Utils.isBlank(allowedOrigins)) { CrossOriginHandler crossOriginHandler = new CrossOriginHandler(); crossOriginHandler.setAllowedOriginPatterns(Set.of(allowedOrigins.split(","))); String allowedMethods = config.allowedMethods(); if (!Utils.isBlank(allowedMethods)) { crossOriginHandler.setAllowedMethods(Set.of(allowedMethods.split(","))); } // Setting to true matches the previously used CrossOriginFilter crossOriginHandler.setDeliverPreflightRequests(true); context.insertHandler(crossOriginHandler); } String headerConfig = config.responseHeaders(); if (!Utils.isBlank(headerConfig)) { configureHttpResponseHeaderFilter(context, headerConfig); } handlers.setHandlers(contextHandlers.toArray(new Handler[0])); try { context.start(); } catch (Exception e) { throw new <mask> <mask> <mask> <mask> ("Unable to initialize REST resources", e); } if (adminResourceConfig != resourceConfig) { try { log.debug("Starting admin context"); adminContext.start(); } catch (Exception e) { throw new <mask> <mask> <mask> <mask> ("Unable to initialize Admin REST resources", e); } } log.info("REST resources initialized; server is started and ready to handle requests"); } private ResourceConfig newResourceConfig() { ResourceConfig result = new ResourceConfig(); result.register(new JacksonJsonProvider()); result.register(requestTimeout.binder()); result.register( <mask> <mask> <mask> <mask> Mapper.class); result.property(ServerProperties.WADL_FEATURE_DISABLE, true); return result; } /** * @return the resources that should be registered with the * standard (i.e., non-admin) listener for this server; may be empty, but not null */ protected abstract Collection<Class<?>> regularResources(); /** * @return the resources that should be registered with the * admin listener for this server; may be empty, but not null */ protected abstract Collection<Class<?>> adminResources(); /** * Pluggable hook to customize the regular (i.e., non-admin) resources on this server * after they have been instantiated and registered with the given {@link ResourceConfig}. * This may be used to, for example, add REST extensions via {@link #registerRestExtensions(Herder, ResourceConfig)}. * <p> * <em>N.B.: Classes do <b>not</b> need to register the resources provided in {@link #regularResources()} with * the {@link ResourceConfig} parameter in this method; they are automatically registered by the parent class.</em> * @param resourceConfig the {@link ResourceConfig} that the server's regular listeners are registered with; never null */ protected void configureRegularResources(ResourceConfig resourceConfig) { // No-op by default } /** * Pluggable hook to customize the admin resources on this server after they have been instantiated and registered * with the given {@link ResourceConfig}. This may be used to, for example, add REST extensions via * {@link #registerRestExtensions(Herder, ResourceConfig)}. * <p> * <em>N.B.: Classes do <b>not</b> need to
|
null) log.info("REST admin endpoints at " + adminUrl); } protected final void initializeResources() { log.info("Initializing REST resources"); ResourceConfig resourceConfig = newResourceConfig(); Collection<Class<?>> regularResources = regularResources(); regularResources.forEach(resourceConfig::register); configureRegularResources(resourceConfig); List<String> adminListeners = config.adminListeners(); ResourceConfig adminResourceConfig; if (adminListeners != null && adminListeners.isEmpty()) { log.info("Skipping adding admin resources"); // set up adminResource but add no handlers to it adminResourceConfig = resourceConfig; } else { if (adminListeners == null) { log.info("Adding admin resources to main listener"); adminResourceConfig = resourceConfig; } else { // TODO: we need to check if these listeners are same as 'listeners' // TODO: the following code assumes that they are different log.info("Adding admin resources to admin listener"); adminResourceConfig = newResourceConfig(); } Collection<Class<?>> adminResources = adminResources(); adminResources.forEach(adminResourceConfig::register); configureAdminResources(adminResourceConfig); } ServletContainer servletContainer = new ServletContainer(resourceConfig); ServletHolder servletHolder = new ServletHolder(servletContainer); List<Handler> contextHandlers = new ArrayList<>(); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); context.addServlet(servletHolder, "/*"); contextHandlers.add(context); ServletContextHandler adminContext = null; if (adminResourceConfig != resourceConfig) { adminContext = new ServletContextHandler(ServletContextHandler.SESSIONS); ServletHolder adminServletHolder = new ServletHolder(new ServletContainer(adminResourceConfig)); adminContext.setContextPath("/"); adminContext.addServlet(adminServletHolder, "/*"); adminContext.setVirtualHosts(List.of("@" + ADMIN_SERVER_CONNECTOR_NAME)); contextHandlers.add(adminContext); } String allowedOrigins = config.allowedOrigins(); if (!Utils.isBlank(allowedOrigins)) { CrossOriginHandler crossOriginHandler = new CrossOriginHandler(); crossOriginHandler.setAllowedOriginPatterns(Set.of(allowedOrigins.split(","))); String allowedMethods = config.allowedMethods(); if (!Utils.isBlank(allowedMethods)) { crossOriginHandler.setAllowedMethods(Set.of(allowedMethods.split(","))); } // Setting to true matches the previously used CrossOriginFilter crossOriginHandler.setDeliverPreflightRequests(true); context.insertHandler(crossOriginHandler); } String headerConfig = config.responseHeaders(); if (!Utils.isBlank(headerConfig)) { configureHttpResponseHeaderFilter(context, headerConfig); } handlers.setHandlers(contextHandlers.toArray(new Handler[0])); try { context.start(); } catch (Exception e) { throw new ConnectException ("Unable to initialize REST resources", e); } if (adminResourceConfig != resourceConfig) { try { log.debug("Starting admin context"); adminContext.start(); } catch (Exception e) { throw new ConnectException ("Unable to initialize Admin REST resources", e); } } log.info("REST resources initialized; server is started and ready to handle requests"); } private ResourceConfig newResourceConfig() { ResourceConfig result = new ResourceConfig(); result.register(new JacksonJsonProvider()); result.register(requestTimeout.binder()); result.register( ConnectException Mapper.class); result.property(ServerProperties.WADL_FEATURE_DISABLE, true); return result; } /** * @return the resources that should be registered with the * standard (i.e., non-admin) listener for this server; may be empty, but not null */ protected abstract Collection<Class<?>> regularResources(); /** * @return the resources that should be registered with the * admin listener for this server; may be empty, but not null */ protected abstract Collection<Class<?>> adminResources(); /** * Pluggable hook to customize the regular (i.e., non-admin) resources on this server * after they have been instantiated and registered with the given {@link ResourceConfig}. * This may be used to, for example, add REST extensions via {@link #registerRestExtensions(Herder, ResourceConfig)}. * <p> * <em>N.B.: Classes do <b>not</b> need to register the resources provided in {@link #regularResources()} with * the {@link ResourceConfig} parameter in this method; they are automatically registered by the parent class.</em> * @param resourceConfig the {@link ResourceConfig} that the server's regular listeners are registered with; never null */ protected void configureRegularResources(ResourceConfig resourceConfig) { // No-op by default } /** * Pluggable hook to customize the admin resources on this server after they have been instantiated and registered * with the given {@link ResourceConfig}. This may be used to, for example, add REST extensions via * {@link #registerRestExtensions(Herder, ResourceConfig)}. * <p> * <em>N.B.: Classes do <b>not</b> need to
|
java
|
!= null && adminListeners.isEmpty()) { log.info("Skipping adding admin resources"); // set up adminResource but add no handlers to it adminResourceConfig = resourceConfig; } else { if (adminListeners == null) { log.info("Adding admin resources to main listener"); adminResourceConfig = resourceConfig; } else { // TODO: we need to check if these listeners are same as 'listeners' // TODO: the following code assumes that they are different log.info("Adding admin resources to admin listener"); adminResourceConfig = newResourceConfig(); } Collection<Class<?>> adminResources = adminResources(); adminResources.forEach(adminResourceConfig::register); configureAdminResources(adminResourceConfig); } ServletContainer servletContainer = new ServletContainer(resourceConfig); ServletHolder servletHolder = new ServletHolder(servletContainer); List<Handler> contextHandlers = new ArrayList<>(); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); context.addServlet(servletHolder, "/*"); contextHandlers.add(context); ServletContextHandler adminContext = null; if (adminResourceConfig != resourceConfig) { adminContext = new ServletContextHandler(ServletContextHandler.SESSIONS); ServletHolder adminServletHolder = new ServletHolder(new ServletContainer(adminResourceConfig)); adminContext.setContextPath("/"); adminContext.addServlet(adminServletHolder, "/*"); adminContext.setVirtualHosts(List.of("@" + ADMIN_SERVER_CONNECTOR_NAME)); contextHandlers.add(adminContext); } String allowedOrigins = config.allowedOrigins(); if (!Utils.isBlank(allowedOrigins)) { CrossOriginHandler crossOriginHandler = new CrossOriginHandler(); crossOriginHandler.setAllowedOriginPatterns(Set.of(allowedOrigins.split(","))); String allowedMethods = config.allowedMethods(); if (!Utils.isBlank(allowedMethods)) { crossOriginHandler.setAllowedMethods(Set.of(allowedMethods.split(","))); } // Setting to true matches the previously used CrossOriginFilter crossOriginHandler.setDeliverPreflightRequests(true); context.insertHandler(crossOriginHandler); } String headerConfig = config.responseHeaders(); if (!Utils.isBlank(headerConfig)) { configureHttpResponseHeaderFilter(context, headerConfig); } handlers.setHandlers(contextHandlers.toArray(new Handler[0])); try { context.start(); } catch (Exception e) { throw new <mask> <mask> <mask> <mask> ("Unable to initialize REST resources", e); } if (adminResourceConfig != resourceConfig) { try { log.debug("Starting admin context"); adminContext.start(); } catch (Exception e) { throw new <mask> <mask> <mask> <mask> ("Unable to initialize Admin REST resources", e); } } log.info("REST resources initialized; server is started and ready to handle requests"); } private ResourceConfig newResourceConfig() { ResourceConfig result = new ResourceConfig(); result.register(new JacksonJsonProvider()); result.register(requestTimeout.binder()); result.register( <mask> <mask> <mask> <mask> Mapper.class); result.property(ServerProperties.WADL_FEATURE_DISABLE, true); return result; } /** * @return the resources that should be registered with the * standard (i.e., non-admin) listener for this server; may be empty, but not null */ protected abstract Collection<Class<?>> regularResources(); /** * @return the resources that should be registered with the * admin listener for this server; may be empty, but not null */ protected abstract Collection<Class<?>> adminResources(); /** * Pluggable hook to customize the regular (i.e., non-admin) resources on this server * after they have been instantiated and registered with the given {@link ResourceConfig}. * This may be used to, for example, add REST extensions via {@link #registerRestExtensions(Herder, ResourceConfig)}. * <p> * <em>N.B.: Classes do <b>not</b> need to register the resources provided in {@link #regularResources()} with * the {@link ResourceConfig} parameter in this method; they are automatically registered by the parent class.</em> * @param resourceConfig the {@link ResourceConfig} that the server's regular listeners are registered with; never null */ protected void configureRegularResources(ResourceConfig resourceConfig) { // No-op by default } /** * Pluggable hook to customize the admin resources on this server after they have been instantiated and registered * with the given {@link ResourceConfig}. This may be used to, for example, add REST extensions via * {@link #registerRestExtensions(Herder, ResourceConfig)}. * <p> * <em>N.B.: Classes do <b>not</b> need to register the resources provided in {@link #adminResources()} with * the {@link ResourceConfig} parameter in this method; they are automatically registered by the parent class.</em> * @param adminResourceConfig the {@link ResourceConfig} that the server's admin listeners
|
!= null && adminListeners.isEmpty()) { log.info("Skipping adding admin resources"); // set up adminResource but add no handlers to it adminResourceConfig = resourceConfig; } else { if (adminListeners == null) { log.info("Adding admin resources to main listener"); adminResourceConfig = resourceConfig; } else { // TODO: we need to check if these listeners are same as 'listeners' // TODO: the following code assumes that they are different log.info("Adding admin resources to admin listener"); adminResourceConfig = newResourceConfig(); } Collection<Class<?>> adminResources = adminResources(); adminResources.forEach(adminResourceConfig::register); configureAdminResources(adminResourceConfig); } ServletContainer servletContainer = new ServletContainer(resourceConfig); ServletHolder servletHolder = new ServletHolder(servletContainer); List<Handler> contextHandlers = new ArrayList<>(); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); context.addServlet(servletHolder, "/*"); contextHandlers.add(context); ServletContextHandler adminContext = null; if (adminResourceConfig != resourceConfig) { adminContext = new ServletContextHandler(ServletContextHandler.SESSIONS); ServletHolder adminServletHolder = new ServletHolder(new ServletContainer(adminResourceConfig)); adminContext.setContextPath("/"); adminContext.addServlet(adminServletHolder, "/*"); adminContext.setVirtualHosts(List.of("@" + ADMIN_SERVER_CONNECTOR_NAME)); contextHandlers.add(adminContext); } String allowedOrigins = config.allowedOrigins(); if (!Utils.isBlank(allowedOrigins)) { CrossOriginHandler crossOriginHandler = new CrossOriginHandler(); crossOriginHandler.setAllowedOriginPatterns(Set.of(allowedOrigins.split(","))); String allowedMethods = config.allowedMethods(); if (!Utils.isBlank(allowedMethods)) { crossOriginHandler.setAllowedMethods(Set.of(allowedMethods.split(","))); } // Setting to true matches the previously used CrossOriginFilter crossOriginHandler.setDeliverPreflightRequests(true); context.insertHandler(crossOriginHandler); } String headerConfig = config.responseHeaders(); if (!Utils.isBlank(headerConfig)) { configureHttpResponseHeaderFilter(context, headerConfig); } handlers.setHandlers(contextHandlers.toArray(new Handler[0])); try { context.start(); } catch (Exception e) { throw new ConnectException ("Unable to initialize REST resources", e); } if (adminResourceConfig != resourceConfig) { try { log.debug("Starting admin context"); adminContext.start(); } catch (Exception e) { throw new ConnectException ("Unable to initialize Admin REST resources", e); } } log.info("REST resources initialized; server is started and ready to handle requests"); } private ResourceConfig newResourceConfig() { ResourceConfig result = new ResourceConfig(); result.register(new JacksonJsonProvider()); result.register(requestTimeout.binder()); result.register( ConnectException Mapper.class); result.property(ServerProperties.WADL_FEATURE_DISABLE, true); return result; } /** * @return the resources that should be registered with the * standard (i.e., non-admin) listener for this server; may be empty, but not null */ protected abstract Collection<Class<?>> regularResources(); /** * @return the resources that should be registered with the * admin listener for this server; may be empty, but not null */ protected abstract Collection<Class<?>> adminResources(); /** * Pluggable hook to customize the regular (i.e., non-admin) resources on this server * after they have been instantiated and registered with the given {@link ResourceConfig}. * This may be used to, for example, add REST extensions via {@link #registerRestExtensions(Herder, ResourceConfig)}. * <p> * <em>N.B.: Classes do <b>not</b> need to register the resources provided in {@link #regularResources()} with * the {@link ResourceConfig} parameter in this method; they are automatically registered by the parent class.</em> * @param resourceConfig the {@link ResourceConfig} that the server's regular listeners are registered with; never null */ protected void configureRegularResources(ResourceConfig resourceConfig) { // No-op by default } /** * Pluggable hook to customize the admin resources on this server after they have been instantiated and registered * with the given {@link ResourceConfig}. This may be used to, for example, add REST extensions via * {@link #registerRestExtensions(Herder, ResourceConfig)}. * <p> * <em>N.B.: Classes do <b>not</b> need to register the resources provided in {@link #adminResources()} with * the {@link ResourceConfig} parameter in this method; they are automatically registered by the parent class.</em> * @param adminResourceConfig the {@link ResourceConfig} that the server's admin listeners
|
java
|
registered with the given {@link ResourceConfig}. * This may be used to, for example, add REST extensions via {@link #registerRestExtensions(Herder, ResourceConfig)}. * <p> * <em>N.B.: Classes do <b>not</b> need to register the resources provided in {@link #regularResources()} with * the {@link ResourceConfig} parameter in this method; they are automatically registered by the parent class.</em> * @param resourceConfig the {@link ResourceConfig} that the server's regular listeners are registered with; never null */ protected void configureRegularResources(ResourceConfig resourceConfig) { // No-op by default } /** * Pluggable hook to customize the admin resources on this server after they have been instantiated and registered * with the given {@link ResourceConfig}. This may be used to, for example, add REST extensions via * {@link #registerRestExtensions(Herder, ResourceConfig)}. * <p> * <em>N.B.: Classes do <b>not</b> need to register the resources provided in {@link #adminResources()} with * the {@link ResourceConfig} parameter in this method; they are automatically registered by the parent class.</em> * @param adminResourceConfig the {@link ResourceConfig} that the server's admin listeners are registered with; never null */ protected void configureAdminResources(ResourceConfig adminResourceConfig) { // No-op by default } public URI serverUrl() { return jettyServer.getURI(); } public void stop() { log.info("Stopping REST server"); try { if (handlers.isRunning()) { for (Handler handler : handlers.getHandlers()) { if (handler != null) { Utils.closeQuietly(handler::stop, handler.toString()); } } } for (ConnectRestExtension connectRestExtension : connectRestExtensions) { try { connectRestExtension.close(); } catch (IOException e) { log.warn("Error while invoking close on " + connectRestExtension.getClass(), e); } } jettyServer.stop(); jettyServer.join(); } catch (Exception e) { throw new <mask> <mask> <mask> <mask> ("Unable to stop REST server", e); } finally { try { jettyServer.destroy(); } catch (Exception e) { log.error("Unable to destroy REST server", e); } } log.info("REST server stopped"); } /** * Get the URL to advertise to other workers and clients. This uses the default connector from the embedded Jetty * server, unless overrides for advertised hostname and/or port are provided via configs. {@link #initializeServer()} * must be invoked successfully before calling this method. */ public URI advertisedUrl() { UriBuilder builder = UriBuilder.fromUri(jettyServer.getURI()); String advertisedSecurityProtocol = determineAdvertisedProtocol(); ServerConnector serverConnector = findConnector(advertisedSecurityProtocol); builder.scheme(advertisedSecurityProtocol); String advertisedHostname = config.advertisedHostName(); if (advertisedHostname != null && !advertisedHostname.isEmpty()) builder.host(advertisedHostname); else if (serverConnector != null && serverConnector.getHost() != null && !serverConnector.getHost().isEmpty()) builder.host(serverConnector.getHost()); Integer advertisedPort = config.advertisedPort(); if (advertisedPort != null) builder.port(advertisedPort); else if (serverConnector != null && serverConnector.getPort() > 0) builder.port(serverConnector.getPort()); else if (serverConnector != null && serverConnector.getLocalPort() > 0) builder.port(serverConnector.getLocalPort()); log.info("Advertised URI: {}", builder.build()); return builder.build(); } /** * @return the admin url for this worker. Can be null if admin endpoints are disabled. */ public URI adminUrl() { ServerConnector adminConnector = null; for (Connector connector : jettyServer.getConnectors()) { if (ADMIN_SERVER_CONNECTOR_NAME.equals(connector.getName())) adminConnector = (ServerConnector) connector; } if (adminConnector == null) { List<String> adminListeners = config.adminListeners(); if (adminListeners == null) { return advertisedUrl(); } else if (adminListeners.isEmpty()) { return null; } else { log.error("No admin connector found for listeners {}", adminListeners); return null; } } UriBuilder builder = UriBuilder.fromUri(jettyServer.getURI()); builder.port(adminConnector.getLocalPort()); return builder.build(); } // For testing only public void requestTimeout(long requestTimeoutMs) { this.requestTimeout.timeoutMs(requestTimeoutMs); } // For testing
|
registered with the given {@link ResourceConfig}. * This may be used to, for example, add REST extensions via {@link #registerRestExtensions(Herder, ResourceConfig)}. * <p> * <em>N.B.: Classes do <b>not</b> need to register the resources provided in {@link #regularResources()} with * the {@link ResourceConfig} parameter in this method; they are automatically registered by the parent class.</em> * @param resourceConfig the {@link ResourceConfig} that the server's regular listeners are registered with; never null */ protected void configureRegularResources(ResourceConfig resourceConfig) { // No-op by default } /** * Pluggable hook to customize the admin resources on this server after they have been instantiated and registered * with the given {@link ResourceConfig}. This may be used to, for example, add REST extensions via * {@link #registerRestExtensions(Herder, ResourceConfig)}. * <p> * <em>N.B.: Classes do <b>not</b> need to register the resources provided in {@link #adminResources()} with * the {@link ResourceConfig} parameter in this method; they are automatically registered by the parent class.</em> * @param adminResourceConfig the {@link ResourceConfig} that the server's admin listeners are registered with; never null */ protected void configureAdminResources(ResourceConfig adminResourceConfig) { // No-op by default } public URI serverUrl() { return jettyServer.getURI(); } public void stop() { log.info("Stopping REST server"); try { if (handlers.isRunning()) { for (Handler handler : handlers.getHandlers()) { if (handler != null) { Utils.closeQuietly(handler::stop, handler.toString()); } } } for (ConnectRestExtension connectRestExtension : connectRestExtensions) { try { connectRestExtension.close(); } catch (IOException e) { log.warn("Error while invoking close on " + connectRestExtension.getClass(), e); } } jettyServer.stop(); jettyServer.join(); } catch (Exception e) { throw new ConnectException ("Unable to stop REST server", e); } finally { try { jettyServer.destroy(); } catch (Exception e) { log.error("Unable to destroy REST server", e); } } log.info("REST server stopped"); } /** * Get the URL to advertise to other workers and clients. This uses the default connector from the embedded Jetty * server, unless overrides for advertised hostname and/or port are provided via configs. {@link #initializeServer()} * must be invoked successfully before calling this method. */ public URI advertisedUrl() { UriBuilder builder = UriBuilder.fromUri(jettyServer.getURI()); String advertisedSecurityProtocol = determineAdvertisedProtocol(); ServerConnector serverConnector = findConnector(advertisedSecurityProtocol); builder.scheme(advertisedSecurityProtocol); String advertisedHostname = config.advertisedHostName(); if (advertisedHostname != null && !advertisedHostname.isEmpty()) builder.host(advertisedHostname); else if (serverConnector != null && serverConnector.getHost() != null && !serverConnector.getHost().isEmpty()) builder.host(serverConnector.getHost()); Integer advertisedPort = config.advertisedPort(); if (advertisedPort != null) builder.port(advertisedPort); else if (serverConnector != null && serverConnector.getPort() > 0) builder.port(serverConnector.getPort()); else if (serverConnector != null && serverConnector.getLocalPort() > 0) builder.port(serverConnector.getLocalPort()); log.info("Advertised URI: {}", builder.build()); return builder.build(); } /** * @return the admin url for this worker. Can be null if admin endpoints are disabled. */ public URI adminUrl() { ServerConnector adminConnector = null; for (Connector connector : jettyServer.getConnectors()) { if (ADMIN_SERVER_CONNECTOR_NAME.equals(connector.getName())) adminConnector = (ServerConnector) connector; } if (adminConnector == null) { List<String> adminListeners = config.adminListeners(); if (adminListeners == null) { return advertisedUrl(); } else if (adminListeners.isEmpty()) { return null; } else { log.error("No admin connector found for listeners {}", adminListeners); return null; } } UriBuilder builder = UriBuilder.fromUri(jettyServer.getURI()); builder.port(adminConnector.getLocalPort()); return builder.build(); } // For testing only public void requestTimeout(long requestTimeoutMs) { this.requestTimeout.timeoutMs(requestTimeoutMs); } // For testing
|
java
|
/* * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.internal.logger; import java.util. <mask> <mask> <mask> <mask> ; import java.util.Iterator; import java.util.Map; import java.util.ResourceBundle; import java.util.ServiceLoader; import java.util.function.BooleanSupplier; import java.util.function.Function; import java.util.function.Supplier; import java.lang.System.LoggerFinder; import java.lang.System.Logger; import java.lang.ref.WeakReference; import java.util.Objects; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import jdk.internal.misc.InnocuousThread; import jdk.internal.misc.VM; import sun.util.logging.PlatformLogger; import jdk.internal.logger.LazyLoggers.LazyLoggerAccessor; /** * The BootstrapLogger class handles all the logic needed by Lazy Loggers * to delay the creation of System.Logger instances until the VM is booted. * By extension - it also contains the logic that will delay the creation * of JUL Loggers until the LogManager is initialized by the application, in * the common case where JUL is the default and there is no custom JUL * configuration. * * A BootstrapLogger instance is both a Logger and a * PlatformLogger.Bridge instance, which will put all Log messages in a queue * until the VM is booted. * Once the VM is booted, it obtain the real System.Logger instance from the * LoggerFinder and flushes the message to the queue. * * There are a few caveat: * - the queue may not be flush until the next message is logged after * the VM is booted * - while the BootstrapLogger is active, the default implementation * for all convenience methods is used * - PlatformLogger.setLevel calls are ignored * * */ public final class BootstrapLogger implements Logger, PlatformLogger.Bridge, PlatformLogger.ConfigurableBridge { // We use the BootstrapExecutors class to submit delayed messages // to an independent InnocuousThread which will ensure that // delayed log events
|
/* * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.internal.logger; import java.util. HashMap ; import java.util.Iterator; import java.util.Map; import java.util.ResourceBundle; import java.util.ServiceLoader; import java.util.function.BooleanSupplier; import java.util.function.Function; import java.util.function.Supplier; import java.lang.System.LoggerFinder; import java.lang.System.Logger; import java.lang.ref.WeakReference; import java.util.Objects; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import jdk.internal.misc.InnocuousThread; import jdk.internal.misc.VM; import sun.util.logging.PlatformLogger; import jdk.internal.logger.LazyLoggers.LazyLoggerAccessor; /** * The BootstrapLogger class handles all the logic needed by Lazy Loggers * to delay the creation of System.Logger instances until the VM is booted. * By extension - it also contains the logic that will delay the creation * of JUL Loggers until the LogManager is initialized by the application, in * the common case where JUL is the default and there is no custom JUL * configuration. * * A BootstrapLogger instance is both a Logger and a * PlatformLogger.Bridge instance, which will put all Log messages in a queue * until the VM is booted. * Once the VM is booted, it obtain the real System.Logger instance from the * LoggerFinder and flushes the message to the queue. * * There are a few caveat: * - the queue may not be flush until the next message is logged after * the VM is booted * - while the BootstrapLogger is active, the default implementation * for all convenience methods is used * - PlatformLogger.setLevel calls are ignored * * */ public final class BootstrapLogger implements Logger, PlatformLogger.Bridge, PlatformLogger.ConfigurableBridge { // We use the BootstrapExecutors class to submit delayed messages // to an independent InnocuousThread which will ensure that // delayed log events
|
java
|
synchronized (BootstrapLogger.class) { return useSurrogateLoggers(); } } // Called by LazyLoggerAccessor. This method will determine whether // to create a BootstrapLogger (if the VM is not yet booted), // a SurrogateLogger (if JUL is the default backend and there // is no custom JUL configuration and LogManager is not yet initialized), // or a logger returned by the loaded LoggerFinder (all other cases). static Logger getLogger(LazyLoggerAccessor accessor, BooleanSupplier isLoading) { if (!BootstrapLogger.isBooted() || isLoading != null && isLoading.getAsBoolean()) { return new BootstrapLogger(accessor, isLoading); } else { if (useSurrogateLoggers()) { // JUL is the default backend, there is no custom configuration, // LogManager has not been used. synchronized(BootstrapLogger.class) { if (useSurrogateLoggers()) { return createSurrogateLogger(accessor); } } } // Already booted. Return the real logger. return accessor.createLogger(); } } // trigger class initialization outside of holding lock static void ensureBackendDetected() { assert VM.isBooted() : "VM is not booted"; // triggers detection of the backend var backend = DetectBackend.detectedBackend; } // If the backend is JUL, and there is no custom configuration, and // nobody has attempted to call LogManager.getLogManager() yet, then // we can temporarily substitute JUL Logger with SurrogateLoggers, // which avoids the cost of actually loading up the LogManager... // The RedirectedLoggers class has the logic to create such surrogate // loggers, and to possibly replace them with real JUL loggers if // someone calls LogManager.getLogManager(). static final class RedirectedLoggers implements Function<LazyLoggerAccessor, SurrogateLogger> { // all accesses must be synchronized on the outer BootstrapLogger.class final Map<LazyLoggerAccessor, SurrogateLogger> redirectedLoggers = new <mask> <mask> <mask> <mask> <>(); // all accesses must be synchronized on the outer BootstrapLogger.class // The redirectLoggers map will be cleared when LogManager is initialized. boolean cleared; @Override // all accesses must be synchronized on the outer BootstrapLogger.class public SurrogateLogger apply(LazyLoggerAccessor t) { if (cleared) throw new IllegalStateException("LoggerFinder already initialized"); return SurrogateLogger.makeSurrogateLogger(t.getLoggerName()); } // all accesses must be synchronized on the outer BootstrapLogger.class SurrogateLogger get(LazyLoggerAccessor a) { if (cleared) throw new IllegalStateException("LoggerFinder already initialized"); return redirectedLoggers.computeIfAbsent(a, this); } // all accesses must be synchronized on the outer BootstrapLogger.class Map<LazyLoggerAccessor, SurrogateLogger> drainLoggersMap() { if (redirectedLoggers.isEmpty()) return null; if (cleared) throw new IllegalStateException("LoggerFinder already initialized"); final Map<LazyLoggerAccessor, SurrogateLogger> accessors = new <mask> <mask> <mask> <mask> <>(redirectedLoggers); redirectedLoggers.clear(); cleared = true; return accessors; } static void replaceSurrogateLoggers(Map<LazyLoggerAccessor, SurrogateLogger> accessors) { // When the backend is JUL we want to force the creation of // JUL loggers here: some tests are expecting that the // PlatformLogger will create JUL loggers as soon as the // LogManager is initialized. // // If the backend is not JUL then we can delay the re-creation // of the wrapped logger until they are next accessed. // final LoggingBackend detectedBackend = DetectBackend.detectedBackend; final boolean lazy = detectedBackend != LoggingBackend.JUL_DEFAULT && detectedBackend != LoggingBackend.JUL_WITH_CONFIG; for (Map.Entry<LazyLoggerAccessor, SurrogateLogger> a : accessors.entrySet()) { a.getKey().release(a.getValue(), !lazy); } } // all accesses must be synchronized on the outer BootstrapLogger.class static final RedirectedLoggers INSTANCE = new RedirectedLoggers(); } static synchronized Logger createSurrogateLogger(LazyLoggerAccessor a) { // accesses to RedirectedLoggers is synchronized on BootstrapLogger.class return RedirectedLoggers.INSTANCE.get(a); } private static volatile boolean logManagerConfigured;
|
synchronized (BootstrapLogger.class) { return useSurrogateLoggers(); } } // Called by LazyLoggerAccessor. This method will determine whether // to create a BootstrapLogger (if the VM is not yet booted), // a SurrogateLogger (if JUL is the default backend and there // is no custom JUL configuration and LogManager is not yet initialized), // or a logger returned by the loaded LoggerFinder (all other cases). static Logger getLogger(LazyLoggerAccessor accessor, BooleanSupplier isLoading) { if (!BootstrapLogger.isBooted() || isLoading != null && isLoading.getAsBoolean()) { return new BootstrapLogger(accessor, isLoading); } else { if (useSurrogateLoggers()) { // JUL is the default backend, there is no custom configuration, // LogManager has not been used. synchronized(BootstrapLogger.class) { if (useSurrogateLoggers()) { return createSurrogateLogger(accessor); } } } // Already booted. Return the real logger. return accessor.createLogger(); } } // trigger class initialization outside of holding lock static void ensureBackendDetected() { assert VM.isBooted() : "VM is not booted"; // triggers detection of the backend var backend = DetectBackend.detectedBackend; } // If the backend is JUL, and there is no custom configuration, and // nobody has attempted to call LogManager.getLogManager() yet, then // we can temporarily substitute JUL Logger with SurrogateLoggers, // which avoids the cost of actually loading up the LogManager... // The RedirectedLoggers class has the logic to create such surrogate // loggers, and to possibly replace them with real JUL loggers if // someone calls LogManager.getLogManager(). static final class RedirectedLoggers implements Function<LazyLoggerAccessor, SurrogateLogger> { // all accesses must be synchronized on the outer BootstrapLogger.class final Map<LazyLoggerAccessor, SurrogateLogger> redirectedLoggers = new HashMap <>(); // all accesses must be synchronized on the outer BootstrapLogger.class // The redirectLoggers map will be cleared when LogManager is initialized. boolean cleared; @Override // all accesses must be synchronized on the outer BootstrapLogger.class public SurrogateLogger apply(LazyLoggerAccessor t) { if (cleared) throw new IllegalStateException("LoggerFinder already initialized"); return SurrogateLogger.makeSurrogateLogger(t.getLoggerName()); } // all accesses must be synchronized on the outer BootstrapLogger.class SurrogateLogger get(LazyLoggerAccessor a) { if (cleared) throw new IllegalStateException("LoggerFinder already initialized"); return redirectedLoggers.computeIfAbsent(a, this); } // all accesses must be synchronized on the outer BootstrapLogger.class Map<LazyLoggerAccessor, SurrogateLogger> drainLoggersMap() { if (redirectedLoggers.isEmpty()) return null; if (cleared) throw new IllegalStateException("LoggerFinder already initialized"); final Map<LazyLoggerAccessor, SurrogateLogger> accessors = new HashMap <>(redirectedLoggers); redirectedLoggers.clear(); cleared = true; return accessors; } static void replaceSurrogateLoggers(Map<LazyLoggerAccessor, SurrogateLogger> accessors) { // When the backend is JUL we want to force the creation of // JUL loggers here: some tests are expecting that the // PlatformLogger will create JUL loggers as soon as the // LogManager is initialized. // // If the backend is not JUL then we can delay the re-creation // of the wrapped logger until they are next accessed. // final LoggingBackend detectedBackend = DetectBackend.detectedBackend; final boolean lazy = detectedBackend != LoggingBackend.JUL_DEFAULT && detectedBackend != LoggingBackend.JUL_WITH_CONFIG; for (Map.Entry<LazyLoggerAccessor, SurrogateLogger> a : accessors.entrySet()) { a.getKey().release(a.getValue(), !lazy); } } // all accesses must be synchronized on the outer BootstrapLogger.class static final RedirectedLoggers INSTANCE = new RedirectedLoggers(); } static synchronized Logger createSurrogateLogger(LazyLoggerAccessor a) { // accesses to RedirectedLoggers is synchronized on BootstrapLogger.class return RedirectedLoggers.INSTANCE.get(a); } private static volatile boolean logManagerConfigured;
|
java
|
{ if (useSurrogateLoggers()) { return createSurrogateLogger(accessor); } } } // Already booted. Return the real logger. return accessor.createLogger(); } } // trigger class initialization outside of holding lock static void ensureBackendDetected() { assert VM.isBooted() : "VM is not booted"; // triggers detection of the backend var backend = DetectBackend.detectedBackend; } // If the backend is JUL, and there is no custom configuration, and // nobody has attempted to call LogManager.getLogManager() yet, then // we can temporarily substitute JUL Logger with SurrogateLoggers, // which avoids the cost of actually loading up the LogManager... // The RedirectedLoggers class has the logic to create such surrogate // loggers, and to possibly replace them with real JUL loggers if // someone calls LogManager.getLogManager(). static final class RedirectedLoggers implements Function<LazyLoggerAccessor, SurrogateLogger> { // all accesses must be synchronized on the outer BootstrapLogger.class final Map<LazyLoggerAccessor, SurrogateLogger> redirectedLoggers = new <mask> <mask> <mask> <mask> <>(); // all accesses must be synchronized on the outer BootstrapLogger.class // The redirectLoggers map will be cleared when LogManager is initialized. boolean cleared; @Override // all accesses must be synchronized on the outer BootstrapLogger.class public SurrogateLogger apply(LazyLoggerAccessor t) { if (cleared) throw new IllegalStateException("LoggerFinder already initialized"); return SurrogateLogger.makeSurrogateLogger(t.getLoggerName()); } // all accesses must be synchronized on the outer BootstrapLogger.class SurrogateLogger get(LazyLoggerAccessor a) { if (cleared) throw new IllegalStateException("LoggerFinder already initialized"); return redirectedLoggers.computeIfAbsent(a, this); } // all accesses must be synchronized on the outer BootstrapLogger.class Map<LazyLoggerAccessor, SurrogateLogger> drainLoggersMap() { if (redirectedLoggers.isEmpty()) return null; if (cleared) throw new IllegalStateException("LoggerFinder already initialized"); final Map<LazyLoggerAccessor, SurrogateLogger> accessors = new <mask> <mask> <mask> <mask> <>(redirectedLoggers); redirectedLoggers.clear(); cleared = true; return accessors; } static void replaceSurrogateLoggers(Map<LazyLoggerAccessor, SurrogateLogger> accessors) { // When the backend is JUL we want to force the creation of // JUL loggers here: some tests are expecting that the // PlatformLogger will create JUL loggers as soon as the // LogManager is initialized. // // If the backend is not JUL then we can delay the re-creation // of the wrapped logger until they are next accessed. // final LoggingBackend detectedBackend = DetectBackend.detectedBackend; final boolean lazy = detectedBackend != LoggingBackend.JUL_DEFAULT && detectedBackend != LoggingBackend.JUL_WITH_CONFIG; for (Map.Entry<LazyLoggerAccessor, SurrogateLogger> a : accessors.entrySet()) { a.getKey().release(a.getValue(), !lazy); } } // all accesses must be synchronized on the outer BootstrapLogger.class static final RedirectedLoggers INSTANCE = new RedirectedLoggers(); } static synchronized Logger createSurrogateLogger(LazyLoggerAccessor a) { // accesses to RedirectedLoggers is synchronized on BootstrapLogger.class return RedirectedLoggers.INSTANCE.get(a); } private static volatile boolean logManagerConfigured; private static synchronized Map<LazyLoggerAccessor, SurrogateLogger> releaseSurrogateLoggers() { // first check whether there's a chance that we have used // surrogate loggers; Will be false if logManagerConfigured is already // true. final boolean releaseSurrogateLoggers = useSurrogateLoggers(); // then sets the flag that tells that the log manager is configured logManagerConfigured = true; // finally retrieves all surrogate loggers that should be replaced // by real JUL loggers, and return them in the form of a redirected // loggers map. if (releaseSurrogateLoggers) { // accesses to RedirectedLoggers is synchronized on BootstrapLogger.class return RedirectedLoggers.INSTANCE.drainLoggersMap(); } else { return null; } } public static void redirectTemporaryLoggers() { // This call is
|
{ if (useSurrogateLoggers()) { return createSurrogateLogger(accessor); } } } // Already booted. Return the real logger. return accessor.createLogger(); } } // trigger class initialization outside of holding lock static void ensureBackendDetected() { assert VM.isBooted() : "VM is not booted"; // triggers detection of the backend var backend = DetectBackend.detectedBackend; } // If the backend is JUL, and there is no custom configuration, and // nobody has attempted to call LogManager.getLogManager() yet, then // we can temporarily substitute JUL Logger with SurrogateLoggers, // which avoids the cost of actually loading up the LogManager... // The RedirectedLoggers class has the logic to create such surrogate // loggers, and to possibly replace them with real JUL loggers if // someone calls LogManager.getLogManager(). static final class RedirectedLoggers implements Function<LazyLoggerAccessor, SurrogateLogger> { // all accesses must be synchronized on the outer BootstrapLogger.class final Map<LazyLoggerAccessor, SurrogateLogger> redirectedLoggers = new HashMap <>(); // all accesses must be synchronized on the outer BootstrapLogger.class // The redirectLoggers map will be cleared when LogManager is initialized. boolean cleared; @Override // all accesses must be synchronized on the outer BootstrapLogger.class public SurrogateLogger apply(LazyLoggerAccessor t) { if (cleared) throw new IllegalStateException("LoggerFinder already initialized"); return SurrogateLogger.makeSurrogateLogger(t.getLoggerName()); } // all accesses must be synchronized on the outer BootstrapLogger.class SurrogateLogger get(LazyLoggerAccessor a) { if (cleared) throw new IllegalStateException("LoggerFinder already initialized"); return redirectedLoggers.computeIfAbsent(a, this); } // all accesses must be synchronized on the outer BootstrapLogger.class Map<LazyLoggerAccessor, SurrogateLogger> drainLoggersMap() { if (redirectedLoggers.isEmpty()) return null; if (cleared) throw new IllegalStateException("LoggerFinder already initialized"); final Map<LazyLoggerAccessor, SurrogateLogger> accessors = new HashMap <>(redirectedLoggers); redirectedLoggers.clear(); cleared = true; return accessors; } static void replaceSurrogateLoggers(Map<LazyLoggerAccessor, SurrogateLogger> accessors) { // When the backend is JUL we want to force the creation of // JUL loggers here: some tests are expecting that the // PlatformLogger will create JUL loggers as soon as the // LogManager is initialized. // // If the backend is not JUL then we can delay the re-creation // of the wrapped logger until they are next accessed. // final LoggingBackend detectedBackend = DetectBackend.detectedBackend; final boolean lazy = detectedBackend != LoggingBackend.JUL_DEFAULT && detectedBackend != LoggingBackend.JUL_WITH_CONFIG; for (Map.Entry<LazyLoggerAccessor, SurrogateLogger> a : accessors.entrySet()) { a.getKey().release(a.getValue(), !lazy); } } // all accesses must be synchronized on the outer BootstrapLogger.class static final RedirectedLoggers INSTANCE = new RedirectedLoggers(); } static synchronized Logger createSurrogateLogger(LazyLoggerAccessor a) { // accesses to RedirectedLoggers is synchronized on BootstrapLogger.class return RedirectedLoggers.INSTANCE.get(a); } private static volatile boolean logManagerConfigured; private static synchronized Map<LazyLoggerAccessor, SurrogateLogger> releaseSurrogateLoggers() { // first check whether there's a chance that we have used // surrogate loggers; Will be false if logManagerConfigured is already // true. final boolean releaseSurrogateLoggers = useSurrogateLoggers(); // then sets the flag that tells that the log manager is configured logManagerConfigured = true; // finally retrieves all surrogate loggers that should be replaced // by real JUL loggers, and return them in the form of a redirected // loggers map. if (releaseSurrogateLoggers) { // accesses to RedirectedLoggers is synchronized on BootstrapLogger.class return RedirectedLoggers.INSTANCE.drainLoggersMap(); } else { return null; } } public static void redirectTemporaryLoggers() { // This call is
|
java
|
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.compute.operator; import org.elasticsearch.TransportVersion; import org.elasticsearch.TransportVersions; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.compute.Describable; import org.elasticsearch.compute.aggregation.AggregatorMode; import org.elasticsearch.compute.aggregation. <mask> <mask> <mask> <mask> <mask> <mask> <mask> ; import org.elasticsearch.compute.aggregation. <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function; import org.elasticsearch.compute.aggregation.blockhash.BlockHash; import org.elasticsearch.compute.data.Block; import org.elasticsearch.compute.data.IntBlock; import org.elasticsearch.compute.data.IntVector; import org.elasticsearch.compute.data.Page; import org.elasticsearch.core.Releasables; import org.elasticsearch.core.TimeValue; import org.elasticsearch.index.analysis.AnalysisRegistry; import org.elasticsearch.xcontent.XContentBuilder; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.Supplier; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; public class HashAggregationOperator implements Operator { public record HashAggregationOperatorFactory( List<BlockHash.GroupSpec> groups, AggregatorMode aggregatorMode, List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory> aggregators, int maxPageSize, AnalysisRegistry analysisRegistry ) implements OperatorFactory { @Override public Operator get(DriverContext driverContext) { if (groups.stream().anyMatch(BlockHash.GroupSpec::isCategorize)) { return new HashAggregationOperator( aggregators, () -> BlockHash.buildCategorizeBlockHash( groups, aggregatorMode, driverContext.blockFactory(), analysisRegistry, maxPageSize ), driverContext ); } return new HashAggregationOperator( aggregators, () -> BlockHash.build(groups, driverContext.blockFactory(), maxPageSize, false), driverContext ); } @Override public String describe() { return "HashAggregationOperator[mode = " + "<not-needed>" + ", aggs = " + aggregators.stream().map(Describable::describe).collect(joining(", ")) + "]"; } } private boolean finished; private Page output; private final BlockHash blockHash; private final List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> > aggregators; private final DriverContext driverContext; /** * Nanoseconds this operator has spent hashing grouping keys. */ private long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private long aggregationNanos; /** * Count of pages this operator has processed. */ private int pagesProcessed; /** * Count of rows this operator has received. */ private long rowsReceived; /** * Count of rows this operator has emitted. */ private long rowsEmitted; @SuppressWarnings("this-escape") public HashAggregationOperator( List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory> aggregators, Supplier<BlockHash> blockHash, DriverContext driverContext ) { this.aggregators = new ArrayList<>(aggregators.size()); this.driverContext = driverContext; boolean success = false; try { this.blockHash = blockHash.get(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory a : aggregators)
|
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.compute.operator; import org.elasticsearch.TransportVersion; import org.elasticsearch.TransportVersions; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.compute.Describable; import org.elasticsearch.compute.aggregation.AggregatorMode; import org.elasticsearch.compute.aggregation. GroupingAggregator ; import org.elasticsearch.compute.aggregation. GroupingAggregator Function; import org.elasticsearch.compute.aggregation.blockhash.BlockHash; import org.elasticsearch.compute.data.Block; import org.elasticsearch.compute.data.IntBlock; import org.elasticsearch.compute.data.IntVector; import org.elasticsearch.compute.data.Page; import org.elasticsearch.core.Releasables; import org.elasticsearch.core.TimeValue; import org.elasticsearch.index.analysis.AnalysisRegistry; import org.elasticsearch.xcontent.XContentBuilder; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.Supplier; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; public class HashAggregationOperator implements Operator { public record HashAggregationOperatorFactory( List<BlockHash.GroupSpec> groups, AggregatorMode aggregatorMode, List< GroupingAggregator .Factory> aggregators, int maxPageSize, AnalysisRegistry analysisRegistry ) implements OperatorFactory { @Override public Operator get(DriverContext driverContext) { if (groups.stream().anyMatch(BlockHash.GroupSpec::isCategorize)) { return new HashAggregationOperator( aggregators, () -> BlockHash.buildCategorizeBlockHash( groups, aggregatorMode, driverContext.blockFactory(), analysisRegistry, maxPageSize ), driverContext ); } return new HashAggregationOperator( aggregators, () -> BlockHash.build(groups, driverContext.blockFactory(), maxPageSize, false), driverContext ); } @Override public String describe() { return "HashAggregationOperator[mode = " + "<not-needed>" + ", aggs = " + aggregators.stream().map(Describable::describe).collect(joining(", ")) + "]"; } } private boolean finished; private Page output; private final BlockHash blockHash; private final List< GroupingAggregator > aggregators; private final DriverContext driverContext; /** * Nanoseconds this operator has spent hashing grouping keys. */ private long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private long aggregationNanos; /** * Count of pages this operator has processed. */ private int pagesProcessed; /** * Count of rows this operator has received. */ private long rowsReceived; /** * Count of rows this operator has emitted. */ private long rowsEmitted; @SuppressWarnings("this-escape") public HashAggregationOperator( List< GroupingAggregator .Factory> aggregators, Supplier<BlockHash> blockHash, DriverContext driverContext ) { this.aggregators = new ArrayList<>(aggregators.size()); this.driverContext = driverContext; boolean success = false; try { this.blockHash = blockHash.get(); for ( GroupingAggregator .Factory a : aggregators)
|
java
|
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.compute.operator; import org.elasticsearch.TransportVersion; import org.elasticsearch.TransportVersions; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.compute.Describable; import org.elasticsearch.compute.aggregation.AggregatorMode; import org.elasticsearch.compute.aggregation. <mask> <mask> <mask> <mask> <mask> <mask> <mask> ; import org.elasticsearch.compute.aggregation. <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function; import org.elasticsearch.compute.aggregation.blockhash.BlockHash; import org.elasticsearch.compute.data.Block; import org.elasticsearch.compute.data.IntBlock; import org.elasticsearch.compute.data.IntVector; import org.elasticsearch.compute.data.Page; import org.elasticsearch.core.Releasables; import org.elasticsearch.core.TimeValue; import org.elasticsearch.index.analysis.AnalysisRegistry; import org.elasticsearch.xcontent.XContentBuilder; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.Supplier; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; public class HashAggregationOperator implements Operator { public record HashAggregationOperatorFactory( List<BlockHash.GroupSpec> groups, AggregatorMode aggregatorMode, List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory> aggregators, int maxPageSize, AnalysisRegistry analysisRegistry ) implements OperatorFactory { @Override public Operator get(DriverContext driverContext) { if (groups.stream().anyMatch(BlockHash.GroupSpec::isCategorize)) { return new HashAggregationOperator( aggregators, () -> BlockHash.buildCategorizeBlockHash( groups, aggregatorMode, driverContext.blockFactory(), analysisRegistry, maxPageSize ), driverContext ); } return new HashAggregationOperator( aggregators, () -> BlockHash.build(groups, driverContext.blockFactory(), maxPageSize, false), driverContext ); } @Override public String describe() { return "HashAggregationOperator[mode = " + "<not-needed>" + ", aggs = " + aggregators.stream().map(Describable::describe).collect(joining(", ")) + "]"; } } private boolean finished; private Page output; private final BlockHash blockHash; private final List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> > aggregators; private final DriverContext driverContext; /** * Nanoseconds this operator has spent hashing grouping keys. */ private long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private long aggregationNanos; /** * Count of pages this operator has processed. */ private int pagesProcessed; /** * Count of rows this operator has received. */ private long rowsReceived; /** * Count of rows this operator has emitted. */ private long rowsEmitted; @SuppressWarnings("this-escape") public HashAggregationOperator( List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory> aggregators, Supplier<BlockHash> blockHash, DriverContext driverContext ) { this.aggregators = new ArrayList<>(aggregators.size()); this.driverContext = driverContext; boolean success = false; try { this.blockHash = blockHash.get(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory a : aggregators) { this.aggregators.add(a.apply(driverContext)); } success
|
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.compute.operator; import org.elasticsearch.TransportVersion; import org.elasticsearch.TransportVersions; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.compute.Describable; import org.elasticsearch.compute.aggregation.AggregatorMode; import org.elasticsearch.compute.aggregation. GroupingAggregator ; import org.elasticsearch.compute.aggregation. GroupingAggregator Function; import org.elasticsearch.compute.aggregation.blockhash.BlockHash; import org.elasticsearch.compute.data.Block; import org.elasticsearch.compute.data.IntBlock; import org.elasticsearch.compute.data.IntVector; import org.elasticsearch.compute.data.Page; import org.elasticsearch.core.Releasables; import org.elasticsearch.core.TimeValue; import org.elasticsearch.index.analysis.AnalysisRegistry; import org.elasticsearch.xcontent.XContentBuilder; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.Supplier; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; public class HashAggregationOperator implements Operator { public record HashAggregationOperatorFactory( List<BlockHash.GroupSpec> groups, AggregatorMode aggregatorMode, List< GroupingAggregator .Factory> aggregators, int maxPageSize, AnalysisRegistry analysisRegistry ) implements OperatorFactory { @Override public Operator get(DriverContext driverContext) { if (groups.stream().anyMatch(BlockHash.GroupSpec::isCategorize)) { return new HashAggregationOperator( aggregators, () -> BlockHash.buildCategorizeBlockHash( groups, aggregatorMode, driverContext.blockFactory(), analysisRegistry, maxPageSize ), driverContext ); } return new HashAggregationOperator( aggregators, () -> BlockHash.build(groups, driverContext.blockFactory(), maxPageSize, false), driverContext ); } @Override public String describe() { return "HashAggregationOperator[mode = " + "<not-needed>" + ", aggs = " + aggregators.stream().map(Describable::describe).collect(joining(", ")) + "]"; } } private boolean finished; private Page output; private final BlockHash blockHash; private final List< GroupingAggregator > aggregators; private final DriverContext driverContext; /** * Nanoseconds this operator has spent hashing grouping keys. */ private long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private long aggregationNanos; /** * Count of pages this operator has processed. */ private int pagesProcessed; /** * Count of rows this operator has received. */ private long rowsReceived; /** * Count of rows this operator has emitted. */ private long rowsEmitted; @SuppressWarnings("this-escape") public HashAggregationOperator( List< GroupingAggregator .Factory> aggregators, Supplier<BlockHash> blockHash, DriverContext driverContext ) { this.aggregators = new ArrayList<>(aggregators.size()); this.driverContext = driverContext; boolean success = false; try { this.blockHash = blockHash.get(); for ( GroupingAggregator .Factory a : aggregators) { this.aggregators.add(a.apply(driverContext)); } success
|
java
|
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.compute.operator; import org.elasticsearch.TransportVersion; import org.elasticsearch.TransportVersions; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.compute.Describable; import org.elasticsearch.compute.aggregation.AggregatorMode; import org.elasticsearch.compute.aggregation. <mask> <mask> <mask> <mask> <mask> <mask> <mask> ; import org.elasticsearch.compute.aggregation. <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function; import org.elasticsearch.compute.aggregation.blockhash.BlockHash; import org.elasticsearch.compute.data.Block; import org.elasticsearch.compute.data.IntBlock; import org.elasticsearch.compute.data.IntVector; import org.elasticsearch.compute.data.Page; import org.elasticsearch.core.Releasables; import org.elasticsearch.core.TimeValue; import org.elasticsearch.index.analysis.AnalysisRegistry; import org.elasticsearch.xcontent.XContentBuilder; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.Supplier; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; public class HashAggregationOperator implements Operator { public record HashAggregationOperatorFactory( List<BlockHash.GroupSpec> groups, AggregatorMode aggregatorMode, List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory> aggregators, int maxPageSize, AnalysisRegistry analysisRegistry ) implements OperatorFactory { @Override public Operator get(DriverContext driverContext) { if (groups.stream().anyMatch(BlockHash.GroupSpec::isCategorize)) { return new HashAggregationOperator( aggregators, () -> BlockHash.buildCategorizeBlockHash( groups, aggregatorMode, driverContext.blockFactory(), analysisRegistry, maxPageSize ), driverContext ); } return new HashAggregationOperator( aggregators, () -> BlockHash.build(groups, driverContext.blockFactory(), maxPageSize, false), driverContext ); } @Override public String describe() { return "HashAggregationOperator[mode = " + "<not-needed>" + ", aggs = " + aggregators.stream().map(Describable::describe).collect(joining(", ")) + "]"; } } private boolean finished; private Page output; private final BlockHash blockHash; private final List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> > aggregators; private final DriverContext driverContext; /** * Nanoseconds this operator has spent hashing grouping keys. */ private long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private long aggregationNanos; /** * Count of pages this operator has processed. */ private int pagesProcessed; /** * Count of rows this operator has received. */ private long rowsReceived; /** * Count of rows this operator has emitted. */ private long rowsEmitted; @SuppressWarnings("this-escape") public HashAggregationOperator( List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory> aggregators, Supplier<BlockHash> blockHash, DriverContext driverContext ) { this.aggregators = new ArrayList<>(aggregators.size()); this.driverContext = driverContext; boolean success = false; try { this.blockHash = blockHash.get(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory a : aggregators) { this.aggregators.add(a.apply(driverContext)); } success = true; } finally { if (success == false) { close(); } } } @Override public boolean needsInput() { return finished == false; } @Override public void addInput(Page page) { try { <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput[] prepared = new <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput[aggregators.size()]; class AddInput implements <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput { long hashStart = System.nanoTime(); long aggStart; @Override
|
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.compute.operator; import org.elasticsearch.TransportVersion; import org.elasticsearch.TransportVersions; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.compute.Describable; import org.elasticsearch.compute.aggregation.AggregatorMode; import org.elasticsearch.compute.aggregation. GroupingAggregator ; import org.elasticsearch.compute.aggregation. GroupingAggregator Function; import org.elasticsearch.compute.aggregation.blockhash.BlockHash; import org.elasticsearch.compute.data.Block; import org.elasticsearch.compute.data.IntBlock; import org.elasticsearch.compute.data.IntVector; import org.elasticsearch.compute.data.Page; import org.elasticsearch.core.Releasables; import org.elasticsearch.core.TimeValue; import org.elasticsearch.index.analysis.AnalysisRegistry; import org.elasticsearch.xcontent.XContentBuilder; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.Supplier; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; public class HashAggregationOperator implements Operator { public record HashAggregationOperatorFactory( List<BlockHash.GroupSpec> groups, AggregatorMode aggregatorMode, List< GroupingAggregator .Factory> aggregators, int maxPageSize, AnalysisRegistry analysisRegistry ) implements OperatorFactory { @Override public Operator get(DriverContext driverContext) { if (groups.stream().anyMatch(BlockHash.GroupSpec::isCategorize)) { return new HashAggregationOperator( aggregators, () -> BlockHash.buildCategorizeBlockHash( groups, aggregatorMode, driverContext.blockFactory(), analysisRegistry, maxPageSize ), driverContext ); } return new HashAggregationOperator( aggregators, () -> BlockHash.build(groups, driverContext.blockFactory(), maxPageSize, false), driverContext ); } @Override public String describe() { return "HashAggregationOperator[mode = " + "<not-needed>" + ", aggs = " + aggregators.stream().map(Describable::describe).collect(joining(", ")) + "]"; } } private boolean finished; private Page output; private final BlockHash blockHash; private final List< GroupingAggregator > aggregators; private final DriverContext driverContext; /** * Nanoseconds this operator has spent hashing grouping keys. */ private long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private long aggregationNanos; /** * Count of pages this operator has processed. */ private int pagesProcessed; /** * Count of rows this operator has received. */ private long rowsReceived; /** * Count of rows this operator has emitted. */ private long rowsEmitted; @SuppressWarnings("this-escape") public HashAggregationOperator( List< GroupingAggregator .Factory> aggregators, Supplier<BlockHash> blockHash, DriverContext driverContext ) { this.aggregators = new ArrayList<>(aggregators.size()); this.driverContext = driverContext; boolean success = false; try { this.blockHash = blockHash.get(); for ( GroupingAggregator .Factory a : aggregators) { this.aggregators.add(a.apply(driverContext)); } success = true; } finally { if (success == false) { close(); } } } @Override public boolean needsInput() { return finished == false; } @Override public void addInput(Page page) { try { GroupingAggregator Function.AddInput[] prepared = new GroupingAggregator Function.AddInput[aggregators.size()]; class AddInput implements GroupingAggregator Function.AddInput { long hashStart = System.nanoTime(); long aggStart; @Override
|
java
|
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.compute.operator; import org.elasticsearch.TransportVersion; import org.elasticsearch.TransportVersions; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.compute.Describable; import org.elasticsearch.compute.aggregation.AggregatorMode; import org.elasticsearch.compute.aggregation. <mask> <mask> <mask> <mask> <mask> <mask> <mask> ; import org.elasticsearch.compute.aggregation. <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function; import org.elasticsearch.compute.aggregation.blockhash.BlockHash; import org.elasticsearch.compute.data.Block; import org.elasticsearch.compute.data.IntBlock; import org.elasticsearch.compute.data.IntVector; import org.elasticsearch.compute.data.Page; import org.elasticsearch.core.Releasables; import org.elasticsearch.core.TimeValue; import org.elasticsearch.index.analysis.AnalysisRegistry; import org.elasticsearch.xcontent.XContentBuilder; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.Supplier; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; public class HashAggregationOperator implements Operator { public record HashAggregationOperatorFactory( List<BlockHash.GroupSpec> groups, AggregatorMode aggregatorMode, List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory> aggregators, int maxPageSize, AnalysisRegistry analysisRegistry ) implements OperatorFactory { @Override public Operator get(DriverContext driverContext) { if (groups.stream().anyMatch(BlockHash.GroupSpec::isCategorize)) { return new HashAggregationOperator( aggregators, () -> BlockHash.buildCategorizeBlockHash( groups, aggregatorMode, driverContext.blockFactory(), analysisRegistry, maxPageSize ), driverContext ); } return new HashAggregationOperator( aggregators, () -> BlockHash.build(groups, driverContext.blockFactory(), maxPageSize, false), driverContext ); } @Override public String describe() { return "HashAggregationOperator[mode = " + "<not-needed>" + ", aggs = " + aggregators.stream().map(Describable::describe).collect(joining(", ")) + "]"; } } private boolean finished; private Page output; private final BlockHash blockHash; private final List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> > aggregators; private final DriverContext driverContext; /** * Nanoseconds this operator has spent hashing grouping keys. */ private long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private long aggregationNanos; /** * Count of pages this operator has processed. */ private int pagesProcessed; /** * Count of rows this operator has received. */ private long rowsReceived; /** * Count of rows this operator has emitted. */ private long rowsEmitted; @SuppressWarnings("this-escape") public HashAggregationOperator( List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory> aggregators, Supplier<BlockHash> blockHash, DriverContext driverContext ) { this.aggregators = new ArrayList<>(aggregators.size()); this.driverContext = driverContext; boolean success = false; try { this.blockHash = blockHash.get(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory a : aggregators) { this.aggregators.add(a.apply(driverContext)); } success = true; } finally { if (success == false) { close(); } } } @Override public boolean needsInput() { return finished == false; } @Override public void addInput(Page page) { try { <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput[] prepared = new <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput[aggregators.size()]; class AddInput implements <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput { long hashStart = System.nanoTime(); long aggStart; @Override public void add(int positionOffset, IntBlock groupIds) { IntVector groupIdsVector = groupIds.asVector(); if (groupIdsVector != null) { add(positionOffset, groupIdsVector); } else { startAggEndHash(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } } @Override public void add(int positionOffset, IntVector groupIds) { startAggEndHash(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } private void startAggEndHash() { aggStart = System.nanoTime(); hashNanos += aggStart - hashStart; } private void end() { hashStart = System.nanoTime(); aggregationNanos += hashStart - aggStart; } @Override
|
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.compute.operator; import org.elasticsearch.TransportVersion; import org.elasticsearch.TransportVersions; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.compute.Describable; import org.elasticsearch.compute.aggregation.AggregatorMode; import org.elasticsearch.compute.aggregation. GroupingAggregator ; import org.elasticsearch.compute.aggregation. GroupingAggregator Function; import org.elasticsearch.compute.aggregation.blockhash.BlockHash; import org.elasticsearch.compute.data.Block; import org.elasticsearch.compute.data.IntBlock; import org.elasticsearch.compute.data.IntVector; import org.elasticsearch.compute.data.Page; import org.elasticsearch.core.Releasables; import org.elasticsearch.core.TimeValue; import org.elasticsearch.index.analysis.AnalysisRegistry; import org.elasticsearch.xcontent.XContentBuilder; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.Supplier; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; public class HashAggregationOperator implements Operator { public record HashAggregationOperatorFactory( List<BlockHash.GroupSpec> groups, AggregatorMode aggregatorMode, List< GroupingAggregator .Factory> aggregators, int maxPageSize, AnalysisRegistry analysisRegistry ) implements OperatorFactory { @Override public Operator get(DriverContext driverContext) { if (groups.stream().anyMatch(BlockHash.GroupSpec::isCategorize)) { return new HashAggregationOperator( aggregators, () -> BlockHash.buildCategorizeBlockHash( groups, aggregatorMode, driverContext.blockFactory(), analysisRegistry, maxPageSize ), driverContext ); } return new HashAggregationOperator( aggregators, () -> BlockHash.build(groups, driverContext.blockFactory(), maxPageSize, false), driverContext ); } @Override public String describe() { return "HashAggregationOperator[mode = " + "<not-needed>" + ", aggs = " + aggregators.stream().map(Describable::describe).collect(joining(", ")) + "]"; } } private boolean finished; private Page output; private final BlockHash blockHash; private final List< GroupingAggregator > aggregators; private final DriverContext driverContext; /** * Nanoseconds this operator has spent hashing grouping keys. */ private long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private long aggregationNanos; /** * Count of pages this operator has processed. */ private int pagesProcessed; /** * Count of rows this operator has received. */ private long rowsReceived; /** * Count of rows this operator has emitted. */ private long rowsEmitted; @SuppressWarnings("this-escape") public HashAggregationOperator( List< GroupingAggregator .Factory> aggregators, Supplier<BlockHash> blockHash, DriverContext driverContext ) { this.aggregators = new ArrayList<>(aggregators.size()); this.driverContext = driverContext; boolean success = false; try { this.blockHash = blockHash.get(); for ( GroupingAggregator .Factory a : aggregators) { this.aggregators.add(a.apply(driverContext)); } success = true; } finally { if (success == false) { close(); } } } @Override public boolean needsInput() { return finished == false; } @Override public void addInput(Page page) { try { GroupingAggregator Function.AddInput[] prepared = new GroupingAggregator Function.AddInput[aggregators.size()]; class AddInput implements GroupingAggregator Function.AddInput { long hashStart = System.nanoTime(); long aggStart; @Override public void add(int positionOffset, IntBlock groupIds) { IntVector groupIdsVector = groupIds.asVector(); if (groupIdsVector != null) { add(positionOffset, groupIdsVector); } else { startAggEndHash(); for ( GroupingAggregator Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } } @Override public void add(int positionOffset, IntVector groupIds) { startAggEndHash(); for ( GroupingAggregator Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } private void startAggEndHash() { aggStart = System.nanoTime(); hashNanos += aggStart - hashStart; } private void end() { hashStart = System.nanoTime(); aggregationNanos += hashStart - aggStart; } @Override
|
java
|
file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.compute.operator; import org.elasticsearch.TransportVersion; import org.elasticsearch.TransportVersions; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.compute.Describable; import org.elasticsearch.compute.aggregation.AggregatorMode; import org.elasticsearch.compute.aggregation. <mask> <mask> <mask> <mask> <mask> <mask> <mask> ; import org.elasticsearch.compute.aggregation. <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function; import org.elasticsearch.compute.aggregation.blockhash.BlockHash; import org.elasticsearch.compute.data.Block; import org.elasticsearch.compute.data.IntBlock; import org.elasticsearch.compute.data.IntVector; import org.elasticsearch.compute.data.Page; import org.elasticsearch.core.Releasables; import org.elasticsearch.core.TimeValue; import org.elasticsearch.index.analysis.AnalysisRegistry; import org.elasticsearch.xcontent.XContentBuilder; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.Supplier; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; public class HashAggregationOperator implements Operator { public record HashAggregationOperatorFactory( List<BlockHash.GroupSpec> groups, AggregatorMode aggregatorMode, List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory> aggregators, int maxPageSize, AnalysisRegistry analysisRegistry ) implements OperatorFactory { @Override public Operator get(DriverContext driverContext) { if (groups.stream().anyMatch(BlockHash.GroupSpec::isCategorize)) { return new HashAggregationOperator( aggregators, () -> BlockHash.buildCategorizeBlockHash( groups, aggregatorMode, driverContext.blockFactory(), analysisRegistry, maxPageSize ), driverContext ); } return new HashAggregationOperator( aggregators, () -> BlockHash.build(groups, driverContext.blockFactory(), maxPageSize, false), driverContext ); } @Override public String describe() { return "HashAggregationOperator[mode = " + "<not-needed>" + ", aggs = " + aggregators.stream().map(Describable::describe).collect(joining(", ")) + "]"; } } private boolean finished; private Page output; private final BlockHash blockHash; private final List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> > aggregators; private final DriverContext driverContext; /** * Nanoseconds this operator has spent hashing grouping keys. */ private long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private long aggregationNanos; /** * Count of pages this operator has processed. */ private int pagesProcessed; /** * Count of rows this operator has received. */ private long rowsReceived; /** * Count of rows this operator has emitted. */ private long rowsEmitted; @SuppressWarnings("this-escape") public HashAggregationOperator( List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory> aggregators, Supplier<BlockHash> blockHash, DriverContext driverContext ) { this.aggregators = new ArrayList<>(aggregators.size()); this.driverContext = driverContext; boolean success = false; try { this.blockHash = blockHash.get(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory a : aggregators) { this.aggregators.add(a.apply(driverContext)); } success = true; } finally { if (success == false) { close(); } } } @Override public boolean needsInput() { return finished == false; } @Override public void addInput(Page page) { try { <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput[] prepared = new <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput[aggregators.size()]; class AddInput implements <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput { long hashStart = System.nanoTime(); long aggStart; @Override public void add(int positionOffset, IntBlock groupIds) { IntVector groupIdsVector = groupIds.asVector(); if (groupIdsVector != null) { add(positionOffset, groupIdsVector); } else { startAggEndHash(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } } @Override public void add(int positionOffset, IntVector groupIds) { startAggEndHash(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } private void startAggEndHash() { aggStart = System.nanoTime(); hashNanos += aggStart - hashStart; } private void end() { hashStart = System.nanoTime(); aggregationNanos += hashStart - aggStart; } @Override public void close() { Releasables.closeExpectNoException(prepared); } } try (AddInput add = new AddInput()) { checkState(needsInput(), "Operator is already finishing"); requireNonNull(page, "page is null"); for (int i = 0; i < prepared.length; i++) { prepared[i] = aggregators.get(i).prepareProcessPage(blockHash, page); } blockHash.add(wrapPage(page), add); hashNanos += System.nanoTime() - add.hashStart; } } finally { page.releaseBlocks(); pagesProcessed++; rowsReceived += page.getPositionCount(); } } @Override public Page getOutput() { Page p = output; if (p != null) { rowsEmitted += p.getPositionCount(); } output = null; return
|
file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.compute.operator; import org.elasticsearch.TransportVersion; import org.elasticsearch.TransportVersions; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.compute.Describable; import org.elasticsearch.compute.aggregation.AggregatorMode; import org.elasticsearch.compute.aggregation. GroupingAggregator ; import org.elasticsearch.compute.aggregation. GroupingAggregator Function; import org.elasticsearch.compute.aggregation.blockhash.BlockHash; import org.elasticsearch.compute.data.Block; import org.elasticsearch.compute.data.IntBlock; import org.elasticsearch.compute.data.IntVector; import org.elasticsearch.compute.data.Page; import org.elasticsearch.core.Releasables; import org.elasticsearch.core.TimeValue; import org.elasticsearch.index.analysis.AnalysisRegistry; import org.elasticsearch.xcontent.XContentBuilder; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.Supplier; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; public class HashAggregationOperator implements Operator { public record HashAggregationOperatorFactory( List<BlockHash.GroupSpec> groups, AggregatorMode aggregatorMode, List< GroupingAggregator .Factory> aggregators, int maxPageSize, AnalysisRegistry analysisRegistry ) implements OperatorFactory { @Override public Operator get(DriverContext driverContext) { if (groups.stream().anyMatch(BlockHash.GroupSpec::isCategorize)) { return new HashAggregationOperator( aggregators, () -> BlockHash.buildCategorizeBlockHash( groups, aggregatorMode, driverContext.blockFactory(), analysisRegistry, maxPageSize ), driverContext ); } return new HashAggregationOperator( aggregators, () -> BlockHash.build(groups, driverContext.blockFactory(), maxPageSize, false), driverContext ); } @Override public String describe() { return "HashAggregationOperator[mode = " + "<not-needed>" + ", aggs = " + aggregators.stream().map(Describable::describe).collect(joining(", ")) + "]"; } } private boolean finished; private Page output; private final BlockHash blockHash; private final List< GroupingAggregator > aggregators; private final DriverContext driverContext; /** * Nanoseconds this operator has spent hashing grouping keys. */ private long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private long aggregationNanos; /** * Count of pages this operator has processed. */ private int pagesProcessed; /** * Count of rows this operator has received. */ private long rowsReceived; /** * Count of rows this operator has emitted. */ private long rowsEmitted; @SuppressWarnings("this-escape") public HashAggregationOperator( List< GroupingAggregator .Factory> aggregators, Supplier<BlockHash> blockHash, DriverContext driverContext ) { this.aggregators = new ArrayList<>(aggregators.size()); this.driverContext = driverContext; boolean success = false; try { this.blockHash = blockHash.get(); for ( GroupingAggregator .Factory a : aggregators) { this.aggregators.add(a.apply(driverContext)); } success = true; } finally { if (success == false) { close(); } } } @Override public boolean needsInput() { return finished == false; } @Override public void addInput(Page page) { try { GroupingAggregator Function.AddInput[] prepared = new GroupingAggregator Function.AddInput[aggregators.size()]; class AddInput implements GroupingAggregator Function.AddInput { long hashStart = System.nanoTime(); long aggStart; @Override public void add(int positionOffset, IntBlock groupIds) { IntVector groupIdsVector = groupIds.asVector(); if (groupIdsVector != null) { add(positionOffset, groupIdsVector); } else { startAggEndHash(); for ( GroupingAggregator Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } } @Override public void add(int positionOffset, IntVector groupIds) { startAggEndHash(); for ( GroupingAggregator Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } private void startAggEndHash() { aggStart = System.nanoTime(); hashNanos += aggStart - hashStart; } private void end() { hashStart = System.nanoTime(); aggregationNanos += hashStart - aggStart; } @Override public void close() { Releasables.closeExpectNoException(prepared); } } try (AddInput add = new AddInput()) { checkState(needsInput(), "Operator is already finishing"); requireNonNull(page, "page is null"); for (int i = 0; i < prepared.length; i++) { prepared[i] = aggregators.get(i).prepareProcessPage(blockHash, page); } blockHash.add(wrapPage(page), add); hashNanos += System.nanoTime() - add.hashStart; } } finally { page.releaseBlocks(); pagesProcessed++; rowsReceived += page.getPositionCount(); } } @Override public Page getOutput() { Page p = output; if (p != null) { rowsEmitted += p.getPositionCount(); } output = null; return
|
java
|
import org.elasticsearch.compute.aggregation.AggregatorMode; import org.elasticsearch.compute.aggregation. <mask> <mask> <mask> <mask> <mask> <mask> <mask> ; import org.elasticsearch.compute.aggregation. <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function; import org.elasticsearch.compute.aggregation.blockhash.BlockHash; import org.elasticsearch.compute.data.Block; import org.elasticsearch.compute.data.IntBlock; import org.elasticsearch.compute.data.IntVector; import org.elasticsearch.compute.data.Page; import org.elasticsearch.core.Releasables; import org.elasticsearch.core.TimeValue; import org.elasticsearch.index.analysis.AnalysisRegistry; import org.elasticsearch.xcontent.XContentBuilder; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.Supplier; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; public class HashAggregationOperator implements Operator { public record HashAggregationOperatorFactory( List<BlockHash.GroupSpec> groups, AggregatorMode aggregatorMode, List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory> aggregators, int maxPageSize, AnalysisRegistry analysisRegistry ) implements OperatorFactory { @Override public Operator get(DriverContext driverContext) { if (groups.stream().anyMatch(BlockHash.GroupSpec::isCategorize)) { return new HashAggregationOperator( aggregators, () -> BlockHash.buildCategorizeBlockHash( groups, aggregatorMode, driverContext.blockFactory(), analysisRegistry, maxPageSize ), driverContext ); } return new HashAggregationOperator( aggregators, () -> BlockHash.build(groups, driverContext.blockFactory(), maxPageSize, false), driverContext ); } @Override public String describe() { return "HashAggregationOperator[mode = " + "<not-needed>" + ", aggs = " + aggregators.stream().map(Describable::describe).collect(joining(", ")) + "]"; } } private boolean finished; private Page output; private final BlockHash blockHash; private final List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> > aggregators; private final DriverContext driverContext; /** * Nanoseconds this operator has spent hashing grouping keys. */ private long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private long aggregationNanos; /** * Count of pages this operator has processed. */ private int pagesProcessed; /** * Count of rows this operator has received. */ private long rowsReceived; /** * Count of rows this operator has emitted. */ private long rowsEmitted; @SuppressWarnings("this-escape") public HashAggregationOperator( List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory> aggregators, Supplier<BlockHash> blockHash, DriverContext driverContext ) { this.aggregators = new ArrayList<>(aggregators.size()); this.driverContext = driverContext; boolean success = false; try { this.blockHash = blockHash.get(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory a : aggregators) { this.aggregators.add(a.apply(driverContext)); } success = true; } finally { if (success == false) { close(); } } } @Override public boolean needsInput() { return finished == false; } @Override public void addInput(Page page) { try { <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput[] prepared = new <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput[aggregators.size()]; class AddInput implements <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput { long hashStart = System.nanoTime(); long aggStart; @Override public void add(int positionOffset, IntBlock groupIds) { IntVector groupIdsVector = groupIds.asVector(); if (groupIdsVector != null) { add(positionOffset, groupIdsVector); } else { startAggEndHash(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } } @Override public void add(int positionOffset, IntVector groupIds) { startAggEndHash(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } private void startAggEndHash() { aggStart = System.nanoTime(); hashNanos += aggStart - hashStart; } private void end() { hashStart = System.nanoTime(); aggregationNanos += hashStart - aggStart; } @Override public void close() { Releasables.closeExpectNoException(prepared); } } try (AddInput add = new AddInput()) { checkState(needsInput(), "Operator is already finishing"); requireNonNull(page, "page is null"); for (int i = 0; i < prepared.length; i++) { prepared[i] = aggregators.get(i).prepareProcessPage(blockHash, page); } blockHash.add(wrapPage(page), add); hashNanos += System.nanoTime() - add.hashStart; } } finally { page.releaseBlocks(); pagesProcessed++; rowsReceived += page.getPositionCount(); } } @Override public Page getOutput() { Page p = output; if (p != null) { rowsEmitted += p.getPositionCount(); } output = null; return p; } @Override public void finish() { if (finished) { return; } finished = true; Block[] blocks = null; IntVector selected = null; boolean success = false;
|
import org.elasticsearch.compute.aggregation.AggregatorMode; import org.elasticsearch.compute.aggregation. GroupingAggregator ; import org.elasticsearch.compute.aggregation. GroupingAggregator Function; import org.elasticsearch.compute.aggregation.blockhash.BlockHash; import org.elasticsearch.compute.data.Block; import org.elasticsearch.compute.data.IntBlock; import org.elasticsearch.compute.data.IntVector; import org.elasticsearch.compute.data.Page; import org.elasticsearch.core.Releasables; import org.elasticsearch.core.TimeValue; import org.elasticsearch.index.analysis.AnalysisRegistry; import org.elasticsearch.xcontent.XContentBuilder; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.Supplier; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; public class HashAggregationOperator implements Operator { public record HashAggregationOperatorFactory( List<BlockHash.GroupSpec> groups, AggregatorMode aggregatorMode, List< GroupingAggregator .Factory> aggregators, int maxPageSize, AnalysisRegistry analysisRegistry ) implements OperatorFactory { @Override public Operator get(DriverContext driverContext) { if (groups.stream().anyMatch(BlockHash.GroupSpec::isCategorize)) { return new HashAggregationOperator( aggregators, () -> BlockHash.buildCategorizeBlockHash( groups, aggregatorMode, driverContext.blockFactory(), analysisRegistry, maxPageSize ), driverContext ); } return new HashAggregationOperator( aggregators, () -> BlockHash.build(groups, driverContext.blockFactory(), maxPageSize, false), driverContext ); } @Override public String describe() { return "HashAggregationOperator[mode = " + "<not-needed>" + ", aggs = " + aggregators.stream().map(Describable::describe).collect(joining(", ")) + "]"; } } private boolean finished; private Page output; private final BlockHash blockHash; private final List< GroupingAggregator > aggregators; private final DriverContext driverContext; /** * Nanoseconds this operator has spent hashing grouping keys. */ private long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private long aggregationNanos; /** * Count of pages this operator has processed. */ private int pagesProcessed; /** * Count of rows this operator has received. */ private long rowsReceived; /** * Count of rows this operator has emitted. */ private long rowsEmitted; @SuppressWarnings("this-escape") public HashAggregationOperator( List< GroupingAggregator .Factory> aggregators, Supplier<BlockHash> blockHash, DriverContext driverContext ) { this.aggregators = new ArrayList<>(aggregators.size()); this.driverContext = driverContext; boolean success = false; try { this.blockHash = blockHash.get(); for ( GroupingAggregator .Factory a : aggregators) { this.aggregators.add(a.apply(driverContext)); } success = true; } finally { if (success == false) { close(); } } } @Override public boolean needsInput() { return finished == false; } @Override public void addInput(Page page) { try { GroupingAggregator Function.AddInput[] prepared = new GroupingAggregator Function.AddInput[aggregators.size()]; class AddInput implements GroupingAggregator Function.AddInput { long hashStart = System.nanoTime(); long aggStart; @Override public void add(int positionOffset, IntBlock groupIds) { IntVector groupIdsVector = groupIds.asVector(); if (groupIdsVector != null) { add(positionOffset, groupIdsVector); } else { startAggEndHash(); for ( GroupingAggregator Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } } @Override public void add(int positionOffset, IntVector groupIds) { startAggEndHash(); for ( GroupingAggregator Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } private void startAggEndHash() { aggStart = System.nanoTime(); hashNanos += aggStart - hashStart; } private void end() { hashStart = System.nanoTime(); aggregationNanos += hashStart - aggStart; } @Override public void close() { Releasables.closeExpectNoException(prepared); } } try (AddInput add = new AddInput()) { checkState(needsInput(), "Operator is already finishing"); requireNonNull(page, "page is null"); for (int i = 0; i < prepared.length; i++) { prepared[i] = aggregators.get(i).prepareProcessPage(blockHash, page); } blockHash.add(wrapPage(page), add); hashNanos += System.nanoTime() - add.hashStart; } } finally { page.releaseBlocks(); pagesProcessed++; rowsReceived += page.getPositionCount(); } } @Override public Page getOutput() { Page p = output; if (p != null) { rowsEmitted += p.getPositionCount(); } output = null; return p; } @Override public void finish() { if (finished) { return; } finished = true; Block[] blocks = null; IntVector selected = null; boolean success = false;
|
java
|
static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; public class HashAggregationOperator implements Operator { public record HashAggregationOperatorFactory( List<BlockHash.GroupSpec> groups, AggregatorMode aggregatorMode, List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory> aggregators, int maxPageSize, AnalysisRegistry analysisRegistry ) implements OperatorFactory { @Override public Operator get(DriverContext driverContext) { if (groups.stream().anyMatch(BlockHash.GroupSpec::isCategorize)) { return new HashAggregationOperator( aggregators, () -> BlockHash.buildCategorizeBlockHash( groups, aggregatorMode, driverContext.blockFactory(), analysisRegistry, maxPageSize ), driverContext ); } return new HashAggregationOperator( aggregators, () -> BlockHash.build(groups, driverContext.blockFactory(), maxPageSize, false), driverContext ); } @Override public String describe() { return "HashAggregationOperator[mode = " + "<not-needed>" + ", aggs = " + aggregators.stream().map(Describable::describe).collect(joining(", ")) + "]"; } } private boolean finished; private Page output; private final BlockHash blockHash; private final List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> > aggregators; private final DriverContext driverContext; /** * Nanoseconds this operator has spent hashing grouping keys. */ private long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private long aggregationNanos; /** * Count of pages this operator has processed. */ private int pagesProcessed; /** * Count of rows this operator has received. */ private long rowsReceived; /** * Count of rows this operator has emitted. */ private long rowsEmitted; @SuppressWarnings("this-escape") public HashAggregationOperator( List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory> aggregators, Supplier<BlockHash> blockHash, DriverContext driverContext ) { this.aggregators = new ArrayList<>(aggregators.size()); this.driverContext = driverContext; boolean success = false; try { this.blockHash = blockHash.get(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory a : aggregators) { this.aggregators.add(a.apply(driverContext)); } success = true; } finally { if (success == false) { close(); } } } @Override public boolean needsInput() { return finished == false; } @Override public void addInput(Page page) { try { <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput[] prepared = new <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput[aggregators.size()]; class AddInput implements <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput { long hashStart = System.nanoTime(); long aggStart; @Override public void add(int positionOffset, IntBlock groupIds) { IntVector groupIdsVector = groupIds.asVector(); if (groupIdsVector != null) { add(positionOffset, groupIdsVector); } else { startAggEndHash(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } } @Override public void add(int positionOffset, IntVector groupIds) { startAggEndHash(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } private void startAggEndHash() { aggStart = System.nanoTime(); hashNanos += aggStart - hashStart; } private void end() { hashStart = System.nanoTime(); aggregationNanos += hashStart - aggStart; } @Override public void close() { Releasables.closeExpectNoException(prepared); } } try (AddInput add = new AddInput()) { checkState(needsInput(), "Operator is already finishing"); requireNonNull(page, "page is null"); for (int i = 0; i < prepared.length; i++) { prepared[i] = aggregators.get(i).prepareProcessPage(blockHash, page); } blockHash.add(wrapPage(page), add); hashNanos += System.nanoTime() - add.hashStart; } } finally { page.releaseBlocks(); pagesProcessed++; rowsReceived += page.getPositionCount(); } } @Override public Page getOutput() { Page p = output; if (p != null) { rowsEmitted += p.getPositionCount(); } output = null; return p; } @Override public void finish() { if (finished) { return; } finished = true; Block[] blocks = null; IntVector selected = null; boolean success = false; try { selected = blockHash.nonEmpty(); Block[] keys = blockHash.getKeys(); int[] aggBlockCounts = aggregators.stream().mapToInt( <mask> <mask> <mask> <mask> <mask> <mask> <mask> ::evaluateBlockCount).toArray(); blocks = new Block[keys.length + Arrays.stream(aggBlockCounts).sum()]; System.arraycopy(keys, 0, blocks, 0, keys.length); int offset = keys.length; for (int i = 0; i < aggregators.size(); i++) { var
|
static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; public class HashAggregationOperator implements Operator { public record HashAggregationOperatorFactory( List<BlockHash.GroupSpec> groups, AggregatorMode aggregatorMode, List< GroupingAggregator .Factory> aggregators, int maxPageSize, AnalysisRegistry analysisRegistry ) implements OperatorFactory { @Override public Operator get(DriverContext driverContext) { if (groups.stream().anyMatch(BlockHash.GroupSpec::isCategorize)) { return new HashAggregationOperator( aggregators, () -> BlockHash.buildCategorizeBlockHash( groups, aggregatorMode, driverContext.blockFactory(), analysisRegistry, maxPageSize ), driverContext ); } return new HashAggregationOperator( aggregators, () -> BlockHash.build(groups, driverContext.blockFactory(), maxPageSize, false), driverContext ); } @Override public String describe() { return "HashAggregationOperator[mode = " + "<not-needed>" + ", aggs = " + aggregators.stream().map(Describable::describe).collect(joining(", ")) + "]"; } } private boolean finished; private Page output; private final BlockHash blockHash; private final List< GroupingAggregator > aggregators; private final DriverContext driverContext; /** * Nanoseconds this operator has spent hashing grouping keys. */ private long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private long aggregationNanos; /** * Count of pages this operator has processed. */ private int pagesProcessed; /** * Count of rows this operator has received. */ private long rowsReceived; /** * Count of rows this operator has emitted. */ private long rowsEmitted; @SuppressWarnings("this-escape") public HashAggregationOperator( List< GroupingAggregator .Factory> aggregators, Supplier<BlockHash> blockHash, DriverContext driverContext ) { this.aggregators = new ArrayList<>(aggregators.size()); this.driverContext = driverContext; boolean success = false; try { this.blockHash = blockHash.get(); for ( GroupingAggregator .Factory a : aggregators) { this.aggregators.add(a.apply(driverContext)); } success = true; } finally { if (success == false) { close(); } } } @Override public boolean needsInput() { return finished == false; } @Override public void addInput(Page page) { try { GroupingAggregator Function.AddInput[] prepared = new GroupingAggregator Function.AddInput[aggregators.size()]; class AddInput implements GroupingAggregator Function.AddInput { long hashStart = System.nanoTime(); long aggStart; @Override public void add(int positionOffset, IntBlock groupIds) { IntVector groupIdsVector = groupIds.asVector(); if (groupIdsVector != null) { add(positionOffset, groupIdsVector); } else { startAggEndHash(); for ( GroupingAggregator Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } } @Override public void add(int positionOffset, IntVector groupIds) { startAggEndHash(); for ( GroupingAggregator Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } private void startAggEndHash() { aggStart = System.nanoTime(); hashNanos += aggStart - hashStart; } private void end() { hashStart = System.nanoTime(); aggregationNanos += hashStart - aggStart; } @Override public void close() { Releasables.closeExpectNoException(prepared); } } try (AddInput add = new AddInput()) { checkState(needsInput(), "Operator is already finishing"); requireNonNull(page, "page is null"); for (int i = 0; i < prepared.length; i++) { prepared[i] = aggregators.get(i).prepareProcessPage(blockHash, page); } blockHash.add(wrapPage(page), add); hashNanos += System.nanoTime() - add.hashStart; } } finally { page.releaseBlocks(); pagesProcessed++; rowsReceived += page.getPositionCount(); } } @Override public Page getOutput() { Page p = output; if (p != null) { rowsEmitted += p.getPositionCount(); } output = null; return p; } @Override public void finish() { if (finished) { return; } finished = true; Block[] blocks = null; IntVector selected = null; boolean success = false; try { selected = blockHash.nonEmpty(); Block[] keys = blockHash.getKeys(); int[] aggBlockCounts = aggregators.stream().mapToInt( GroupingAggregator ::evaluateBlockCount).toArray(); blocks = new Block[keys.length + Arrays.stream(aggBlockCounts).sum()]; System.arraycopy(keys, 0, blocks, 0, keys.length); int offset = keys.length; for (int i = 0; i < aggregators.size(); i++) { var
|
java
|
public class HashAggregationOperator implements Operator { public record HashAggregationOperatorFactory( List<BlockHash.GroupSpec> groups, AggregatorMode aggregatorMode, List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory> aggregators, int maxPageSize, AnalysisRegistry analysisRegistry ) implements OperatorFactory { @Override public Operator get(DriverContext driverContext) { if (groups.stream().anyMatch(BlockHash.GroupSpec::isCategorize)) { return new HashAggregationOperator( aggregators, () -> BlockHash.buildCategorizeBlockHash( groups, aggregatorMode, driverContext.blockFactory(), analysisRegistry, maxPageSize ), driverContext ); } return new HashAggregationOperator( aggregators, () -> BlockHash.build(groups, driverContext.blockFactory(), maxPageSize, false), driverContext ); } @Override public String describe() { return "HashAggregationOperator[mode = " + "<not-needed>" + ", aggs = " + aggregators.stream().map(Describable::describe).collect(joining(", ")) + "]"; } } private boolean finished; private Page output; private final BlockHash blockHash; private final List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> > aggregators; private final DriverContext driverContext; /** * Nanoseconds this operator has spent hashing grouping keys. */ private long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private long aggregationNanos; /** * Count of pages this operator has processed. */ private int pagesProcessed; /** * Count of rows this operator has received. */ private long rowsReceived; /** * Count of rows this operator has emitted. */ private long rowsEmitted; @SuppressWarnings("this-escape") public HashAggregationOperator( List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory> aggregators, Supplier<BlockHash> blockHash, DriverContext driverContext ) { this.aggregators = new ArrayList<>(aggregators.size()); this.driverContext = driverContext; boolean success = false; try { this.blockHash = blockHash.get(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory a : aggregators) { this.aggregators.add(a.apply(driverContext)); } success = true; } finally { if (success == false) { close(); } } } @Override public boolean needsInput() { return finished == false; } @Override public void addInput(Page page) { try { <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput[] prepared = new <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput[aggregators.size()]; class AddInput implements <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput { long hashStart = System.nanoTime(); long aggStart; @Override public void add(int positionOffset, IntBlock groupIds) { IntVector groupIdsVector = groupIds.asVector(); if (groupIdsVector != null) { add(positionOffset, groupIdsVector); } else { startAggEndHash(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } } @Override public void add(int positionOffset, IntVector groupIds) { startAggEndHash(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } private void startAggEndHash() { aggStart = System.nanoTime(); hashNanos += aggStart - hashStart; } private void end() { hashStart = System.nanoTime(); aggregationNanos += hashStart - aggStart; } @Override public void close() { Releasables.closeExpectNoException(prepared); } } try (AddInput add = new AddInput()) { checkState(needsInput(), "Operator is already finishing"); requireNonNull(page, "page is null"); for (int i = 0; i < prepared.length; i++) { prepared[i] = aggregators.get(i).prepareProcessPage(blockHash, page); } blockHash.add(wrapPage(page), add); hashNanos += System.nanoTime() - add.hashStart; } } finally { page.releaseBlocks(); pagesProcessed++; rowsReceived += page.getPositionCount(); } } @Override public Page getOutput() { Page p = output; if (p != null) { rowsEmitted += p.getPositionCount(); } output = null; return p; } @Override public void finish() { if (finished) { return; } finished = true; Block[] blocks = null; IntVector selected = null; boolean success = false; try { selected = blockHash.nonEmpty(); Block[] keys = blockHash.getKeys(); int[] aggBlockCounts = aggregators.stream().mapToInt( <mask> <mask> <mask> <mask> <mask> <mask> <mask> ::evaluateBlockCount).toArray(); blocks = new Block[keys.length + Arrays.stream(aggBlockCounts).sum()]; System.arraycopy(keys, 0, blocks, 0, keys.length); int offset = keys.length; for (int i = 0; i < aggregators.size(); i++) { var aggregator = aggregators.get(i); aggregator.evaluate(blocks, offset,
|
public class HashAggregationOperator implements Operator { public record HashAggregationOperatorFactory( List<BlockHash.GroupSpec> groups, AggregatorMode aggregatorMode, List< GroupingAggregator .Factory> aggregators, int maxPageSize, AnalysisRegistry analysisRegistry ) implements OperatorFactory { @Override public Operator get(DriverContext driverContext) { if (groups.stream().anyMatch(BlockHash.GroupSpec::isCategorize)) { return new HashAggregationOperator( aggregators, () -> BlockHash.buildCategorizeBlockHash( groups, aggregatorMode, driverContext.blockFactory(), analysisRegistry, maxPageSize ), driverContext ); } return new HashAggregationOperator( aggregators, () -> BlockHash.build(groups, driverContext.blockFactory(), maxPageSize, false), driverContext ); } @Override public String describe() { return "HashAggregationOperator[mode = " + "<not-needed>" + ", aggs = " + aggregators.stream().map(Describable::describe).collect(joining(", ")) + "]"; } } private boolean finished; private Page output; private final BlockHash blockHash; private final List< GroupingAggregator > aggregators; private final DriverContext driverContext; /** * Nanoseconds this operator has spent hashing grouping keys. */ private long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private long aggregationNanos; /** * Count of pages this operator has processed. */ private int pagesProcessed; /** * Count of rows this operator has received. */ private long rowsReceived; /** * Count of rows this operator has emitted. */ private long rowsEmitted; @SuppressWarnings("this-escape") public HashAggregationOperator( List< GroupingAggregator .Factory> aggregators, Supplier<BlockHash> blockHash, DriverContext driverContext ) { this.aggregators = new ArrayList<>(aggregators.size()); this.driverContext = driverContext; boolean success = false; try { this.blockHash = blockHash.get(); for ( GroupingAggregator .Factory a : aggregators) { this.aggregators.add(a.apply(driverContext)); } success = true; } finally { if (success == false) { close(); } } } @Override public boolean needsInput() { return finished == false; } @Override public void addInput(Page page) { try { GroupingAggregator Function.AddInput[] prepared = new GroupingAggregator Function.AddInput[aggregators.size()]; class AddInput implements GroupingAggregator Function.AddInput { long hashStart = System.nanoTime(); long aggStart; @Override public void add(int positionOffset, IntBlock groupIds) { IntVector groupIdsVector = groupIds.asVector(); if (groupIdsVector != null) { add(positionOffset, groupIdsVector); } else { startAggEndHash(); for ( GroupingAggregator Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } } @Override public void add(int positionOffset, IntVector groupIds) { startAggEndHash(); for ( GroupingAggregator Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } private void startAggEndHash() { aggStart = System.nanoTime(); hashNanos += aggStart - hashStart; } private void end() { hashStart = System.nanoTime(); aggregationNanos += hashStart - aggStart; } @Override public void close() { Releasables.closeExpectNoException(prepared); } } try (AddInput add = new AddInput()) { checkState(needsInput(), "Operator is already finishing"); requireNonNull(page, "page is null"); for (int i = 0; i < prepared.length; i++) { prepared[i] = aggregators.get(i).prepareProcessPage(blockHash, page); } blockHash.add(wrapPage(page), add); hashNanos += System.nanoTime() - add.hashStart; } } finally { page.releaseBlocks(); pagesProcessed++; rowsReceived += page.getPositionCount(); } } @Override public Page getOutput() { Page p = output; if (p != null) { rowsEmitted += p.getPositionCount(); } output = null; return p; } @Override public void finish() { if (finished) { return; } finished = true; Block[] blocks = null; IntVector selected = null; boolean success = false; try { selected = blockHash.nonEmpty(); Block[] keys = blockHash.getKeys(); int[] aggBlockCounts = aggregators.stream().mapToInt( GroupingAggregator ::evaluateBlockCount).toArray(); blocks = new Block[keys.length + Arrays.stream(aggBlockCounts).sum()]; System.arraycopy(keys, 0, blocks, 0, keys.length); int offset = keys.length; for (int i = 0; i < aggregators.size(); i++) { var aggregator = aggregators.get(i); aggregator.evaluate(blocks, offset,
|
java
|
{ public record HashAggregationOperatorFactory( List<BlockHash.GroupSpec> groups, AggregatorMode aggregatorMode, List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory> aggregators, int maxPageSize, AnalysisRegistry analysisRegistry ) implements OperatorFactory { @Override public Operator get(DriverContext driverContext) { if (groups.stream().anyMatch(BlockHash.GroupSpec::isCategorize)) { return new HashAggregationOperator( aggregators, () -> BlockHash.buildCategorizeBlockHash( groups, aggregatorMode, driverContext.blockFactory(), analysisRegistry, maxPageSize ), driverContext ); } return new HashAggregationOperator( aggregators, () -> BlockHash.build(groups, driverContext.blockFactory(), maxPageSize, false), driverContext ); } @Override public String describe() { return "HashAggregationOperator[mode = " + "<not-needed>" + ", aggs = " + aggregators.stream().map(Describable::describe).collect(joining(", ")) + "]"; } } private boolean finished; private Page output; private final BlockHash blockHash; private final List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> > aggregators; private final DriverContext driverContext; /** * Nanoseconds this operator has spent hashing grouping keys. */ private long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private long aggregationNanos; /** * Count of pages this operator has processed. */ private int pagesProcessed; /** * Count of rows this operator has received. */ private long rowsReceived; /** * Count of rows this operator has emitted. */ private long rowsEmitted; @SuppressWarnings("this-escape") public HashAggregationOperator( List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory> aggregators, Supplier<BlockHash> blockHash, DriverContext driverContext ) { this.aggregators = new ArrayList<>(aggregators.size()); this.driverContext = driverContext; boolean success = false; try { this.blockHash = blockHash.get(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory a : aggregators) { this.aggregators.add(a.apply(driverContext)); } success = true; } finally { if (success == false) { close(); } } } @Override public boolean needsInput() { return finished == false; } @Override public void addInput(Page page) { try { <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput[] prepared = new <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput[aggregators.size()]; class AddInput implements <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput { long hashStart = System.nanoTime(); long aggStart; @Override public void add(int positionOffset, IntBlock groupIds) { IntVector groupIdsVector = groupIds.asVector(); if (groupIdsVector != null) { add(positionOffset, groupIdsVector); } else { startAggEndHash(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } } @Override public void add(int positionOffset, IntVector groupIds) { startAggEndHash(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } private void startAggEndHash() { aggStart = System.nanoTime(); hashNanos += aggStart - hashStart; } private void end() { hashStart = System.nanoTime(); aggregationNanos += hashStart - aggStart; } @Override public void close() { Releasables.closeExpectNoException(prepared); } } try (AddInput add = new AddInput()) { checkState(needsInput(), "Operator is already finishing"); requireNonNull(page, "page is null"); for (int i = 0; i < prepared.length; i++) { prepared[i] = aggregators.get(i).prepareProcessPage(blockHash, page); } blockHash.add(wrapPage(page), add); hashNanos += System.nanoTime() - add.hashStart; } } finally { page.releaseBlocks(); pagesProcessed++; rowsReceived += page.getPositionCount(); } } @Override public Page getOutput() { Page p = output; if (p != null) { rowsEmitted += p.getPositionCount(); } output = null; return p; } @Override public void finish() { if (finished) { return; } finished = true; Block[] blocks = null; IntVector selected = null; boolean success = false; try { selected = blockHash.nonEmpty(); Block[] keys = blockHash.getKeys(); int[] aggBlockCounts = aggregators.stream().mapToInt( <mask> <mask> <mask> <mask> <mask> <mask> <mask> ::evaluateBlockCount).toArray(); blocks = new Block[keys.length + Arrays.stream(aggBlockCounts).sum()]; System.arraycopy(keys, 0, blocks, 0, keys.length); int offset = keys.length; for (int i = 0; i < aggregators.size(); i++) { var aggregator = aggregators.get(i); aggregator.evaluate(blocks, offset, selected, driverContext); offset += aggBlockCounts[i];
|
{ public record HashAggregationOperatorFactory( List<BlockHash.GroupSpec> groups, AggregatorMode aggregatorMode, List< GroupingAggregator .Factory> aggregators, int maxPageSize, AnalysisRegistry analysisRegistry ) implements OperatorFactory { @Override public Operator get(DriverContext driverContext) { if (groups.stream().anyMatch(BlockHash.GroupSpec::isCategorize)) { return new HashAggregationOperator( aggregators, () -> BlockHash.buildCategorizeBlockHash( groups, aggregatorMode, driverContext.blockFactory(), analysisRegistry, maxPageSize ), driverContext ); } return new HashAggregationOperator( aggregators, () -> BlockHash.build(groups, driverContext.blockFactory(), maxPageSize, false), driverContext ); } @Override public String describe() { return "HashAggregationOperator[mode = " + "<not-needed>" + ", aggs = " + aggregators.stream().map(Describable::describe).collect(joining(", ")) + "]"; } } private boolean finished; private Page output; private final BlockHash blockHash; private final List< GroupingAggregator > aggregators; private final DriverContext driverContext; /** * Nanoseconds this operator has spent hashing grouping keys. */ private long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private long aggregationNanos; /** * Count of pages this operator has processed. */ private int pagesProcessed; /** * Count of rows this operator has received. */ private long rowsReceived; /** * Count of rows this operator has emitted. */ private long rowsEmitted; @SuppressWarnings("this-escape") public HashAggregationOperator( List< GroupingAggregator .Factory> aggregators, Supplier<BlockHash> blockHash, DriverContext driverContext ) { this.aggregators = new ArrayList<>(aggregators.size()); this.driverContext = driverContext; boolean success = false; try { this.blockHash = blockHash.get(); for ( GroupingAggregator .Factory a : aggregators) { this.aggregators.add(a.apply(driverContext)); } success = true; } finally { if (success == false) { close(); } } } @Override public boolean needsInput() { return finished == false; } @Override public void addInput(Page page) { try { GroupingAggregator Function.AddInput[] prepared = new GroupingAggregator Function.AddInput[aggregators.size()]; class AddInput implements GroupingAggregator Function.AddInput { long hashStart = System.nanoTime(); long aggStart; @Override public void add(int positionOffset, IntBlock groupIds) { IntVector groupIdsVector = groupIds.asVector(); if (groupIdsVector != null) { add(positionOffset, groupIdsVector); } else { startAggEndHash(); for ( GroupingAggregator Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } } @Override public void add(int positionOffset, IntVector groupIds) { startAggEndHash(); for ( GroupingAggregator Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } private void startAggEndHash() { aggStart = System.nanoTime(); hashNanos += aggStart - hashStart; } private void end() { hashStart = System.nanoTime(); aggregationNanos += hashStart - aggStart; } @Override public void close() { Releasables.closeExpectNoException(prepared); } } try (AddInput add = new AddInput()) { checkState(needsInput(), "Operator is already finishing"); requireNonNull(page, "page is null"); for (int i = 0; i < prepared.length; i++) { prepared[i] = aggregators.get(i).prepareProcessPage(blockHash, page); } blockHash.add(wrapPage(page), add); hashNanos += System.nanoTime() - add.hashStart; } } finally { page.releaseBlocks(); pagesProcessed++; rowsReceived += page.getPositionCount(); } } @Override public Page getOutput() { Page p = output; if (p != null) { rowsEmitted += p.getPositionCount(); } output = null; return p; } @Override public void finish() { if (finished) { return; } finished = true; Block[] blocks = null; IntVector selected = null; boolean success = false; try { selected = blockHash.nonEmpty(); Block[] keys = blockHash.getKeys(); int[] aggBlockCounts = aggregators.stream().mapToInt( GroupingAggregator ::evaluateBlockCount).toArray(); blocks = new Block[keys.length + Arrays.stream(aggBlockCounts).sum()]; System.arraycopy(keys, 0, blocks, 0, keys.length); int offset = keys.length; for (int i = 0; i < aggregators.size(); i++) { var aggregator = aggregators.get(i); aggregator.evaluate(blocks, offset, selected, driverContext); offset += aggBlockCounts[i];
|
java
|
-> BlockHash.buildCategorizeBlockHash( groups, aggregatorMode, driverContext.blockFactory(), analysisRegistry, maxPageSize ), driverContext ); } return new HashAggregationOperator( aggregators, () -> BlockHash.build(groups, driverContext.blockFactory(), maxPageSize, false), driverContext ); } @Override public String describe() { return "HashAggregationOperator[mode = " + "<not-needed>" + ", aggs = " + aggregators.stream().map(Describable::describe).collect(joining(", ")) + "]"; } } private boolean finished; private Page output; private final BlockHash blockHash; private final List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> > aggregators; private final DriverContext driverContext; /** * Nanoseconds this operator has spent hashing grouping keys. */ private long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private long aggregationNanos; /** * Count of pages this operator has processed. */ private int pagesProcessed; /** * Count of rows this operator has received. */ private long rowsReceived; /** * Count of rows this operator has emitted. */ private long rowsEmitted; @SuppressWarnings("this-escape") public HashAggregationOperator( List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory> aggregators, Supplier<BlockHash> blockHash, DriverContext driverContext ) { this.aggregators = new ArrayList<>(aggregators.size()); this.driverContext = driverContext; boolean success = false; try { this.blockHash = blockHash.get(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory a : aggregators) { this.aggregators.add(a.apply(driverContext)); } success = true; } finally { if (success == false) { close(); } } } @Override public boolean needsInput() { return finished == false; } @Override public void addInput(Page page) { try { <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput[] prepared = new <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput[aggregators.size()]; class AddInput implements <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput { long hashStart = System.nanoTime(); long aggStart; @Override public void add(int positionOffset, IntBlock groupIds) { IntVector groupIdsVector = groupIds.asVector(); if (groupIdsVector != null) { add(positionOffset, groupIdsVector); } else { startAggEndHash(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } } @Override public void add(int positionOffset, IntVector groupIds) { startAggEndHash(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } private void startAggEndHash() { aggStart = System.nanoTime(); hashNanos += aggStart - hashStart; } private void end() { hashStart = System.nanoTime(); aggregationNanos += hashStart - aggStart; } @Override public void close() { Releasables.closeExpectNoException(prepared); } } try (AddInput add = new AddInput()) { checkState(needsInput(), "Operator is already finishing"); requireNonNull(page, "page is null"); for (int i = 0; i < prepared.length; i++) { prepared[i] = aggregators.get(i).prepareProcessPage(blockHash, page); } blockHash.add(wrapPage(page), add); hashNanos += System.nanoTime() - add.hashStart; } } finally { page.releaseBlocks(); pagesProcessed++; rowsReceived += page.getPositionCount(); } } @Override public Page getOutput() { Page p = output; if (p != null) { rowsEmitted += p.getPositionCount(); } output = null; return p; } @Override public void finish() { if (finished) { return; } finished = true; Block[] blocks = null; IntVector selected = null; boolean success = false; try { selected = blockHash.nonEmpty(); Block[] keys = blockHash.getKeys(); int[] aggBlockCounts = aggregators.stream().mapToInt( <mask> <mask> <mask> <mask> <mask> <mask> <mask> ::evaluateBlockCount).toArray(); blocks = new Block[keys.length + Arrays.stream(aggBlockCounts).sum()]; System.arraycopy(keys, 0, blocks, 0, keys.length); int offset = keys.length; for (int i = 0; i < aggregators.size(); i++) { var aggregator = aggregators.get(i); aggregator.evaluate(blocks, offset, selected, driverContext); offset += aggBlockCounts[i]; } output = new Page(blocks); success = true; } finally { // selected should always be closed if (selected != null) { selected.close(); } if (success == false && blocks != null) { Releasables.closeExpectNoException(blocks);
|
-> BlockHash.buildCategorizeBlockHash( groups, aggregatorMode, driverContext.blockFactory(), analysisRegistry, maxPageSize ), driverContext ); } return new HashAggregationOperator( aggregators, () -> BlockHash.build(groups, driverContext.blockFactory(), maxPageSize, false), driverContext ); } @Override public String describe() { return "HashAggregationOperator[mode = " + "<not-needed>" + ", aggs = " + aggregators.stream().map(Describable::describe).collect(joining(", ")) + "]"; } } private boolean finished; private Page output; private final BlockHash blockHash; private final List< GroupingAggregator > aggregators; private final DriverContext driverContext; /** * Nanoseconds this operator has spent hashing grouping keys. */ private long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private long aggregationNanos; /** * Count of pages this operator has processed. */ private int pagesProcessed; /** * Count of rows this operator has received. */ private long rowsReceived; /** * Count of rows this operator has emitted. */ private long rowsEmitted; @SuppressWarnings("this-escape") public HashAggregationOperator( List< GroupingAggregator .Factory> aggregators, Supplier<BlockHash> blockHash, DriverContext driverContext ) { this.aggregators = new ArrayList<>(aggregators.size()); this.driverContext = driverContext; boolean success = false; try { this.blockHash = blockHash.get(); for ( GroupingAggregator .Factory a : aggregators) { this.aggregators.add(a.apply(driverContext)); } success = true; } finally { if (success == false) { close(); } } } @Override public boolean needsInput() { return finished == false; } @Override public void addInput(Page page) { try { GroupingAggregator Function.AddInput[] prepared = new GroupingAggregator Function.AddInput[aggregators.size()]; class AddInput implements GroupingAggregator Function.AddInput { long hashStart = System.nanoTime(); long aggStart; @Override public void add(int positionOffset, IntBlock groupIds) { IntVector groupIdsVector = groupIds.asVector(); if (groupIdsVector != null) { add(positionOffset, groupIdsVector); } else { startAggEndHash(); for ( GroupingAggregator Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } } @Override public void add(int positionOffset, IntVector groupIds) { startAggEndHash(); for ( GroupingAggregator Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } private void startAggEndHash() { aggStart = System.nanoTime(); hashNanos += aggStart - hashStart; } private void end() { hashStart = System.nanoTime(); aggregationNanos += hashStart - aggStart; } @Override public void close() { Releasables.closeExpectNoException(prepared); } } try (AddInput add = new AddInput()) { checkState(needsInput(), "Operator is already finishing"); requireNonNull(page, "page is null"); for (int i = 0; i < prepared.length; i++) { prepared[i] = aggregators.get(i).prepareProcessPage(blockHash, page); } blockHash.add(wrapPage(page), add); hashNanos += System.nanoTime() - add.hashStart; } } finally { page.releaseBlocks(); pagesProcessed++; rowsReceived += page.getPositionCount(); } } @Override public Page getOutput() { Page p = output; if (p != null) { rowsEmitted += p.getPositionCount(); } output = null; return p; } @Override public void finish() { if (finished) { return; } finished = true; Block[] blocks = null; IntVector selected = null; boolean success = false; try { selected = blockHash.nonEmpty(); Block[] keys = blockHash.getKeys(); int[] aggBlockCounts = aggregators.stream().mapToInt( GroupingAggregator ::evaluateBlockCount).toArray(); blocks = new Block[keys.length + Arrays.stream(aggBlockCounts).sum()]; System.arraycopy(keys, 0, blocks, 0, keys.length); int offset = keys.length; for (int i = 0; i < aggregators.size(); i++) { var aggregator = aggregators.get(i); aggregator.evaluate(blocks, offset, selected, driverContext); offset += aggBlockCounts[i]; } output = new Page(blocks); success = true; } finally { // selected should always be closed if (selected != null) { selected.close(); } if (success == false && blocks != null) { Releasables.closeExpectNoException(blocks);
|
java
|
} @Override public String describe() { return "HashAggregationOperator[mode = " + "<not-needed>" + ", aggs = " + aggregators.stream().map(Describable::describe).collect(joining(", ")) + "]"; } } private boolean finished; private Page output; private final BlockHash blockHash; private final List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> > aggregators; private final DriverContext driverContext; /** * Nanoseconds this operator has spent hashing grouping keys. */ private long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private long aggregationNanos; /** * Count of pages this operator has processed. */ private int pagesProcessed; /** * Count of rows this operator has received. */ private long rowsReceived; /** * Count of rows this operator has emitted. */ private long rowsEmitted; @SuppressWarnings("this-escape") public HashAggregationOperator( List< <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory> aggregators, Supplier<BlockHash> blockHash, DriverContext driverContext ) { this.aggregators = new ArrayList<>(aggregators.size()); this.driverContext = driverContext; boolean success = false; try { this.blockHash = blockHash.get(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> .Factory a : aggregators) { this.aggregators.add(a.apply(driverContext)); } success = true; } finally { if (success == false) { close(); } } } @Override public boolean needsInput() { return finished == false; } @Override public void addInput(Page page) { try { <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput[] prepared = new <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput[aggregators.size()]; class AddInput implements <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput { long hashStart = System.nanoTime(); long aggStart; @Override public void add(int positionOffset, IntBlock groupIds) { IntVector groupIdsVector = groupIds.asVector(); if (groupIdsVector != null) { add(positionOffset, groupIdsVector); } else { startAggEndHash(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } } @Override public void add(int positionOffset, IntVector groupIds) { startAggEndHash(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } private void startAggEndHash() { aggStart = System.nanoTime(); hashNanos += aggStart - hashStart; } private void end() { hashStart = System.nanoTime(); aggregationNanos += hashStart - aggStart; } @Override public void close() { Releasables.closeExpectNoException(prepared); } } try (AddInput add = new AddInput()) { checkState(needsInput(), "Operator is already finishing"); requireNonNull(page, "page is null"); for (int i = 0; i < prepared.length; i++) { prepared[i] = aggregators.get(i).prepareProcessPage(blockHash, page); } blockHash.add(wrapPage(page), add); hashNanos += System.nanoTime() - add.hashStart; } } finally { page.releaseBlocks(); pagesProcessed++; rowsReceived += page.getPositionCount(); } } @Override public Page getOutput() { Page p = output; if (p != null) { rowsEmitted += p.getPositionCount(); } output = null; return p; } @Override public void finish() { if (finished) { return; } finished = true; Block[] blocks = null; IntVector selected = null; boolean success = false; try { selected = blockHash.nonEmpty(); Block[] keys = blockHash.getKeys(); int[] aggBlockCounts = aggregators.stream().mapToInt( <mask> <mask> <mask> <mask> <mask> <mask> <mask> ::evaluateBlockCount).toArray(); blocks = new Block[keys.length + Arrays.stream(aggBlockCounts).sum()]; System.arraycopy(keys, 0, blocks, 0, keys.length); int offset = keys.length; for (int i = 0; i < aggregators.size(); i++) { var aggregator = aggregators.get(i); aggregator.evaluate(blocks, offset, selected, driverContext); offset += aggBlockCounts[i]; } output = new Page(blocks); success = true; } finally { // selected should always be closed if (selected != null) { selected.close(); } if (success == false && blocks != null) { Releasables.closeExpectNoException(blocks); } } } @Override public boolean isFinished() { return finished && output == null; } @Override public void close() { if (output !=
|
} @Override public String describe() { return "HashAggregationOperator[mode = " + "<not-needed>" + ", aggs = " + aggregators.stream().map(Describable::describe).collect(joining(", ")) + "]"; } } private boolean finished; private Page output; private final BlockHash blockHash; private final List< GroupingAggregator > aggregators; private final DriverContext driverContext; /** * Nanoseconds this operator has spent hashing grouping keys. */ private long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private long aggregationNanos; /** * Count of pages this operator has processed. */ private int pagesProcessed; /** * Count of rows this operator has received. */ private long rowsReceived; /** * Count of rows this operator has emitted. */ private long rowsEmitted; @SuppressWarnings("this-escape") public HashAggregationOperator( List< GroupingAggregator .Factory> aggregators, Supplier<BlockHash> blockHash, DriverContext driverContext ) { this.aggregators = new ArrayList<>(aggregators.size()); this.driverContext = driverContext; boolean success = false; try { this.blockHash = blockHash.get(); for ( GroupingAggregator .Factory a : aggregators) { this.aggregators.add(a.apply(driverContext)); } success = true; } finally { if (success == false) { close(); } } } @Override public boolean needsInput() { return finished == false; } @Override public void addInput(Page page) { try { GroupingAggregator Function.AddInput[] prepared = new GroupingAggregator Function.AddInput[aggregators.size()]; class AddInput implements GroupingAggregator Function.AddInput { long hashStart = System.nanoTime(); long aggStart; @Override public void add(int positionOffset, IntBlock groupIds) { IntVector groupIdsVector = groupIds.asVector(); if (groupIdsVector != null) { add(positionOffset, groupIdsVector); } else { startAggEndHash(); for ( GroupingAggregator Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } } @Override public void add(int positionOffset, IntVector groupIds) { startAggEndHash(); for ( GroupingAggregator Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } private void startAggEndHash() { aggStart = System.nanoTime(); hashNanos += aggStart - hashStart; } private void end() { hashStart = System.nanoTime(); aggregationNanos += hashStart - aggStart; } @Override public void close() { Releasables.closeExpectNoException(prepared); } } try (AddInput add = new AddInput()) { checkState(needsInput(), "Operator is already finishing"); requireNonNull(page, "page is null"); for (int i = 0; i < prepared.length; i++) { prepared[i] = aggregators.get(i).prepareProcessPage(blockHash, page); } blockHash.add(wrapPage(page), add); hashNanos += System.nanoTime() - add.hashStart; } } finally { page.releaseBlocks(); pagesProcessed++; rowsReceived += page.getPositionCount(); } } @Override public Page getOutput() { Page p = output; if (p != null) { rowsEmitted += p.getPositionCount(); } output = null; return p; } @Override public void finish() { if (finished) { return; } finished = true; Block[] blocks = null; IntVector selected = null; boolean success = false; try { selected = blockHash.nonEmpty(); Block[] keys = blockHash.getKeys(); int[] aggBlockCounts = aggregators.stream().mapToInt( GroupingAggregator ::evaluateBlockCount).toArray(); blocks = new Block[keys.length + Arrays.stream(aggBlockCounts).sum()]; System.arraycopy(keys, 0, blocks, 0, keys.length); int offset = keys.length; for (int i = 0; i < aggregators.size(); i++) { var aggregator = aggregators.get(i); aggregator.evaluate(blocks, offset, selected, driverContext); offset += aggBlockCounts[i]; } output = new Page(blocks); success = true; } finally { // selected should always be closed if (selected != null) { selected.close(); } if (success == false && blocks != null) { Releasables.closeExpectNoException(blocks); } } } @Override public boolean isFinished() { return finished && output == null; } @Override public void close() { if (output !=
|
java
|
if (success == false) { close(); } } } @Override public boolean needsInput() { return finished == false; } @Override public void addInput(Page page) { try { <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput[] prepared = new <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput[aggregators.size()]; class AddInput implements <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput { long hashStart = System.nanoTime(); long aggStart; @Override public void add(int positionOffset, IntBlock groupIds) { IntVector groupIdsVector = groupIds.asVector(); if (groupIdsVector != null) { add(positionOffset, groupIdsVector); } else { startAggEndHash(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } } @Override public void add(int positionOffset, IntVector groupIds) { startAggEndHash(); for ( <mask> <mask> <mask> <mask> <mask> <mask> <mask> Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } private void startAggEndHash() { aggStart = System.nanoTime(); hashNanos += aggStart - hashStart; } private void end() { hashStart = System.nanoTime(); aggregationNanos += hashStart - aggStart; } @Override public void close() { Releasables.closeExpectNoException(prepared); } } try (AddInput add = new AddInput()) { checkState(needsInput(), "Operator is already finishing"); requireNonNull(page, "page is null"); for (int i = 0; i < prepared.length; i++) { prepared[i] = aggregators.get(i).prepareProcessPage(blockHash, page); } blockHash.add(wrapPage(page), add); hashNanos += System.nanoTime() - add.hashStart; } } finally { page.releaseBlocks(); pagesProcessed++; rowsReceived += page.getPositionCount(); } } @Override public Page getOutput() { Page p = output; if (p != null) { rowsEmitted += p.getPositionCount(); } output = null; return p; } @Override public void finish() { if (finished) { return; } finished = true; Block[] blocks = null; IntVector selected = null; boolean success = false; try { selected = blockHash.nonEmpty(); Block[] keys = blockHash.getKeys(); int[] aggBlockCounts = aggregators.stream().mapToInt( <mask> <mask> <mask> <mask> <mask> <mask> <mask> ::evaluateBlockCount).toArray(); blocks = new Block[keys.length + Arrays.stream(aggBlockCounts).sum()]; System.arraycopy(keys, 0, blocks, 0, keys.length); int offset = keys.length; for (int i = 0; i < aggregators.size(); i++) { var aggregator = aggregators.get(i); aggregator.evaluate(blocks, offset, selected, driverContext); offset += aggBlockCounts[i]; } output = new Page(blocks); success = true; } finally { // selected should always be closed if (selected != null) { selected.close(); } if (success == false && blocks != null) { Releasables.closeExpectNoException(blocks); } } } @Override public boolean isFinished() { return finished && output == null; } @Override public void close() { if (output != null) { output.releaseBlocks(); } Releasables.close(blockHash, () -> Releasables.close(aggregators)); } @Override public Operator.Status status() { return new Status(hashNanos, aggregationNanos, pagesProcessed, rowsReceived, rowsEmitted); } protected static void checkState(boolean condition, String msg) { if (condition == false) { throw new IllegalArgumentException(msg); } } protected Page wrapPage(Page page) { return page; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.getClass().getSimpleName()).append("["); sb.append("blockHash=").append(blockHash).append(", "); sb.append("aggregators=").append(aggregators); sb.append("]"); return sb.toString(); } public static class Status implements Operator.Status { public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry( Operator.Status.class, "hashagg", Status::new ); /** * Nanoseconds this operator has spent hashing grouping keys. */ private final long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private final long aggregationNanos; /** * Count of pages this operator has processed. */ private final int pagesProcessed; /** * Count of rows this operator has received. */ private final long rowsReceived; /** * Count of rows this operator has emitted. */ private final long
|
if (success == false) { close(); } } } @Override public boolean needsInput() { return finished == false; } @Override public void addInput(Page page) { try { GroupingAggregator Function.AddInput[] prepared = new GroupingAggregator Function.AddInput[aggregators.size()]; class AddInput implements GroupingAggregator Function.AddInput { long hashStart = System.nanoTime(); long aggStart; @Override public void add(int positionOffset, IntBlock groupIds) { IntVector groupIdsVector = groupIds.asVector(); if (groupIdsVector != null) { add(positionOffset, groupIdsVector); } else { startAggEndHash(); for ( GroupingAggregator Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } } @Override public void add(int positionOffset, IntVector groupIds) { startAggEndHash(); for ( GroupingAggregator Function.AddInput p : prepared) { p.add(positionOffset, groupIds); } end(); } private void startAggEndHash() { aggStart = System.nanoTime(); hashNanos += aggStart - hashStart; } private void end() { hashStart = System.nanoTime(); aggregationNanos += hashStart - aggStart; } @Override public void close() { Releasables.closeExpectNoException(prepared); } } try (AddInput add = new AddInput()) { checkState(needsInput(), "Operator is already finishing"); requireNonNull(page, "page is null"); for (int i = 0; i < prepared.length; i++) { prepared[i] = aggregators.get(i).prepareProcessPage(blockHash, page); } blockHash.add(wrapPage(page), add); hashNanos += System.nanoTime() - add.hashStart; } } finally { page.releaseBlocks(); pagesProcessed++; rowsReceived += page.getPositionCount(); } } @Override public Page getOutput() { Page p = output; if (p != null) { rowsEmitted += p.getPositionCount(); } output = null; return p; } @Override public void finish() { if (finished) { return; } finished = true; Block[] blocks = null; IntVector selected = null; boolean success = false; try { selected = blockHash.nonEmpty(); Block[] keys = blockHash.getKeys(); int[] aggBlockCounts = aggregators.stream().mapToInt( GroupingAggregator ::evaluateBlockCount).toArray(); blocks = new Block[keys.length + Arrays.stream(aggBlockCounts).sum()]; System.arraycopy(keys, 0, blocks, 0, keys.length); int offset = keys.length; for (int i = 0; i < aggregators.size(); i++) { var aggregator = aggregators.get(i); aggregator.evaluate(blocks, offset, selected, driverContext); offset += aggBlockCounts[i]; } output = new Page(blocks); success = true; } finally { // selected should always be closed if (selected != null) { selected.close(); } if (success == false && blocks != null) { Releasables.closeExpectNoException(blocks); } } } @Override public boolean isFinished() { return finished && output == null; } @Override public void close() { if (output != null) { output.releaseBlocks(); } Releasables.close(blockHash, () -> Releasables.close(aggregators)); } @Override public Operator.Status status() { return new Status(hashNanos, aggregationNanos, pagesProcessed, rowsReceived, rowsEmitted); } protected static void checkState(boolean condition, String msg) { if (condition == false) { throw new IllegalArgumentException(msg); } } protected Page wrapPage(Page page) { return page; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.getClass().getSimpleName()).append("["); sb.append("blockHash=").append(blockHash).append(", "); sb.append("aggregators=").append(aggregators); sb.append("]"); return sb.toString(); } public static class Status implements Operator.Status { public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry( Operator.Status.class, "hashagg", Status::new ); /** * Nanoseconds this operator has spent hashing grouping keys. */ private final long hashNanos; /** * Nanoseconds this operator has spent running the aggregations. */ private final long aggregationNanos; /** * Count of pages this operator has processed. */ private final int pagesProcessed; /** * Count of rows this operator has received. */ private final long rowsReceived; /** * Count of rows this operator has emitted. */ private final long
|
java
|
Protobuf type {@code DoRoguelikeDungeonCardGachaReq} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:DoRoguelikeDungeonCardGachaReq) emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReqOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.internal_static_DoRoguelikeDungeonCardGachaReq_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.internal_static_DoRoguelikeDungeonCardGachaReq_fieldAccessorTable .ensureFieldAccessorsInitialized( emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq.class, emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq.Builder.class); } // Construct using emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); dungeonId_ = 0; cellId_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.internal_static_DoRoguelikeDungeonCardGachaReq_descriptor; } @java.lang.Override public emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq getDefaultInstanceForType() { return emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq.getDefaultInstance(); } @java.lang.Override public emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq build() { emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq buildPartial() { emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq result = new emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq(this); result.dungeonId_ = dungeonId_; result.cellId_ = cellId_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq) { return mergeFrom((emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq other) { if (other == emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq.getDefaultInstance()) return this; if (other.getDungeonId() != 0) { setDungeonId(other.getDungeonId()); } if (other.getCellId() != 0) { setCellId(other.getCellId()); } this. <mask> <mask> <mask> <mask> <mask> <mask> <mask> (other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int dungeonId_ ; /** * <code>uint32 dungeon_id = 14;</code> * @return The dungeonId. */ @java.lang.Override public int getDungeonId() { return dungeonId_; } /** * <code>uint32 dungeon_id = 14;</code> * @param value The dungeonId to set. * @return This builder for chaining. */ public Builder setDungeonId(int value) { dungeonId_ = value; onChanged(); return this; } /** * <code>uint32 dungeon_id = 14;</code> * @return This builder for chaining. */ public Builder clearDungeonId() { dungeonId_ = 0; onChanged(); return this; } private int cellId_ ; /** * <code>uint32 cell_id = 3;</code> * @return The cellId. */ @java.lang.Override public int getCellId() { return cellId_; } /** * <code>uint32 cell_id = 3;</code> * @param value The cellId to set. * @return This builder for chaining. */ public Builder setCellId(int value) { cellId_ = value; onChanged(); return this; } /** * <code>uint32 cell_id = 3;</code> * @return This builder for chaining. */ public Builder clearCellId() { cellId_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder <mask> <mask> <mask> <mask> <mask> <mask> <mask> ( final com.google.protobuf.UnknownFieldSet unknownFields) { return super. <mask> <mask> <mask> <mask> <mask> <mask> <mask> (unknownFields); } // @@protoc_insertion_point(builder_scope:DoRoguelikeDungeonCardGachaReq) } // @@protoc_insertion_point(class_scope:DoRoguelikeDungeonCardGachaReq)
|
Protobuf type {@code DoRoguelikeDungeonCardGachaReq} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:DoRoguelikeDungeonCardGachaReq) emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReqOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.internal_static_DoRoguelikeDungeonCardGachaReq_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.internal_static_DoRoguelikeDungeonCardGachaReq_fieldAccessorTable .ensureFieldAccessorsInitialized( emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq.class, emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq.Builder.class); } // Construct using emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); dungeonId_ = 0; cellId_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.internal_static_DoRoguelikeDungeonCardGachaReq_descriptor; } @java.lang.Override public emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq getDefaultInstanceForType() { return emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq.getDefaultInstance(); } @java.lang.Override public emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq build() { emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq buildPartial() { emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq result = new emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq(this); result.dungeonId_ = dungeonId_; result.cellId_ = cellId_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq) { return mergeFrom((emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq other) { if (other == emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq.getDefaultInstance()) return this; if (other.getDungeonId() != 0) { setDungeonId(other.getDungeonId()); } if (other.getCellId() != 0) { setCellId(other.getCellId()); } this. mergeUnknownFields (other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int dungeonId_ ; /** * <code>uint32 dungeon_id = 14;</code> * @return The dungeonId. */ @java.lang.Override public int getDungeonId() { return dungeonId_; } /** * <code>uint32 dungeon_id = 14;</code> * @param value The dungeonId to set. * @return This builder for chaining. */ public Builder setDungeonId(int value) { dungeonId_ = value; onChanged(); return this; } /** * <code>uint32 dungeon_id = 14;</code> * @return This builder for chaining. */ public Builder clearDungeonId() { dungeonId_ = 0; onChanged(); return this; } private int cellId_ ; /** * <code>uint32 cell_id = 3;</code> * @return The cellId. */ @java.lang.Override public int getCellId() { return cellId_; } /** * <code>uint32 cell_id = 3;</code> * @param value The cellId to set. * @return This builder for chaining. */ public Builder setCellId(int value) { cellId_ = value; onChanged(); return this; } /** * <code>uint32 cell_id = 3;</code> * @return This builder for chaining. */ public Builder clearCellId() { cellId_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields ( final com.google.protobuf.UnknownFieldSet unknownFields) { return super. mergeUnknownFields (unknownFields); } // @@protoc_insertion_point(builder_scope:DoRoguelikeDungeonCardGachaReq) } // @@protoc_insertion_point(class_scope:DoRoguelikeDungeonCardGachaReq)
|
java
|
if (other.getDungeonId() != 0) { setDungeonId(other.getDungeonId()); } if (other.getCellId() != 0) { setCellId(other.getCellId()); } this. <mask> <mask> <mask> <mask> <mask> <mask> <mask> (other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int dungeonId_ ; /** * <code>uint32 dungeon_id = 14;</code> * @return The dungeonId. */ @java.lang.Override public int getDungeonId() { return dungeonId_; } /** * <code>uint32 dungeon_id = 14;</code> * @param value The dungeonId to set. * @return This builder for chaining. */ public Builder setDungeonId(int value) { dungeonId_ = value; onChanged(); return this; } /** * <code>uint32 dungeon_id = 14;</code> * @return This builder for chaining. */ public Builder clearDungeonId() { dungeonId_ = 0; onChanged(); return this; } private int cellId_ ; /** * <code>uint32 cell_id = 3;</code> * @return The cellId. */ @java.lang.Override public int getCellId() { return cellId_; } /** * <code>uint32 cell_id = 3;</code> * @param value The cellId to set. * @return This builder for chaining. */ public Builder setCellId(int value) { cellId_ = value; onChanged(); return this; } /** * <code>uint32 cell_id = 3;</code> * @return This builder for chaining. */ public Builder clearCellId() { cellId_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder <mask> <mask> <mask> <mask> <mask> <mask> <mask> ( final com.google.protobuf.UnknownFieldSet unknownFields) { return super. <mask> <mask> <mask> <mask> <mask> <mask> <mask> (unknownFields); } // @@protoc_insertion_point(builder_scope:DoRoguelikeDungeonCardGachaReq) } // @@protoc_insertion_point(class_scope:DoRoguelikeDungeonCardGachaReq) private static final emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq(); } public static emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<DoRoguelikeDungeonCardGachaReq> PARSER = new com.google.protobuf.AbstractParser<DoRoguelikeDungeonCardGachaReq>() { @java.lang.Override public DoRoguelikeDungeonCardGachaReq parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new DoRoguelikeDungeonCardGachaReq(input, extensionRegistry); } }; public static com.google.protobuf.Parser<DoRoguelikeDungeonCardGachaReq> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<DoRoguelikeDungeonCardGachaReq> getParserForType() { return PARSER; } @java.lang.Override public emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_DoRoguelikeDungeonCardGachaReq_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_DoRoguelikeDungeonCardGachaReq_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n$DoRoguelikeDungeonCardGachaReq.proto\"E" + "\n\036DoRoguelikeDungeonCardGachaReq\022\022\n\ndung" + "eon_id\030\016 \001(\r\022\017\n\007cell_id\030\003 \001(\rB\033\n\031emu.gra" + "sscutter.net.protob\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }); internal_static_DoRoguelikeDungeonCardGachaReq_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_DoRoguelikeDungeonCardGachaReq_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_DoRoguelikeDungeonCardGachaReq_descriptor, new java.lang.String[] { "DungeonId", "CellId", }); } // @@protoc_insertion_point(outer_class_scope) }
|
if (other.getDungeonId() != 0) { setDungeonId(other.getDungeonId()); } if (other.getCellId() != 0) { setCellId(other.getCellId()); } this. mergeUnknownFields (other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int dungeonId_ ; /** * <code>uint32 dungeon_id = 14;</code> * @return The dungeonId. */ @java.lang.Override public int getDungeonId() { return dungeonId_; } /** * <code>uint32 dungeon_id = 14;</code> * @param value The dungeonId to set. * @return This builder for chaining. */ public Builder setDungeonId(int value) { dungeonId_ = value; onChanged(); return this; } /** * <code>uint32 dungeon_id = 14;</code> * @return This builder for chaining. */ public Builder clearDungeonId() { dungeonId_ = 0; onChanged(); return this; } private int cellId_ ; /** * <code>uint32 cell_id = 3;</code> * @return The cellId. */ @java.lang.Override public int getCellId() { return cellId_; } /** * <code>uint32 cell_id = 3;</code> * @param value The cellId to set. * @return This builder for chaining. */ public Builder setCellId(int value) { cellId_ = value; onChanged(); return this; } /** * <code>uint32 cell_id = 3;</code> * @return This builder for chaining. */ public Builder clearCellId() { cellId_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields ( final com.google.protobuf.UnknownFieldSet unknownFields) { return super. mergeUnknownFields (unknownFields); } // @@protoc_insertion_point(builder_scope:DoRoguelikeDungeonCardGachaReq) } // @@protoc_insertion_point(class_scope:DoRoguelikeDungeonCardGachaReq) private static final emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq(); } public static emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<DoRoguelikeDungeonCardGachaReq> PARSER = new com.google.protobuf.AbstractParser<DoRoguelikeDungeonCardGachaReq>() { @java.lang.Override public DoRoguelikeDungeonCardGachaReq parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new DoRoguelikeDungeonCardGachaReq(input, extensionRegistry); } }; public static com.google.protobuf.Parser<DoRoguelikeDungeonCardGachaReq> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<DoRoguelikeDungeonCardGachaReq> getParserForType() { return PARSER; } @java.lang.Override public emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_DoRoguelikeDungeonCardGachaReq_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_DoRoguelikeDungeonCardGachaReq_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n$DoRoguelikeDungeonCardGachaReq.proto\"E" + "\n\036DoRoguelikeDungeonCardGachaReq\022\022\n\ndung" + "eon_id\030\016 \001(\r\022\017\n\007cell_id\030\003 \001(\rB\033\n\031emu.gra" + "sscutter.net.protob\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }); internal_static_DoRoguelikeDungeonCardGachaReq_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_DoRoguelikeDungeonCardGachaReq_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_DoRoguelikeDungeonCardGachaReq_descriptor, new java.lang.String[] { "DungeonId", "CellId", }); } // @@protoc_insertion_point(outer_class_scope) }
|
java
|
(other.getCellId() != 0) { setCellId(other.getCellId()); } this. <mask> <mask> <mask> <mask> <mask> <mask> <mask> (other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int dungeonId_ ; /** * <code>uint32 dungeon_id = 14;</code> * @return The dungeonId. */ @java.lang.Override public int getDungeonId() { return dungeonId_; } /** * <code>uint32 dungeon_id = 14;</code> * @param value The dungeonId to set. * @return This builder for chaining. */ public Builder setDungeonId(int value) { dungeonId_ = value; onChanged(); return this; } /** * <code>uint32 dungeon_id = 14;</code> * @return This builder for chaining. */ public Builder clearDungeonId() { dungeonId_ = 0; onChanged(); return this; } private int cellId_ ; /** * <code>uint32 cell_id = 3;</code> * @return The cellId. */ @java.lang.Override public int getCellId() { return cellId_; } /** * <code>uint32 cell_id = 3;</code> * @param value The cellId to set. * @return This builder for chaining. */ public Builder setCellId(int value) { cellId_ = value; onChanged(); return this; } /** * <code>uint32 cell_id = 3;</code> * @return This builder for chaining. */ public Builder clearCellId() { cellId_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder <mask> <mask> <mask> <mask> <mask> <mask> <mask> ( final com.google.protobuf.UnknownFieldSet unknownFields) { return super. <mask> <mask> <mask> <mask> <mask> <mask> <mask> (unknownFields); } // @@protoc_insertion_point(builder_scope:DoRoguelikeDungeonCardGachaReq) } // @@protoc_insertion_point(class_scope:DoRoguelikeDungeonCardGachaReq) private static final emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq(); } public static emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<DoRoguelikeDungeonCardGachaReq> PARSER = new com.google.protobuf.AbstractParser<DoRoguelikeDungeonCardGachaReq>() { @java.lang.Override public DoRoguelikeDungeonCardGachaReq parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new DoRoguelikeDungeonCardGachaReq(input, extensionRegistry); } }; public static com.google.protobuf.Parser<DoRoguelikeDungeonCardGachaReq> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<DoRoguelikeDungeonCardGachaReq> getParserForType() { return PARSER; } @java.lang.Override public emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_DoRoguelikeDungeonCardGachaReq_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_DoRoguelikeDungeonCardGachaReq_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n$DoRoguelikeDungeonCardGachaReq.proto\"E" + "\n\036DoRoguelikeDungeonCardGachaReq\022\022\n\ndung" + "eon_id\030\016 \001(\r\022\017\n\007cell_id\030\003 \001(\rB\033\n\031emu.gra" + "sscutter.net.protob\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }); internal_static_DoRoguelikeDungeonCardGachaReq_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_DoRoguelikeDungeonCardGachaReq_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_DoRoguelikeDungeonCardGachaReq_descriptor, new java.lang.String[] { "DungeonId", "CellId", }); } // @@protoc_insertion_point(outer_class_scope) }
|
(other.getCellId() != 0) { setCellId(other.getCellId()); } this. mergeUnknownFields (other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int dungeonId_ ; /** * <code>uint32 dungeon_id = 14;</code> * @return The dungeonId. */ @java.lang.Override public int getDungeonId() { return dungeonId_; } /** * <code>uint32 dungeon_id = 14;</code> * @param value The dungeonId to set. * @return This builder for chaining. */ public Builder setDungeonId(int value) { dungeonId_ = value; onChanged(); return this; } /** * <code>uint32 dungeon_id = 14;</code> * @return This builder for chaining. */ public Builder clearDungeonId() { dungeonId_ = 0; onChanged(); return this; } private int cellId_ ; /** * <code>uint32 cell_id = 3;</code> * @return The cellId. */ @java.lang.Override public int getCellId() { return cellId_; } /** * <code>uint32 cell_id = 3;</code> * @param value The cellId to set. * @return This builder for chaining. */ public Builder setCellId(int value) { cellId_ = value; onChanged(); return this; } /** * <code>uint32 cell_id = 3;</code> * @return This builder for chaining. */ public Builder clearCellId() { cellId_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields ( final com.google.protobuf.UnknownFieldSet unknownFields) { return super. mergeUnknownFields (unknownFields); } // @@protoc_insertion_point(builder_scope:DoRoguelikeDungeonCardGachaReq) } // @@protoc_insertion_point(class_scope:DoRoguelikeDungeonCardGachaReq) private static final emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq(); } public static emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<DoRoguelikeDungeonCardGachaReq> PARSER = new com.google.protobuf.AbstractParser<DoRoguelikeDungeonCardGachaReq>() { @java.lang.Override public DoRoguelikeDungeonCardGachaReq parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new DoRoguelikeDungeonCardGachaReq(input, extensionRegistry); } }; public static com.google.protobuf.Parser<DoRoguelikeDungeonCardGachaReq> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<DoRoguelikeDungeonCardGachaReq> getParserForType() { return PARSER; } @java.lang.Override public emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_DoRoguelikeDungeonCardGachaReq_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_DoRoguelikeDungeonCardGachaReq_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n$DoRoguelikeDungeonCardGachaReq.proto\"E" + "\n\036DoRoguelikeDungeonCardGachaReq\022\022\n\ndung" + "eon_id\030\016 \001(\r\022\017\n\007cell_id\030\003 \001(\rB\033\n\031emu.gra" + "sscutter.net.protob\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }); internal_static_DoRoguelikeDungeonCardGachaReq_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_DoRoguelikeDungeonCardGachaReq_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_DoRoguelikeDungeonCardGachaReq_descriptor, new java.lang.String[] { "DungeonId", "CellId", }); } // @@protoc_insertion_point(outer_class_scope) }
|
java
|
package ai.chat2db.server.test.domain.data.service; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.alibaba.fastjson2.JSON; import ai.chat2db.server.domain.api.param.ConsoleConnectParam; import ai.chat2db.server.domain.api.param.DlExecuteParam; import ai.chat2db.server.domain.api.param.DropParam; import ai.chat2db.server.domain.api.param.ShowCreateTableParam; import ai.chat2db.server.domain.api.param.TablePageQueryParam; import ai.chat2db.server.domain.api.param.TableQueryParam; import ai.chat2db.server.domain.api.param.TableSelector; import ai.chat2db.server.domain.api.param.datasource.DataSourcePreConnectParam; import ai.chat2db.server.domain.api.service.ConsoleService; import ai.chat2db.server.domain.api.service.DataSourceService; import ai.chat2db.server.domain.api.service.DlTemplateService; import ai.chat2db.server.domain.api.service.TableService; import ai.chat2db.server.test.common.BaseTest; import ai.chat2db.server.test.domain.data.service.dialect.DialectProperties; import ai.chat2db.server.test.domain.data.utils.TestUtils; import ai.chat2db.server.tools.base.wrapper.result.DataResult; import ai.chat2db.server.tools.common.util.EasyCollectionUtils; import ai.chat2db.spi.enums.CollationEnum; import ai.chat2db.spi.enums.IndexTypeEnum; import ai.chat2db.spi.model.Sql; import ai.chat2db.spi.model.Table; import ai.chat2db.spi.model.TableColumn; import ai.chat2db.spi.model.TableIndex; import ai.chat2db.spi.model.TableIndexColumn; import com.google.common.collect.Lists; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; /** * Data source testing * * @author Jiaju Zhuang */ @Slf4j public class TableOperationsTest extends BaseTest { /** * Table Name */ public static final String TABLE_NAME = "data_ops_table_test_" + System.currentTimeMillis(); @Resource private DataSourceService dataSourceService; @Resource private ConsoleService consoleService; @Autowired private List<DialectProperties> dialectPropertiesList; @Resource private DlTemplateService dlTemplateService; @Resource private TableService tableService; //@Resource //private SqlOperations sqlOperations; @Test @Order(1) public void table() { for (DialectProperties dialectProperties : dialectPropertiesList) { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); // Prepare context putConnect(dialectProperties.getUrl(), dialectProperties.getUsername(), dialectProperties.getPassword(), dialectProperties.getDbType(), dialectProperties.getDatabaseName(), dataSourceId, consoleId); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId); consoleCreateParam.setConsoleId(consoleId); consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName()); consoleService.createConsole(consoleCreateParam); // Create table structure DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(dialectProperties.getCrateTableSql(TABLE_NAME)); dlTemplateService.execute(templateQueryParam); // Query table creation statement ShowCreateTableParam showCreateTableParam = ShowCreateTableParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); if (dialectProperties.getDbType() == "POSTGRESQL") { showCreateTableParam.setSchemaName("public"); } DataResult<String> createTable = tableService.showCreateTable(showCreateTableParam); log.info("Table creation statement: {}", createTable.getData()); if (dialectProperties.getDbType() != "H2") { Assertions.assertTrue(createTable.getData().contains(dialectProperties.toCase(TABLE_NAME)), "Query table structure failed"); } // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(TABLE_NAME)); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure
|
package ai.chat2db.server.test.domain.data.service; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.alibaba.fastjson2.JSON; import ai.chat2db.server.domain.api.param.ConsoleConnectParam; import ai.chat2db.server.domain.api.param.DlExecuteParam; import ai.chat2db.server.domain.api.param.DropParam; import ai.chat2db.server.domain.api.param.ShowCreateTableParam; import ai.chat2db.server.domain.api.param.TablePageQueryParam; import ai.chat2db.server.domain.api.param.TableQueryParam; import ai.chat2db.server.domain.api.param.TableSelector; import ai.chat2db.server.domain.api.param.datasource.DataSourcePreConnectParam; import ai.chat2db.server.domain.api.service.ConsoleService; import ai.chat2db.server.domain.api.service.DataSourceService; import ai.chat2db.server.domain.api.service.DlTemplateService; import ai.chat2db.server.domain.api.service.TableService; import ai.chat2db.server.test.common.BaseTest; import ai.chat2db.server.test.domain.data.service.dialect.DialectProperties; import ai.chat2db.server.test.domain.data.utils.TestUtils; import ai.chat2db.server.tools.base.wrapper.result.DataResult; import ai.chat2db.server.tools.common.util.EasyCollectionUtils; import ai.chat2db.spi.enums.CollationEnum; import ai.chat2db.spi.enums.IndexTypeEnum; import ai.chat2db.spi.model.Sql; import ai.chat2db.spi.model.Table; import ai.chat2db.spi.model.TableColumn; import ai.chat2db.spi.model.TableIndex; import ai.chat2db.spi.model.TableIndexColumn; import com.google.common.collect.Lists; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; /** * Data source testing * * @author Jiaju Zhuang */ @Slf4j public class TableOperationsTest extends BaseTest { /** * Table Name */ public static final String TABLE_NAME = "data_ops_table_test_" + System.currentTimeMillis(); @Resource private DataSourceService dataSourceService; @Resource private ConsoleService consoleService; @Autowired private List<DialectProperties> dialectPropertiesList; @Resource private DlTemplateService dlTemplateService; @Resource private TableService tableService; //@Resource //private SqlOperations sqlOperations; @Test @Order(1) public void table() { for (DialectProperties dialectProperties : dialectPropertiesList) { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); // Prepare context putConnect(dialectProperties.getUrl(), dialectProperties.getUsername(), dialectProperties.getPassword(), dialectProperties.getDbType(), dialectProperties.getDatabaseName(), dataSourceId, consoleId); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId); consoleCreateParam.setConsoleId(consoleId); consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName()); consoleService.createConsole(consoleCreateParam); // Create table structure DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(dialectProperties.getCrateTableSql(TABLE_NAME)); dlTemplateService.execute(templateQueryParam); // Query table creation statement ShowCreateTableParam showCreateTableParam = ShowCreateTableParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); if (dialectProperties.getDbType() == "POSTGRESQL") { showCreateTableParam.setSchemaName("public"); } DataResult<String> createTable = tableService.showCreateTable(showCreateTableParam); log.info("Table creation statement: {}", createTable.getData()); if (dialectProperties.getDbType() != "H2") { Assertions.assertTrue(createTable.getData().contains(dialectProperties.toCase(TABLE_NAME)), "Query table structure failed"); } // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(TABLE_NAME)); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure
|
java
|
package ai.chat2db.server.test.domain.data.service; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.alibaba.fastjson2.JSON; import ai.chat2db.server.domain.api.param.ConsoleConnectParam; import ai.chat2db.server.domain.api.param.DlExecuteParam; import ai.chat2db.server.domain.api.param.DropParam; import ai.chat2db.server.domain.api.param.ShowCreateTableParam; import ai.chat2db.server.domain.api.param.TablePageQueryParam; import ai.chat2db.server.domain.api.param.TableQueryParam; import ai.chat2db.server.domain.api.param.TableSelector; import ai.chat2db.server.domain.api.param.datasource.DataSourcePreConnectParam; import ai.chat2db.server.domain.api.service.ConsoleService; import ai.chat2db.server.domain.api.service.DataSourceService; import ai.chat2db.server.domain.api.service.DlTemplateService; import ai.chat2db.server.domain.api.service.TableService; import ai.chat2db.server.test.common.BaseTest; import ai.chat2db.server.test.domain.data.service.dialect.DialectProperties; import ai.chat2db.server.test.domain.data.utils.TestUtils; import ai.chat2db.server.tools.base.wrapper.result.DataResult; import ai.chat2db.server.tools.common.util.EasyCollectionUtils; import ai.chat2db.spi.enums.CollationEnum; import ai.chat2db.spi.enums.IndexTypeEnum; import ai.chat2db.spi.model.Sql; import ai.chat2db.spi.model.Table; import ai.chat2db.spi.model.TableColumn; import ai.chat2db.spi.model.TableIndex; import ai.chat2db.spi.model.TableIndexColumn; import com.google.common.collect.Lists; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; /** * Data source testing * * @author Jiaju Zhuang */ @Slf4j public class TableOperationsTest extends BaseTest { /** * Table Name */ public static final String TABLE_NAME = "data_ops_table_test_" + System.currentTimeMillis(); @Resource private DataSourceService dataSourceService; @Resource private ConsoleService consoleService; @Autowired private List<DialectProperties> dialectPropertiesList; @Resource private DlTemplateService dlTemplateService; @Resource private TableService tableService; //@Resource //private SqlOperations sqlOperations; @Test @Order(1) public void table() { for (DialectProperties dialectProperties : dialectPropertiesList) { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); // Prepare context putConnect(dialectProperties.getUrl(), dialectProperties.getUsername(), dialectProperties.getPassword(), dialectProperties.getDbType(), dialectProperties.getDatabaseName(), dataSourceId, consoleId); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId); consoleCreateParam.setConsoleId(consoleId); consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName()); consoleService.createConsole(consoleCreateParam); // Create table structure DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(dialectProperties.getCrateTableSql(TABLE_NAME)); dlTemplateService.execute(templateQueryParam); // Query table creation statement ShowCreateTableParam showCreateTableParam = ShowCreateTableParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); if (dialectProperties.getDbType() == "POSTGRESQL") { showCreateTableParam.setSchemaName("public"); } DataResult<String> createTable = tableService.showCreateTable(showCreateTableParam); log.info("Table creation statement: {}", createTable.getData()); if (dialectProperties.getDbType() != "H2") { Assertions.assertTrue(createTable.getData().contains(dialectProperties.toCase(TABLE_NAME)), "Query table structure failed"); } // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(TABLE_NAME)); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam();
|
package ai.chat2db.server.test.domain.data.service; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.alibaba.fastjson2.JSON; import ai.chat2db.server.domain.api.param.ConsoleConnectParam; import ai.chat2db.server.domain.api.param.DlExecuteParam; import ai.chat2db.server.domain.api.param.DropParam; import ai.chat2db.server.domain.api.param.ShowCreateTableParam; import ai.chat2db.server.domain.api.param.TablePageQueryParam; import ai.chat2db.server.domain.api.param.TableQueryParam; import ai.chat2db.server.domain.api.param.TableSelector; import ai.chat2db.server.domain.api.param.datasource.DataSourcePreConnectParam; import ai.chat2db.server.domain.api.service.ConsoleService; import ai.chat2db.server.domain.api.service.DataSourceService; import ai.chat2db.server.domain.api.service.DlTemplateService; import ai.chat2db.server.domain.api.service.TableService; import ai.chat2db.server.test.common.BaseTest; import ai.chat2db.server.test.domain.data.service.dialect.DialectProperties; import ai.chat2db.server.test.domain.data.utils.TestUtils; import ai.chat2db.server.tools.base.wrapper.result.DataResult; import ai.chat2db.server.tools.common.util.EasyCollectionUtils; import ai.chat2db.spi.enums.CollationEnum; import ai.chat2db.spi.enums.IndexTypeEnum; import ai.chat2db.spi.model.Sql; import ai.chat2db.spi.model.Table; import ai.chat2db.spi.model.TableColumn; import ai.chat2db.spi.model.TableIndex; import ai.chat2db.spi.model.TableIndexColumn; import com.google.common.collect.Lists; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; /** * Data source testing * * @author Jiaju Zhuang */ @Slf4j public class TableOperationsTest extends BaseTest { /** * Table Name */ public static final String TABLE_NAME = "data_ops_table_test_" + System.currentTimeMillis(); @Resource private DataSourceService dataSourceService; @Resource private ConsoleService consoleService; @Autowired private List<DialectProperties> dialectPropertiesList; @Resource private DlTemplateService dlTemplateService; @Resource private TableService tableService; //@Resource //private SqlOperations sqlOperations; @Test @Order(1) public void table() { for (DialectProperties dialectProperties : dialectPropertiesList) { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); // Prepare context putConnect(dialectProperties.getUrl(), dialectProperties.getUsername(), dialectProperties.getPassword(), dialectProperties.getDbType(), dialectProperties.getDatabaseName(), dataSourceId, consoleId); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId); consoleCreateParam.setConsoleId(consoleId); consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName()); consoleService.createConsole(consoleCreateParam); // Create table structure DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(dialectProperties.getCrateTableSql(TABLE_NAME)); dlTemplateService.execute(templateQueryParam); // Query table creation statement ShowCreateTableParam showCreateTableParam = ShowCreateTableParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); if (dialectProperties.getDbType() == "POSTGRESQL") { showCreateTableParam.setSchemaName("public"); } DataResult<String> createTable = tableService.showCreateTable(showCreateTableParam); log.info("Table creation statement: {}", createTable.getData()); if (dialectProperties.getDbType() != "H2") { Assertions.assertTrue(createTable.getData().contains(dialectProperties.toCase(TABLE_NAME)), "Query table structure failed"); } // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(TABLE_NAME)); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure tablePageQueryParam = new TablePageQueryParam();
|
java
|
package ai.chat2db.server.test.domain.data.service; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.alibaba.fastjson2.JSON; import ai.chat2db.server.domain.api.param.ConsoleConnectParam; import ai.chat2db.server.domain.api.param.DlExecuteParam; import ai.chat2db.server.domain.api.param.DropParam; import ai.chat2db.server.domain.api.param.ShowCreateTableParam; import ai.chat2db.server.domain.api.param.TablePageQueryParam; import ai.chat2db.server.domain.api.param.TableQueryParam; import ai.chat2db.server.domain.api.param.TableSelector; import ai.chat2db.server.domain.api.param.datasource.DataSourcePreConnectParam; import ai.chat2db.server.domain.api.service.ConsoleService; import ai.chat2db.server.domain.api.service.DataSourceService; import ai.chat2db.server.domain.api.service.DlTemplateService; import ai.chat2db.server.domain.api.service.TableService; import ai.chat2db.server.test.common.BaseTest; import ai.chat2db.server.test.domain.data.service.dialect.DialectProperties; import ai.chat2db.server.test.domain.data.utils.TestUtils; import ai.chat2db.server.tools.base.wrapper.result.DataResult; import ai.chat2db.server.tools.common.util.EasyCollectionUtils; import ai.chat2db.spi.enums.CollationEnum; import ai.chat2db.spi.enums.IndexTypeEnum; import ai.chat2db.spi.model.Sql; import ai.chat2db.spi.model.Table; import ai.chat2db.spi.model.TableColumn; import ai.chat2db.spi.model.TableIndex; import ai.chat2db.spi.model.TableIndexColumn; import com.google.common.collect.Lists; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; /** * Data source testing * * @author Jiaju Zhuang */ @Slf4j public class TableOperationsTest extends BaseTest { /** * Table Name */ public static final String TABLE_NAME = "data_ops_table_test_" + System.currentTimeMillis(); @Resource private DataSourceService dataSourceService; @Resource private ConsoleService consoleService; @Autowired private List<DialectProperties> dialectPropertiesList; @Resource private DlTemplateService dlTemplateService; @Resource private TableService tableService; //@Resource //private SqlOperations sqlOperations; @Test @Order(1) public void table() { for (DialectProperties dialectProperties : dialectPropertiesList) { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); // Prepare context putConnect(dialectProperties.getUrl(), dialectProperties.getUsername(), dialectProperties.getPassword(), dialectProperties.getDbType(), dialectProperties.getDatabaseName(), dataSourceId, consoleId); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId); consoleCreateParam.setConsoleId(consoleId); consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName()); consoleService.createConsole(consoleCreateParam); // Create table structure DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(dialectProperties.getCrateTableSql(TABLE_NAME)); dlTemplateService.execute(templateQueryParam); // Query table creation statement ShowCreateTableParam showCreateTableParam = ShowCreateTableParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); if (dialectProperties.getDbType() == "POSTGRESQL") { showCreateTableParam.setSchemaName("public"); } DataResult<String> createTable = tableService.showCreateTable(showCreateTableParam); log.info("Table creation statement: {}", createTable.getData()); if (dialectProperties.getDbType() != "H2") { Assertions.assertTrue(createTable.getData().contains(dialectProperties.toCase(TABLE_NAME)), "Query table structure failed"); } // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(TABLE_NAME)); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId);
|
package ai.chat2db.server.test.domain.data.service; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.alibaba.fastjson2.JSON; import ai.chat2db.server.domain.api.param.ConsoleConnectParam; import ai.chat2db.server.domain.api.param.DlExecuteParam; import ai.chat2db.server.domain.api.param.DropParam; import ai.chat2db.server.domain.api.param.ShowCreateTableParam; import ai.chat2db.server.domain.api.param.TablePageQueryParam; import ai.chat2db.server.domain.api.param.TableQueryParam; import ai.chat2db.server.domain.api.param.TableSelector; import ai.chat2db.server.domain.api.param.datasource.DataSourcePreConnectParam; import ai.chat2db.server.domain.api.service.ConsoleService; import ai.chat2db.server.domain.api.service.DataSourceService; import ai.chat2db.server.domain.api.service.DlTemplateService; import ai.chat2db.server.domain.api.service.TableService; import ai.chat2db.server.test.common.BaseTest; import ai.chat2db.server.test.domain.data.service.dialect.DialectProperties; import ai.chat2db.server.test.domain.data.utils.TestUtils; import ai.chat2db.server.tools.base.wrapper.result.DataResult; import ai.chat2db.server.tools.common.util.EasyCollectionUtils; import ai.chat2db.spi.enums.CollationEnum; import ai.chat2db.spi.enums.IndexTypeEnum; import ai.chat2db.spi.model.Sql; import ai.chat2db.spi.model.Table; import ai.chat2db.spi.model.TableColumn; import ai.chat2db.spi.model.TableIndex; import ai.chat2db.spi.model.TableIndexColumn; import com.google.common.collect.Lists; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; /** * Data source testing * * @author Jiaju Zhuang */ @Slf4j public class TableOperationsTest extends BaseTest { /** * Table Name */ public static final String TABLE_NAME = "data_ops_table_test_" + System.currentTimeMillis(); @Resource private DataSourceService dataSourceService; @Resource private ConsoleService consoleService; @Autowired private List<DialectProperties> dialectPropertiesList; @Resource private DlTemplateService dlTemplateService; @Resource private TableService tableService; //@Resource //private SqlOperations sqlOperations; @Test @Order(1) public void table() { for (DialectProperties dialectProperties : dialectPropertiesList) { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); // Prepare context putConnect(dialectProperties.getUrl(), dialectProperties.getUsername(), dialectProperties.getPassword(), dialectProperties.getDbType(), dialectProperties.getDatabaseName(), dataSourceId, consoleId); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId); consoleCreateParam.setConsoleId(consoleId); consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName()); consoleService.createConsole(consoleCreateParam); // Create table structure DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(dialectProperties.getCrateTableSql(TABLE_NAME)); dlTemplateService.execute(templateQueryParam); // Query table creation statement ShowCreateTableParam showCreateTableParam = ShowCreateTableParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); if (dialectProperties.getDbType() == "POSTGRESQL") { showCreateTableParam.setSchemaName("public"); } DataResult<String> createTable = tableService.showCreateTable(showCreateTableParam); log.info("Table creation statement: {}", createTable.getData()); if (dialectProperties.getDbType() != "H2") { Assertions.assertTrue(createTable.getData().contains(dialectProperties.toCase(TABLE_NAME)), "Query table structure failed"); } // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(TABLE_NAME)); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId);
|
java
|
ai.chat2db.server.test.domain.data.service; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.alibaba.fastjson2.JSON; import ai.chat2db.server.domain.api.param.ConsoleConnectParam; import ai.chat2db.server.domain.api.param.DlExecuteParam; import ai.chat2db.server.domain.api.param.DropParam; import ai.chat2db.server.domain.api.param.ShowCreateTableParam; import ai.chat2db.server.domain.api.param.TablePageQueryParam; import ai.chat2db.server.domain.api.param.TableQueryParam; import ai.chat2db.server.domain.api.param.TableSelector; import ai.chat2db.server.domain.api.param.datasource.DataSourcePreConnectParam; import ai.chat2db.server.domain.api.service.ConsoleService; import ai.chat2db.server.domain.api.service.DataSourceService; import ai.chat2db.server.domain.api.service.DlTemplateService; import ai.chat2db.server.domain.api.service.TableService; import ai.chat2db.server.test.common.BaseTest; import ai.chat2db.server.test.domain.data.service.dialect.DialectProperties; import ai.chat2db.server.test.domain.data.utils.TestUtils; import ai.chat2db.server.tools.base.wrapper.result.DataResult; import ai.chat2db.server.tools.common.util.EasyCollectionUtils; import ai.chat2db.spi.enums.CollationEnum; import ai.chat2db.spi.enums.IndexTypeEnum; import ai.chat2db.spi.model.Sql; import ai.chat2db.spi.model.Table; import ai.chat2db.spi.model.TableColumn; import ai.chat2db.spi.model.TableIndex; import ai.chat2db.spi.model.TableIndexColumn; import com.google.common.collect.Lists; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; /** * Data source testing * * @author Jiaju Zhuang */ @Slf4j public class TableOperationsTest extends BaseTest { /** * Table Name */ public static final String TABLE_NAME = "data_ops_table_test_" + System.currentTimeMillis(); @Resource private DataSourceService dataSourceService; @Resource private ConsoleService consoleService; @Autowired private List<DialectProperties> dialectPropertiesList; @Resource private DlTemplateService dlTemplateService; @Resource private TableService tableService; //@Resource //private SqlOperations sqlOperations; @Test @Order(1) public void table() { for (DialectProperties dialectProperties : dialectPropertiesList) { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); // Prepare context putConnect(dialectProperties.getUrl(), dialectProperties.getUsername(), dialectProperties.getPassword(), dialectProperties.getDbType(), dialectProperties.getDatabaseName(), dataSourceId, consoleId); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId); consoleCreateParam.setConsoleId(consoleId); consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName()); consoleService.createConsole(consoleCreateParam); // Create table structure DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(dialectProperties.getCrateTableSql(TABLE_NAME)); dlTemplateService.execute(templateQueryParam); // Query table creation statement ShowCreateTableParam showCreateTableParam = ShowCreateTableParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); if (dialectProperties.getDbType() == "POSTGRESQL") { showCreateTableParam.setSchemaName("public"); } DataResult<String> createTable = tableService.showCreateTable(showCreateTableParam); log.info("Table creation statement: {}", createTable.getData()); if (dialectProperties.getDbType() != "H2") { Assertions.assertTrue(createTable.getData().contains(dialectProperties.toCase(TABLE_NAME)), "Query table structure failed"); } // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(TABLE_NAME)); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName());
|
ai.chat2db.server.test.domain.data.service; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.alibaba.fastjson2.JSON; import ai.chat2db.server.domain.api.param.ConsoleConnectParam; import ai.chat2db.server.domain.api.param.DlExecuteParam; import ai.chat2db.server.domain.api.param.DropParam; import ai.chat2db.server.domain.api.param.ShowCreateTableParam; import ai.chat2db.server.domain.api.param.TablePageQueryParam; import ai.chat2db.server.domain.api.param.TableQueryParam; import ai.chat2db.server.domain.api.param.TableSelector; import ai.chat2db.server.domain.api.param.datasource.DataSourcePreConnectParam; import ai.chat2db.server.domain.api.service.ConsoleService; import ai.chat2db.server.domain.api.service.DataSourceService; import ai.chat2db.server.domain.api.service.DlTemplateService; import ai.chat2db.server.domain.api.service.TableService; import ai.chat2db.server.test.common.BaseTest; import ai.chat2db.server.test.domain.data.service.dialect.DialectProperties; import ai.chat2db.server.test.domain.data.utils.TestUtils; import ai.chat2db.server.tools.base.wrapper.result.DataResult; import ai.chat2db.server.tools.common.util.EasyCollectionUtils; import ai.chat2db.spi.enums.CollationEnum; import ai.chat2db.spi.enums.IndexTypeEnum; import ai.chat2db.spi.model.Sql; import ai.chat2db.spi.model.Table; import ai.chat2db.spi.model.TableColumn; import ai.chat2db.spi.model.TableIndex; import ai.chat2db.spi.model.TableIndexColumn; import com.google.common.collect.Lists; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; /** * Data source testing * * @author Jiaju Zhuang */ @Slf4j public class TableOperationsTest extends BaseTest { /** * Table Name */ public static final String TABLE_NAME = "data_ops_table_test_" + System.currentTimeMillis(); @Resource private DataSourceService dataSourceService; @Resource private ConsoleService consoleService; @Autowired private List<DialectProperties> dialectPropertiesList; @Resource private DlTemplateService dlTemplateService; @Resource private TableService tableService; //@Resource //private SqlOperations sqlOperations; @Test @Order(1) public void table() { for (DialectProperties dialectProperties : dialectPropertiesList) { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); // Prepare context putConnect(dialectProperties.getUrl(), dialectProperties.getUsername(), dialectProperties.getPassword(), dialectProperties.getDbType(), dialectProperties.getDatabaseName(), dataSourceId, consoleId); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId); consoleCreateParam.setConsoleId(consoleId); consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName()); consoleService.createConsole(consoleCreateParam); // Create table structure DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(dialectProperties.getCrateTableSql(TABLE_NAME)); dlTemplateService.execute(templateQueryParam); // Query table creation statement ShowCreateTableParam showCreateTableParam = ShowCreateTableParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); if (dialectProperties.getDbType() == "POSTGRESQL") { showCreateTableParam.setSchemaName("public"); } DataResult<String> createTable = tableService.showCreateTable(showCreateTableParam); log.info("Table creation statement: {}", createTable.getData()); if (dialectProperties.getDbType() != "H2") { Assertions.assertTrue(createTable.getData().contains(dialectProperties.toCase(TABLE_NAME)), "Query table structure failed"); } // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(TABLE_NAME)); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName());
|
java
|
import com.alibaba.fastjson2.JSON; import ai.chat2db.server.domain.api.param.ConsoleConnectParam; import ai.chat2db.server.domain.api.param.DlExecuteParam; import ai.chat2db.server.domain.api.param.DropParam; import ai.chat2db.server.domain.api.param.ShowCreateTableParam; import ai.chat2db.server.domain.api.param.TablePageQueryParam; import ai.chat2db.server.domain.api.param.TableQueryParam; import ai.chat2db.server.domain.api.param.TableSelector; import ai.chat2db.server.domain.api.param.datasource.DataSourcePreConnectParam; import ai.chat2db.server.domain.api.service.ConsoleService; import ai.chat2db.server.domain.api.service.DataSourceService; import ai.chat2db.server.domain.api.service.DlTemplateService; import ai.chat2db.server.domain.api.service.TableService; import ai.chat2db.server.test.common.BaseTest; import ai.chat2db.server.test.domain.data.service.dialect.DialectProperties; import ai.chat2db.server.test.domain.data.utils.TestUtils; import ai.chat2db.server.tools.base.wrapper.result.DataResult; import ai.chat2db.server.tools.common.util.EasyCollectionUtils; import ai.chat2db.spi.enums.CollationEnum; import ai.chat2db.spi.enums.IndexTypeEnum; import ai.chat2db.spi.model.Sql; import ai.chat2db.spi.model.Table; import ai.chat2db.spi.model.TableColumn; import ai.chat2db.spi.model.TableIndex; import ai.chat2db.spi.model.TableIndexColumn; import com.google.common.collect.Lists; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; /** * Data source testing * * @author Jiaju Zhuang */ @Slf4j public class TableOperationsTest extends BaseTest { /** * Table Name */ public static final String TABLE_NAME = "data_ops_table_test_" + System.currentTimeMillis(); @Resource private DataSourceService dataSourceService; @Resource private ConsoleService consoleService; @Autowired private List<DialectProperties> dialectPropertiesList; @Resource private DlTemplateService dlTemplateService; @Resource private TableService tableService; //@Resource //private SqlOperations sqlOperations; @Test @Order(1) public void table() { for (DialectProperties dialectProperties : dialectPropertiesList) { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); // Prepare context putConnect(dialectProperties.getUrl(), dialectProperties.getUsername(), dialectProperties.getPassword(), dialectProperties.getDbType(), dialectProperties.getDatabaseName(), dataSourceId, consoleId); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId); consoleCreateParam.setConsoleId(consoleId); consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName()); consoleService.createConsole(consoleCreateParam); // Create table structure DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(dialectProperties.getCrateTableSql(TABLE_NAME)); dlTemplateService.execute(templateQueryParam); // Query table creation statement ShowCreateTableParam showCreateTableParam = ShowCreateTableParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); if (dialectProperties.getDbType() == "POSTGRESQL") { showCreateTableParam.setSchemaName("public"); } DataResult<String> createTable = tableService.showCreateTable(showCreateTableParam); log.info("Table creation statement: {}", createTable.getData()); if (dialectProperties.getDbType() != "H2") { Assertions.assertTrue(createTable.getData().contains(dialectProperties.toCase(TABLE_NAME)), "Query table structure failed"); } // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(TABLE_NAME)); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(TABLE_NAME)); tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> ,
|
import com.alibaba.fastjson2.JSON; import ai.chat2db.server.domain.api.param.ConsoleConnectParam; import ai.chat2db.server.domain.api.param.DlExecuteParam; import ai.chat2db.server.domain.api.param.DropParam; import ai.chat2db.server.domain.api.param.ShowCreateTableParam; import ai.chat2db.server.domain.api.param.TablePageQueryParam; import ai.chat2db.server.domain.api.param.TableQueryParam; import ai.chat2db.server.domain.api.param.TableSelector; import ai.chat2db.server.domain.api.param.datasource.DataSourcePreConnectParam; import ai.chat2db.server.domain.api.service.ConsoleService; import ai.chat2db.server.domain.api.service.DataSourceService; import ai.chat2db.server.domain.api.service.DlTemplateService; import ai.chat2db.server.domain.api.service.TableService; import ai.chat2db.server.test.common.BaseTest; import ai.chat2db.server.test.domain.data.service.dialect.DialectProperties; import ai.chat2db.server.test.domain.data.utils.TestUtils; import ai.chat2db.server.tools.base.wrapper.result.DataResult; import ai.chat2db.server.tools.common.util.EasyCollectionUtils; import ai.chat2db.spi.enums.CollationEnum; import ai.chat2db.spi.enums.IndexTypeEnum; import ai.chat2db.spi.model.Sql; import ai.chat2db.spi.model.Table; import ai.chat2db.spi.model.TableColumn; import ai.chat2db.spi.model.TableIndex; import ai.chat2db.spi.model.TableIndexColumn; import com.google.common.collect.Lists; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; /** * Data source testing * * @author Jiaju Zhuang */ @Slf4j public class TableOperationsTest extends BaseTest { /** * Table Name */ public static final String TABLE_NAME = "data_ops_table_test_" + System.currentTimeMillis(); @Resource private DataSourceService dataSourceService; @Resource private ConsoleService consoleService; @Autowired private List<DialectProperties> dialectPropertiesList; @Resource private DlTemplateService dlTemplateService; @Resource private TableService tableService; //@Resource //private SqlOperations sqlOperations; @Test @Order(1) public void table() { for (DialectProperties dialectProperties : dialectPropertiesList) { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); // Prepare context putConnect(dialectProperties.getUrl(), dialectProperties.getUsername(), dialectProperties.getPassword(), dialectProperties.getDbType(), dialectProperties.getDatabaseName(), dataSourceId, consoleId); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId); consoleCreateParam.setConsoleId(consoleId); consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName()); consoleService.createConsole(consoleCreateParam); // Create table structure DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(dialectProperties.getCrateTableSql(TABLE_NAME)); dlTemplateService.execute(templateQueryParam); // Query table creation statement ShowCreateTableParam showCreateTableParam = ShowCreateTableParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); if (dialectProperties.getDbType() == "POSTGRESQL") { showCreateTableParam.setSchemaName("public"); } DataResult<String> createTable = tableService.showCreateTable(showCreateTableParam); log.info("Table creation statement: {}", createTable.getData()); if (dialectProperties.getDbType() != "H2") { Assertions.assertTrue(createTable.getData().contains(dialectProperties.toCase(TABLE_NAME)), "Query table structure failed"); } // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(TABLE_NAME)); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(TABLE_NAME)); tableList = tableService.pageQuery( tablePageQueryParam ,
|
java
|
ai.chat2db.server.domain.api.param.DropParam; import ai.chat2db.server.domain.api.param.ShowCreateTableParam; import ai.chat2db.server.domain.api.param.TablePageQueryParam; import ai.chat2db.server.domain.api.param.TableQueryParam; import ai.chat2db.server.domain.api.param.TableSelector; import ai.chat2db.server.domain.api.param.datasource.DataSourcePreConnectParam; import ai.chat2db.server.domain.api.service.ConsoleService; import ai.chat2db.server.domain.api.service.DataSourceService; import ai.chat2db.server.domain.api.service.DlTemplateService; import ai.chat2db.server.domain.api.service.TableService; import ai.chat2db.server.test.common.BaseTest; import ai.chat2db.server.test.domain.data.service.dialect.DialectProperties; import ai.chat2db.server.test.domain.data.utils.TestUtils; import ai.chat2db.server.tools.base.wrapper.result.DataResult; import ai.chat2db.server.tools.common.util.EasyCollectionUtils; import ai.chat2db.spi.enums.CollationEnum; import ai.chat2db.spi.enums.IndexTypeEnum; import ai.chat2db.spi.model.Sql; import ai.chat2db.spi.model.Table; import ai.chat2db.spi.model.TableColumn; import ai.chat2db.spi.model.TableIndex; import ai.chat2db.spi.model.TableIndexColumn; import com.google.common.collect.Lists; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; /** * Data source testing * * @author Jiaju Zhuang */ @Slf4j public class TableOperationsTest extends BaseTest { /** * Table Name */ public static final String TABLE_NAME = "data_ops_table_test_" + System.currentTimeMillis(); @Resource private DataSourceService dataSourceService; @Resource private ConsoleService consoleService; @Autowired private List<DialectProperties> dialectPropertiesList; @Resource private DlTemplateService dlTemplateService; @Resource private TableService tableService; //@Resource //private SqlOperations sqlOperations; @Test @Order(1) public void table() { for (DialectProperties dialectProperties : dialectPropertiesList) { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); // Prepare context putConnect(dialectProperties.getUrl(), dialectProperties.getUsername(), dialectProperties.getPassword(), dialectProperties.getDbType(), dialectProperties.getDatabaseName(), dataSourceId, consoleId); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId); consoleCreateParam.setConsoleId(consoleId); consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName()); consoleService.createConsole(consoleCreateParam); // Create table structure DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(dialectProperties.getCrateTableSql(TABLE_NAME)); dlTemplateService.execute(templateQueryParam); // Query table creation statement ShowCreateTableParam showCreateTableParam = ShowCreateTableParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); if (dialectProperties.getDbType() == "POSTGRESQL") { showCreateTableParam.setSchemaName("public"); } DataResult<String> createTable = tableService.showCreateTable(showCreateTableParam); log.info("Table creation statement: {}", createTable.getData()); if (dialectProperties.getDbType() != "H2") { Assertions.assertTrue(createTable.getData().contains(dialectProperties.toCase(TABLE_NAME)), "Query table structure failed"); } // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(TABLE_NAME)); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(TABLE_NAME)); tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the
|
ai.chat2db.server.domain.api.param.DropParam; import ai.chat2db.server.domain.api.param.ShowCreateTableParam; import ai.chat2db.server.domain.api.param.TablePageQueryParam; import ai.chat2db.server.domain.api.param.TableQueryParam; import ai.chat2db.server.domain.api.param.TableSelector; import ai.chat2db.server.domain.api.param.datasource.DataSourcePreConnectParam; import ai.chat2db.server.domain.api.service.ConsoleService; import ai.chat2db.server.domain.api.service.DataSourceService; import ai.chat2db.server.domain.api.service.DlTemplateService; import ai.chat2db.server.domain.api.service.TableService; import ai.chat2db.server.test.common.BaseTest; import ai.chat2db.server.test.domain.data.service.dialect.DialectProperties; import ai.chat2db.server.test.domain.data.utils.TestUtils; import ai.chat2db.server.tools.base.wrapper.result.DataResult; import ai.chat2db.server.tools.common.util.EasyCollectionUtils; import ai.chat2db.spi.enums.CollationEnum; import ai.chat2db.spi.enums.IndexTypeEnum; import ai.chat2db.spi.model.Sql; import ai.chat2db.spi.model.Table; import ai.chat2db.spi.model.TableColumn; import ai.chat2db.spi.model.TableIndex; import ai.chat2db.spi.model.TableIndexColumn; import com.google.common.collect.Lists; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; /** * Data source testing * * @author Jiaju Zhuang */ @Slf4j public class TableOperationsTest extends BaseTest { /** * Table Name */ public static final String TABLE_NAME = "data_ops_table_test_" + System.currentTimeMillis(); @Resource private DataSourceService dataSourceService; @Resource private ConsoleService consoleService; @Autowired private List<DialectProperties> dialectPropertiesList; @Resource private DlTemplateService dlTemplateService; @Resource private TableService tableService; //@Resource //private SqlOperations sqlOperations; @Test @Order(1) public void table() { for (DialectProperties dialectProperties : dialectPropertiesList) { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); // Prepare context putConnect(dialectProperties.getUrl(), dialectProperties.getUsername(), dialectProperties.getPassword(), dialectProperties.getDbType(), dialectProperties.getDatabaseName(), dataSourceId, consoleId); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId); consoleCreateParam.setConsoleId(consoleId); consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName()); consoleService.createConsole(consoleCreateParam); // Create table structure DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(dialectProperties.getCrateTableSql(TABLE_NAME)); dlTemplateService.execute(templateQueryParam); // Query table creation statement ShowCreateTableParam showCreateTableParam = ShowCreateTableParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); if (dialectProperties.getDbType() == "POSTGRESQL") { showCreateTableParam.setSchemaName("public"); } DataResult<String> createTable = tableService.showCreateTable(showCreateTableParam); log.info("Table creation statement: {}", createTable.getData()); if (dialectProperties.getDbType() != "H2") { Assertions.assertTrue(createTable.getData().contains(dialectProperties.toCase(TABLE_NAME)), "Query table structure failed"); } // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(TABLE_NAME)); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(TABLE_NAME)); tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the
|
java
|
(DialectProperties dialectProperties : dialectPropertiesList) { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); // Prepare context putConnect(dialectProperties.getUrl(), dialectProperties.getUsername(), dialectProperties.getPassword(), dialectProperties.getDbType(), dialectProperties.getDatabaseName(), dataSourceId, consoleId); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId); consoleCreateParam.setConsoleId(consoleId); consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName()); consoleService.createConsole(consoleCreateParam); // Create table structure DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(dialectProperties.getCrateTableSql(TABLE_NAME)); dlTemplateService.execute(templateQueryParam); // Query table creation statement ShowCreateTableParam showCreateTableParam = ShowCreateTableParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); if (dialectProperties.getDbType() == "POSTGRESQL") { showCreateTableParam.setSchemaName("public"); } DataResult<String> createTable = tableService.showCreateTable(showCreateTableParam); log.info("Table creation statement: {}", createTable.getData()); if (dialectProperties.getDbType() != "H2") { Assertions.assertTrue(createTable.getData().contains(dialectProperties.toCase(TABLE_NAME)), "Query table structure failed"); } // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(TABLE_NAME)); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(TABLE_NAME)); tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); // Test the table creation statement testBuildSql(dialectProperties, dataSourceId, consoleId); removeConnect(); } } private void testBuildSql(DialectProperties dialectProperties, Long dataSourceId, Long consoleId) { if (dialectProperties.getDbType() != "MYSQL") { log.error("Currently the test case only supports mysql"); return; } // Create new table // CREATE TABLE `DATA_OPS_TEMPLATE_TEST_1673093980449` // ( // `id` bigint PRIMARY KEY AUTO_INCREMENT NOT NULL COMMENT 'Primary key auto-increment', // `date` datetime(3) not null COMMENT 'date', // `number` bigint COMMENT 'long integer', // `string` VARCHAR(100) default 'DATA' COMMENT 'name', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' //) COMMENT ='Test table'; // * The case
|
(DialectProperties dialectProperties : dialectPropertiesList) { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); // Prepare context putConnect(dialectProperties.getUrl(), dialectProperties.getUsername(), dialectProperties.getPassword(), dialectProperties.getDbType(), dialectProperties.getDatabaseName(), dataSourceId, consoleId); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId); consoleCreateParam.setConsoleId(consoleId); consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName()); consoleService.createConsole(consoleCreateParam); // Create table structure DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(dialectProperties.getCrateTableSql(TABLE_NAME)); dlTemplateService.execute(templateQueryParam); // Query table creation statement ShowCreateTableParam showCreateTableParam = ShowCreateTableParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); if (dialectProperties.getDbType() == "POSTGRESQL") { showCreateTableParam.setSchemaName("public"); } DataResult<String> createTable = tableService.showCreateTable(showCreateTableParam); log.info("Table creation statement: {}", createTable.getData()); if (dialectProperties.getDbType() != "H2") { Assertions.assertTrue(createTable.getData().contains(dialectProperties.toCase(TABLE_NAME)), "Query table structure failed"); } // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(TABLE_NAME)); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(TABLE_NAME)); tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); // Test the table creation statement testBuildSql(dialectProperties, dataSourceId, consoleId); removeConnect(); } } private void testBuildSql(DialectProperties dialectProperties, Long dataSourceId, Long consoleId) { if (dialectProperties.getDbType() != "MYSQL") { log.error("Currently the test case only supports mysql"); return; } // Create new table // CREATE TABLE `DATA_OPS_TEMPLATE_TEST_1673093980449` // ( // `id` bigint PRIMARY KEY AUTO_INCREMENT NOT NULL COMMENT 'Primary key auto-increment', // `date` datetime(3) not null COMMENT 'date', // `number` bigint COMMENT 'long integer', // `string` VARCHAR(100) default 'DATA' COMMENT 'name', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' //) COMMENT ='Test table'; // * The case
|
java
|
= new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(TABLE_NAME)); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(TABLE_NAME)); tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); // Test the table creation statement testBuildSql(dialectProperties, dataSourceId, consoleId); removeConnect(); } } private void testBuildSql(DialectProperties dialectProperties, Long dataSourceId, Long consoleId) { if (dialectProperties.getDbType() != "MYSQL") { log.error("Currently the test case only supports mysql"); return; } // Create new table // CREATE TABLE `DATA_OPS_TEMPLATE_TEST_1673093980449` // ( // `id` bigint PRIMARY KEY AUTO_INCREMENT NOT NULL COMMENT 'Primary key auto-increment', // `date` datetime(3) not null COMMENT 'date', // `number` bigint COMMENT 'long integer', // `string` VARCHAR(100) default 'DATA' COMMENT 'name', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' //) COMMENT ='Test table'; // * The case depends on the specific database: //* Create table structure: Test table // * Fields: //* id Primary key auto-increment //* date date is not null // * number long integer // * string String length 100 default value "DATA" // * //* Index (plus $tableName_ because some database indexes are globally unique): //* $tableName_idx_date date index reverse order // * $tableName_uk_number unique index // * $tableName_idx_number_string Union index String tableName = dialectProperties.toCase("data_ops_table_test_" + System.currentTimeMillis()); Table newTable = new Table(); newTable.setName(tableName); newTable.setComment("Test table"); List<TableColumn> tableColumnList = new ArrayList<>(); newTable.setColumnList(tableColumnList); //id TableColumn idTableColumn = new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new
|
= new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(TABLE_NAME)); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(TABLE_NAME)); tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); // Test the table creation statement testBuildSql(dialectProperties, dataSourceId, consoleId); removeConnect(); } } private void testBuildSql(DialectProperties dialectProperties, Long dataSourceId, Long consoleId) { if (dialectProperties.getDbType() != "MYSQL") { log.error("Currently the test case only supports mysql"); return; } // Create new table // CREATE TABLE `DATA_OPS_TEMPLATE_TEST_1673093980449` // ( // `id` bigint PRIMARY KEY AUTO_INCREMENT NOT NULL COMMENT 'Primary key auto-increment', // `date` datetime(3) not null COMMENT 'date', // `number` bigint COMMENT 'long integer', // `string` VARCHAR(100) default 'DATA' COMMENT 'name', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' //) COMMENT ='Test table'; // * The case depends on the specific database: //* Create table structure: Test table // * Fields: //* id Primary key auto-increment //* date date is not null // * number long integer // * string String length 100 default value "DATA" // * //* Index (plus $tableName_ because some database indexes are globally unique): //* $tableName_idx_date date index reverse order // * $tableName_uk_number unique index // * $tableName_idx_number_string Union index String tableName = dialectProperties.toCase("data_ops_table_test_" + System.currentTimeMillis()); Table newTable = new Table(); newTable.setName(tableName); newTable.setComment("Test table"); List<TableColumn> tableColumnList = new ArrayList<>(); newTable.setColumnList(tableColumnList); //id TableColumn idTableColumn = new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new
|
java
|
.setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(TABLE_NAME)); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(TABLE_NAME)); tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); // Test the table creation statement testBuildSql(dialectProperties, dataSourceId, consoleId); removeConnect(); } } private void testBuildSql(DialectProperties dialectProperties, Long dataSourceId, Long consoleId) { if (dialectProperties.getDbType() != "MYSQL") { log.error("Currently the test case only supports mysql"); return; } // Create new table // CREATE TABLE `DATA_OPS_TEMPLATE_TEST_1673093980449` // ( // `id` bigint PRIMARY KEY AUTO_INCREMENT NOT NULL COMMENT 'Primary key auto-increment', // `date` datetime(3) not null COMMENT 'date', // `number` bigint COMMENT 'long integer', // `string` VARCHAR(100) default 'DATA' COMMENT 'name', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' //) COMMENT ='Test table'; // * The case depends on the specific database: //* Create table structure: Test table // * Fields: //* id Primary key auto-increment //* date date is not null // * number long integer // * string String length 100 default value "DATA" // * //* Index (plus $tableName_ because some database indexes are globally unique): //* $tableName_idx_date date index reverse order // * $tableName_uk_number unique index // * $tableName_idx_number_string Union index String tableName = dialectProperties.toCase("data_ops_table_test_" + System.currentTimeMillis()); Table newTable = new Table(); newTable.setName(tableName); newTable.setComment("Test table"); List<TableColumn> tableColumnList = new ArrayList<>(); newTable.setColumnList(tableColumnList); //id TableColumn idTableColumn = new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date");
|
.setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(TABLE_NAME)); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(TABLE_NAME)); tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); // Test the table creation statement testBuildSql(dialectProperties, dataSourceId, consoleId); removeConnect(); } } private void testBuildSql(DialectProperties dialectProperties, Long dataSourceId, Long consoleId) { if (dialectProperties.getDbType() != "MYSQL") { log.error("Currently the test case only supports mysql"); return; } // Create new table // CREATE TABLE `DATA_OPS_TEMPLATE_TEST_1673093980449` // ( // `id` bigint PRIMARY KEY AUTO_INCREMENT NOT NULL COMMENT 'Primary key auto-increment', // `date` datetime(3) not null COMMENT 'date', // `number` bigint COMMENT 'long integer', // `string` VARCHAR(100) default 'DATA' COMMENT 'name', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' //) COMMENT ='Test table'; // * The case depends on the specific database: //* Create table structure: Test table // * Fields: //* id Primary key auto-increment //* date date is not null // * number long integer // * string String length 100 default value "DATA" // * //* Index (plus $tableName_ because some database indexes are globally unique): //* $tableName_idx_date date index reverse order // * $tableName_uk_number unique index // * $tableName_idx_number_string Union index String tableName = dialectProperties.toCase("data_ops_table_test_" + System.currentTimeMillis()); Table newTable = new Table(); newTable.setName(tableName); newTable.setComment("Test table"); List<TableColumn> tableColumnList = new ArrayList<>(); newTable.setColumnList(tableColumnList); //id TableColumn idTableColumn = new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date");
|
java
|
.setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(TABLE_NAME)); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(TABLE_NAME)); tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); // Test the table creation statement testBuildSql(dialectProperties, dataSourceId, consoleId); removeConnect(); } } private void testBuildSql(DialectProperties dialectProperties, Long dataSourceId, Long consoleId) { if (dialectProperties.getDbType() != "MYSQL") { log.error("Currently the test case only supports mysql"); return; } // Create new table // CREATE TABLE `DATA_OPS_TEMPLATE_TEST_1673093980449` // ( // `id` bigint PRIMARY KEY AUTO_INCREMENT NOT NULL COMMENT 'Primary key auto-increment', // `date` datetime(3) not null COMMENT 'date', // `number` bigint COMMENT 'long integer', // `string` VARCHAR(100) default 'DATA' COMMENT 'name', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' //) COMMENT ='Test table'; // * The case depends on the specific database: //* Create table structure: Test table // * Fields: //* id Primary key auto-increment //* date date is not null // * number long integer // * string String length 100 default value "DATA" // * //* Index (plus $tableName_ because some database indexes are globally unique): //* $tableName_idx_date date index reverse order // * $tableName_uk_number unique index // * $tableName_idx_number_string Union index String tableName = dialectProperties.toCase("data_ops_table_test_" + System.currentTimeMillis()); Table newTable = new Table(); newTable.setName(tableName); newTable.setComment("Test table"); List<TableColumn> tableColumnList = new ArrayList<>(); newTable.setColumnList(tableColumnList); //id TableColumn idTableColumn = new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn);
|
.setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(TABLE_NAME)); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(TABLE_NAME)); tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); // Test the table creation statement testBuildSql(dialectProperties, dataSourceId, consoleId); removeConnect(); } } private void testBuildSql(DialectProperties dialectProperties, Long dataSourceId, Long consoleId) { if (dialectProperties.getDbType() != "MYSQL") { log.error("Currently the test case only supports mysql"); return; } // Create new table // CREATE TABLE `DATA_OPS_TEMPLATE_TEST_1673093980449` // ( // `id` bigint PRIMARY KEY AUTO_INCREMENT NOT NULL COMMENT 'Primary key auto-increment', // `date` datetime(3) not null COMMENT 'date', // `number` bigint COMMENT 'long integer', // `string` VARCHAR(100) default 'DATA' COMMENT 'name', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' //) COMMENT ='Test table'; // * The case depends on the specific database: //* Create table structure: Test table // * Fields: //* id Primary key auto-increment //* date date is not null // * number long integer // * string String length 100 default value "DATA" // * //* Index (plus $tableName_ because some database indexes are globally unique): //* $tableName_idx_date date index reverse order // * $tableName_uk_number unique index // * $tableName_idx_number_string Union index String tableName = dialectProperties.toCase("data_ops_table_test_" + System.currentTimeMillis()); Table newTable = new Table(); newTable.setName(tableName); newTable.setComment("Test table"); List<TableColumn> tableColumnList = new ArrayList<>(); newTable.setColumnList(tableColumnList); //id TableColumn idTableColumn = new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn);
|
java
|
.setTableName(dialectProperties.toCase(TABLE_NAME)); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(TABLE_NAME)); tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); // Test the table creation statement testBuildSql(dialectProperties, dataSourceId, consoleId); removeConnect(); } } private void testBuildSql(DialectProperties dialectProperties, Long dataSourceId, Long consoleId) { if (dialectProperties.getDbType() != "MYSQL") { log.error("Currently the test case only supports mysql"); return; } // Create new table // CREATE TABLE `DATA_OPS_TEMPLATE_TEST_1673093980449` // ( // `id` bigint PRIMARY KEY AUTO_INCREMENT NOT NULL COMMENT 'Primary key auto-increment', // `date` datetime(3) not null COMMENT 'date', // `number` bigint COMMENT 'long integer', // `string` VARCHAR(100) default 'DATA' COMMENT 'name', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' //) COMMENT ='Test table'; // * The case depends on the specific database: //* Create table structure: Test table // * Fields: //* id Primary key auto-increment //* date date is not null // * number long integer // * string String length 100 default value "DATA" // * //* Index (plus $tableName_ because some database indexes are globally unique): //* $tableName_idx_date date index reverse order // * $tableName_uk_number unique index // * $tableName_idx_number_string Union index String tableName = dialectProperties.toCase("data_ops_table_test_" + System.currentTimeMillis()); Table newTable = new Table(); newTable.setName(tableName); newTable.setComment("Test table"); List<TableColumn> tableColumnList = new ArrayList<>(); newTable.setColumnList(tableColumnList); //id TableColumn idTableColumn = new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number
|
.setTableName(dialectProperties.toCase(TABLE_NAME)); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(TABLE_NAME)); tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); // Test the table creation statement testBuildSql(dialectProperties, dataSourceId, consoleId); removeConnect(); } } private void testBuildSql(DialectProperties dialectProperties, Long dataSourceId, Long consoleId) { if (dialectProperties.getDbType() != "MYSQL") { log.error("Currently the test case only supports mysql"); return; } // Create new table // CREATE TABLE `DATA_OPS_TEMPLATE_TEST_1673093980449` // ( // `id` bigint PRIMARY KEY AUTO_INCREMENT NOT NULL COMMENT 'Primary key auto-increment', // `date` datetime(3) not null COMMENT 'date', // `number` bigint COMMENT 'long integer', // `string` VARCHAR(100) default 'DATA' COMMENT 'name', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' //) COMMENT ='Test table'; // * The case depends on the specific database: //* Create table structure: Test table // * Fields: //* id Primary key auto-increment //* date date is not null // * number long integer // * string String length 100 default value "DATA" // * //* Index (plus $tableName_ because some database indexes are globally unique): //* $tableName_idx_date date index reverse order // * $tableName_uk_number unique index // * $tableName_idx_number_string Union index String tableName = dialectProperties.toCase("data_ops_table_test_" + System.currentTimeMillis()); Table newTable = new Table(); newTable.setName(tableName); newTable.setComment("Test table"); List<TableColumn> tableColumnList = new ArrayList<>(); newTable.setColumnList(tableColumnList); //id TableColumn idTableColumn = new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number
|
java
|
{ <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { <mask> <mask> <mask> <mask> <mask> <mask> .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(TABLE_NAME)); tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); // Test the table creation statement testBuildSql(dialectProperties, dataSourceId, consoleId); removeConnect(); } } private void testBuildSql(DialectProperties dialectProperties, Long dataSourceId, Long consoleId) { if (dialectProperties.getDbType() != "MYSQL") { log.error("Currently the test case only supports mysql"); return; } // Create new table // CREATE TABLE `DATA_OPS_TEMPLATE_TEST_1673093980449` // ( // `id` bigint PRIMARY KEY AUTO_INCREMENT NOT NULL COMMENT 'Primary key auto-increment', // `date` datetime(3) not null COMMENT 'date', // `number` bigint COMMENT 'long integer', // `string` VARCHAR(100) default 'DATA' COMMENT 'name', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' //) COMMENT ='Test table'; // * The case depends on the specific database: //* Create table structure: Test table // * Fields: //* id Primary key auto-increment //* date date is not null // * number long integer // * string String length 100 default value "DATA" // * //* Index (plus $tableName_ because some database indexes are globally unique): //* $tableName_idx_date date index reverse order // * $tableName_uk_number unique index // * $tableName_idx_number_string Union index String tableName = dialectProperties.toCase("data_ops_table_test_" + System.currentTimeMillis()); Table newTable = new Table(); newTable.setName(tableName); newTable.setComment("Test table"); List<TableColumn> tableColumnList = new ArrayList<>(); newTable.setColumnList(tableColumnList); //id TableColumn idTableColumn = new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number TableColumn numberTableColumn = new TableColumn();
|
{ tablePageQueryParam .setSchemaName("public"); } List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); // Assertions.assertEquals(dialectProperties.toCase(TABLE_NAME), table.getName(), "Query table structure failed"); if (dialectProperties.getDbType() != "POSTGRESQL") { Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); } TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); if (dialectProperties.getDbType() == "POSTGRESQL") { tableQueryParam.setSchemaName("public"); } List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); if (dialectProperties.getDbType() == "POSTGRESQL") { tablePageQueryParam .setSchemaName("public"); } List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList)); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(TABLE_NAME)) .build(); tableService.drop(dropParam); // Query table structure tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(TABLE_NAME)); tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); // Test the table creation statement testBuildSql(dialectProperties, dataSourceId, consoleId); removeConnect(); } } private void testBuildSql(DialectProperties dialectProperties, Long dataSourceId, Long consoleId) { if (dialectProperties.getDbType() != "MYSQL") { log.error("Currently the test case only supports mysql"); return; } // Create new table // CREATE TABLE `DATA_OPS_TEMPLATE_TEST_1673093980449` // ( // `id` bigint PRIMARY KEY AUTO_INCREMENT NOT NULL COMMENT 'Primary key auto-increment', // `date` datetime(3) not null COMMENT 'date', // `number` bigint COMMENT 'long integer', // `string` VARCHAR(100) default 'DATA' COMMENT 'name', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' //) COMMENT ='Test table'; // * The case depends on the specific database: //* Create table structure: Test table // * Fields: //* id Primary key auto-increment //* date date is not null // * number long integer // * string String length 100 default value "DATA" // * //* Index (plus $tableName_ because some database indexes are globally unique): //* $tableName_idx_date date index reverse order // * $tableName_uk_number unique index // * $tableName_idx_number_string Union index String tableName = dialectProperties.toCase("data_ops_table_test_" + System.currentTimeMillis()); Table newTable = new Table(); newTable.setName(tableName); newTable.setComment("Test table"); List<TableColumn> tableColumnList = new ArrayList<>(); newTable.setColumnList(tableColumnList); //id TableColumn idTableColumn = new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number TableColumn numberTableColumn = new TableColumn();
|
java
|
structure: Test table // * Fields: //* id Primary key auto-increment //* date date is not null // * number long integer // * string String length 100 default value "DATA" // * //* Index (plus $tableName_ because some database indexes are globally unique): //* $tableName_idx_date date index reverse order // * $tableName_uk_number unique index // * $tableName_idx_number_string Union index String tableName = dialectProperties.toCase("data_ops_table_test_" + System.currentTimeMillis()); Table newTable = new Table(); newTable.setName(tableName); newTable.setComment("Test table"); List<TableColumn> tableColumnList = new ArrayList<>(); newTable.setColumnList(tableColumnList); //id TableColumn idTableColumn = new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number TableColumn numberTableColumn = new TableColumn(); numberTableColumn.setName("number"); numberTableColumn.setComment("long integer"); numberTableColumn.setColumnType("bigint"); tableColumnList.add(numberTableColumn); // string TableColumn stringTableColumn = new TableColumn(); stringTableColumn.setName("string"); stringTableColumn.setComment("name"); stringTableColumn.setColumnType("varchar(100)"); stringTableColumn.setDefaultValue("DATA"); tableColumnList.add(stringTableColumn); // index List<TableIndex> tableIndexList = new ArrayList<>(); newTable.setIndexList(tableIndexList); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_date") .type(IndexTypeEnum.NORMAL.getCode()) .comment("date index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("date") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', tableIndexList.add(TableIndex.builder() .name(tableName + "_uk_number") .type(IndexTypeEnum.UNIQUE.getCode()) .comment("unique index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build())) .build()); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder()
|
structure: Test table // * Fields: //* id Primary key auto-increment //* date date is not null // * number long integer // * string String length 100 default value "DATA" // * //* Index (plus $tableName_ because some database indexes are globally unique): //* $tableName_idx_date date index reverse order // * $tableName_uk_number unique index // * $tableName_idx_number_string Union index String tableName = dialectProperties.toCase("data_ops_table_test_" + System.currentTimeMillis()); Table newTable = new Table(); newTable.setName(tableName); newTable.setComment("Test table"); List<TableColumn> tableColumnList = new ArrayList<>(); newTable.setColumnList(tableColumnList); //id TableColumn idTableColumn = new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number TableColumn numberTableColumn = new TableColumn(); numberTableColumn.setName("number"); numberTableColumn.setComment("long integer"); numberTableColumn.setColumnType("bigint"); tableColumnList.add(numberTableColumn); // string TableColumn stringTableColumn = new TableColumn(); stringTableColumn.setName("string"); stringTableColumn.setComment("name"); stringTableColumn.setColumnType("varchar(100)"); stringTableColumn.setDefaultValue("DATA"); tableColumnList.add(stringTableColumn); // index List<TableIndex> tableIndexList = new ArrayList<>(); newTable.setIndexList(tableIndexList); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_date") .type(IndexTypeEnum.NORMAL.getCode()) .comment("date index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("date") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', tableIndexList.add(TableIndex.builder() .name(tableName + "_uk_number") .type(IndexTypeEnum.UNIQUE.getCode()) .comment("unique index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build())) .build()); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder()
|
java
|
* Fields: //* id Primary key auto-increment //* date date is not null // * number long integer // * string String length 100 default value "DATA" // * //* Index (plus $tableName_ because some database indexes are globally unique): //* $tableName_idx_date date index reverse order // * $tableName_uk_number unique index // * $tableName_idx_number_string Union index String tableName = dialectProperties.toCase("data_ops_table_test_" + System.currentTimeMillis()); Table newTable = new Table(); newTable.setName(tableName); newTable.setComment("Test table"); List<TableColumn> tableColumnList = new ArrayList<>(); newTable.setColumnList(tableColumnList); //id TableColumn idTableColumn = new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number TableColumn numberTableColumn = new TableColumn(); numberTableColumn.setName("number"); numberTableColumn.setComment("long integer"); numberTableColumn.setColumnType("bigint"); tableColumnList.add(numberTableColumn); // string TableColumn stringTableColumn = new TableColumn(); stringTableColumn.setName("string"); stringTableColumn.setComment("name"); stringTableColumn.setColumnType("varchar(100)"); stringTableColumn.setDefaultValue("DATA"); tableColumnList.add(stringTableColumn); // index List<TableIndex> tableIndexList = new ArrayList<>(); newTable.setIndexList(tableIndexList); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_date") .type(IndexTypeEnum.NORMAL.getCode()) .comment("date index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("date") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', tableIndexList.add(TableIndex.builder() .name(tableName + "_uk_number") .type(IndexTypeEnum.UNIQUE.getCode()) .comment("unique index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build())) .build()); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing
|
* Fields: //* id Primary key auto-increment //* date date is not null // * number long integer // * string String length 100 default value "DATA" // * //* Index (plus $tableName_ because some database indexes are globally unique): //* $tableName_idx_date date index reverse order // * $tableName_uk_number unique index // * $tableName_idx_number_string Union index String tableName = dialectProperties.toCase("data_ops_table_test_" + System.currentTimeMillis()); Table newTable = new Table(); newTable.setName(tableName); newTable.setComment("Test table"); List<TableColumn> tableColumnList = new ArrayList<>(); newTable.setColumnList(tableColumnList); //id TableColumn idTableColumn = new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number TableColumn numberTableColumn = new TableColumn(); numberTableColumn.setName("number"); numberTableColumn.setComment("long integer"); numberTableColumn.setColumnType("bigint"); tableColumnList.add(numberTableColumn); // string TableColumn stringTableColumn = new TableColumn(); stringTableColumn.setName("string"); stringTableColumn.setComment("name"); stringTableColumn.setColumnType("varchar(100)"); stringTableColumn.setDefaultValue("DATA"); tableColumnList.add(stringTableColumn); // index List<TableIndex> tableIndexList = new ArrayList<>(); newTable.setIndexList(tableIndexList); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_date") .type(IndexTypeEnum.NORMAL.getCode()) .comment("date index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("date") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', tableIndexList.add(TableIndex.builder() .name(tableName + "_uk_number") .type(IndexTypeEnum.UNIQUE.getCode()) .comment("unique index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build())) .build()); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing
|
java
|
//* id Primary key auto-increment //* date date is not null // * number long integer // * string String length 100 default value "DATA" // * //* Index (plus $tableName_ because some database indexes are globally unique): //* $tableName_idx_date date index reverse order // * $tableName_uk_number unique index // * $tableName_idx_number_string Union index String tableName = dialectProperties.toCase("data_ops_table_test_" + System.currentTimeMillis()); Table newTable = new Table(); newTable.setName(tableName); newTable.setComment("Test table"); List<TableColumn> tableColumnList = new ArrayList<>(); newTable.setColumnList(tableColumnList); //id TableColumn idTableColumn = new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number TableColumn numberTableColumn = new TableColumn(); numberTableColumn.setName("number"); numberTableColumn.setComment("long integer"); numberTableColumn.setColumnType("bigint"); tableColumnList.add(numberTableColumn); // string TableColumn stringTableColumn = new TableColumn(); stringTableColumn.setName("string"); stringTableColumn.setComment("name"); stringTableColumn.setColumnType("varchar(100)"); stringTableColumn.setDefaultValue("DATA"); tableColumnList.add(stringTableColumn); // index List<TableIndex> tableIndexList = new ArrayList<>(); newTable.setIndexList(tableIndexList); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_date") .type(IndexTypeEnum.NORMAL.getCode()) .comment("date index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("date") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', tableIndexList.add(TableIndex.builder() .name(tableName + "_uk_number") .type(IndexTypeEnum.UNIQUE.getCode()) .comment("unique index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build())) .build()); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns
|
//* id Primary key auto-increment //* date date is not null // * number long integer // * string String length 100 default value "DATA" // * //* Index (plus $tableName_ because some database indexes are globally unique): //* $tableName_idx_date date index reverse order // * $tableName_uk_number unique index // * $tableName_idx_number_string Union index String tableName = dialectProperties.toCase("data_ops_table_test_" + System.currentTimeMillis()); Table newTable = new Table(); newTable.setName(tableName); newTable.setComment("Test table"); List<TableColumn> tableColumnList = new ArrayList<>(); newTable.setColumnList(tableColumnList); //id TableColumn idTableColumn = new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number TableColumn numberTableColumn = new TableColumn(); numberTableColumn.setName("number"); numberTableColumn.setComment("long integer"); numberTableColumn.setColumnType("bigint"); tableColumnList.add(numberTableColumn); // string TableColumn stringTableColumn = new TableColumn(); stringTableColumn.setName("string"); stringTableColumn.setComment("name"); stringTableColumn.setColumnType("varchar(100)"); stringTableColumn.setDefaultValue("DATA"); tableColumnList.add(stringTableColumn); // index List<TableIndex> tableIndexList = new ArrayList<>(); newTable.setIndexList(tableIndexList); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_date") .type(IndexTypeEnum.NORMAL.getCode()) .comment("date index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("date") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', tableIndexList.add(TableIndex.builder() .name(tableName + "_uk_number") .type(IndexTypeEnum.UNIQUE.getCode()) .comment("unique index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build())) .build()); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns
|
java
|
Primary key auto-increment //* date date is not null // * number long integer // * string String length 100 default value "DATA" // * //* Index (plus $tableName_ because some database indexes are globally unique): //* $tableName_idx_date date index reverse order // * $tableName_uk_number unique index // * $tableName_idx_number_string Union index String tableName = dialectProperties.toCase("data_ops_table_test_" + System.currentTimeMillis()); Table newTable = new Table(); newTable.setName(tableName); newTable.setComment("Test table"); List<TableColumn> tableColumnList = new ArrayList<>(); newTable.setColumnList(tableColumnList); //id TableColumn idTableColumn = new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number TableColumn numberTableColumn = new TableColumn(); numberTableColumn.setName("number"); numberTableColumn.setComment("long integer"); numberTableColumn.setColumnType("bigint"); tableColumnList.add(numberTableColumn); // string TableColumn stringTableColumn = new TableColumn(); stringTableColumn.setName("string"); stringTableColumn.setComment("name"); stringTableColumn.setColumnType("varchar(100)"); stringTableColumn.setDefaultValue("DATA"); tableColumnList.add(stringTableColumn); // index List<TableIndex> tableIndexList = new ArrayList<>(); newTable.setIndexList(tableIndexList); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_date") .type(IndexTypeEnum.NORMAL.getCode()) .comment("date index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("date") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', tableIndexList.add(TableIndex.builder() .name(tableName + "_uk_number") .type(IndexTypeEnum.UNIQUE.getCode()) .comment("unique index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build())) .build()); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList));
|
Primary key auto-increment //* date date is not null // * number long integer // * string String length 100 default value "DATA" // * //* Index (plus $tableName_ because some database indexes are globally unique): //* $tableName_idx_date date index reverse order // * $tableName_uk_number unique index // * $tableName_idx_number_string Union index String tableName = dialectProperties.toCase("data_ops_table_test_" + System.currentTimeMillis()); Table newTable = new Table(); newTable.setName(tableName); newTable.setComment("Test table"); List<TableColumn> tableColumnList = new ArrayList<>(); newTable.setColumnList(tableColumnList); //id TableColumn idTableColumn = new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number TableColumn numberTableColumn = new TableColumn(); numberTableColumn.setName("number"); numberTableColumn.setComment("long integer"); numberTableColumn.setColumnType("bigint"); tableColumnList.add(numberTableColumn); // string TableColumn stringTableColumn = new TableColumn(); stringTableColumn.setName("string"); stringTableColumn.setComment("name"); stringTableColumn.setColumnType("varchar(100)"); stringTableColumn.setDefaultValue("DATA"); tableColumnList.add(stringTableColumn); // index List<TableIndex> tableIndexList = new ArrayList<>(); newTable.setIndexList(tableIndexList); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_date") .type(IndexTypeEnum.NORMAL.getCode()) .comment("date index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("date") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', tableIndexList.add(TableIndex.builder() .name(tableName + "_uk_number") .type(IndexTypeEnum.UNIQUE.getCode()) .comment("unique index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build())) .build()); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList));
|
java
|
is not null // * number long integer // * string String length 100 default value "DATA" // * //* Index (plus $tableName_ because some database indexes are globally unique): //* $tableName_idx_date date index reverse order // * $tableName_uk_number unique index // * $tableName_idx_number_string Union index String tableName = dialectProperties.toCase("data_ops_table_test_" + System.currentTimeMillis()); Table newTable = new Table(); newTable.setName(tableName); newTable.setComment("Test table"); List<TableColumn> tableColumnList = new ArrayList<>(); newTable.setColumnList(tableColumnList); //id TableColumn idTableColumn = new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number TableColumn numberTableColumn = new TableColumn(); numberTableColumn.setName("number"); numberTableColumn.setComment("long integer"); numberTableColumn.setColumnType("bigint"); tableColumnList.add(numberTableColumn); // string TableColumn stringTableColumn = new TableColumn(); stringTableColumn.setName("string"); stringTableColumn.setComment("name"); stringTableColumn.setColumnType("varchar(100)"); stringTableColumn.setDefaultValue("DATA"); tableColumnList.add(stringTableColumn); // index List<TableIndex> tableIndexList = new ArrayList<>(); newTable.setIndexList(tableIndexList); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_date") .type(IndexTypeEnum.NORMAL.getCode()) .comment("date index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("date") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', tableIndexList.add(TableIndex.builder() .name(tableName + "_uk_number") .type(IndexTypeEnum.UNIQUE.getCode()) .comment("unique index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build())) .build()); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed");
|
is not null // * number long integer // * string String length 100 default value "DATA" // * //* Index (plus $tableName_ because some database indexes are globally unique): //* $tableName_idx_date date index reverse order // * $tableName_uk_number unique index // * $tableName_idx_number_string Union index String tableName = dialectProperties.toCase("data_ops_table_test_" + System.currentTimeMillis()); Table newTable = new Table(); newTable.setName(tableName); newTable.setComment("Test table"); List<TableColumn> tableColumnList = new ArrayList<>(); newTable.setColumnList(tableColumnList); //id TableColumn idTableColumn = new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number TableColumn numberTableColumn = new TableColumn(); numberTableColumn.setName("number"); numberTableColumn.setComment("long integer"); numberTableColumn.setColumnType("bigint"); tableColumnList.add(numberTableColumn); // string TableColumn stringTableColumn = new TableColumn(); stringTableColumn.setName("string"); stringTableColumn.setComment("name"); stringTableColumn.setColumnType("varchar(100)"); stringTableColumn.setDefaultValue("DATA"); tableColumnList.add(stringTableColumn); // index List<TableIndex> tableIndexList = new ArrayList<>(); newTable.setIndexList(tableIndexList); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_date") .type(IndexTypeEnum.NORMAL.getCode()) .comment("date index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("date") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', tableIndexList.add(TableIndex.builder() .name(tableName + "_uk_number") .type(IndexTypeEnum.UNIQUE.getCode()) .comment("unique index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build())) .build()); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed");
|
java
|
newTable.setColumnList(tableColumnList); //id TableColumn idTableColumn = new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number TableColumn numberTableColumn = new TableColumn(); numberTableColumn.setName("number"); numberTableColumn.setComment("long integer"); numberTableColumn.setColumnType("bigint"); tableColumnList.add(numberTableColumn); // string TableColumn stringTableColumn = new TableColumn(); stringTableColumn.setName("string"); stringTableColumn.setComment("name"); stringTableColumn.setColumnType("varchar(100)"); stringTableColumn.setDefaultValue("DATA"); tableColumnList.add(stringTableColumn); // index List<TableIndex> tableIndexList = new ArrayList<>(); newTable.setIndexList(tableIndexList); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_date") .type(IndexTypeEnum.NORMAL.getCode()) .comment("date index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("date") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', tableIndexList.add(TableIndex.builder() .name(tableName + "_uk_number") .type(IndexTypeEnum.UNIQUE.getCode()) .comment("unique index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build())) .build()); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query
|
newTable.setColumnList(tableColumnList); //id TableColumn idTableColumn = new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number TableColumn numberTableColumn = new TableColumn(); numberTableColumn.setName("number"); numberTableColumn.setComment("long integer"); numberTableColumn.setColumnType("bigint"); tableColumnList.add(numberTableColumn); // string TableColumn stringTableColumn = new TableColumn(); stringTableColumn.setName("string"); stringTableColumn.setComment("name"); stringTableColumn.setColumnType("varchar(100)"); stringTableColumn.setDefaultValue("DATA"); tableColumnList.add(stringTableColumn); // index List<TableIndex> tableIndexList = new ArrayList<>(); newTable.setIndexList(tableIndexList); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_date") .type(IndexTypeEnum.NORMAL.getCode()) .comment("date index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("date") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', tableIndexList.add(TableIndex.builder() .name(tableName + "_uk_number") .type(IndexTypeEnum.UNIQUE.getCode()) .comment("unique index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build())) .build()); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query
|
java
|
= new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number TableColumn numberTableColumn = new TableColumn(); numberTableColumn.setName("number"); numberTableColumn.setComment("long integer"); numberTableColumn.setColumnType("bigint"); tableColumnList.add(numberTableColumn); // string TableColumn stringTableColumn = new TableColumn(); stringTableColumn.setName("string"); stringTableColumn.setComment("name"); stringTableColumn.setColumnType("varchar(100)"); stringTableColumn.setDefaultValue("DATA"); tableColumnList.add(stringTableColumn); // index List<TableIndex> tableIndexList = new ArrayList<>(); newTable.setIndexList(tableIndexList); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_date") .type(IndexTypeEnum.NORMAL.getCode()) .comment("date index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("date") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', tableIndexList.add(TableIndex.builder() .name(tableName + "_uk_number") .type(IndexTypeEnum.UNIQUE.getCode()) .comment("unique index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build())) .build()); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn
|
= new TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number TableColumn numberTableColumn = new TableColumn(); numberTableColumn.setName("number"); numberTableColumn.setComment("long integer"); numberTableColumn.setColumnType("bigint"); tableColumnList.add(numberTableColumn); // string TableColumn stringTableColumn = new TableColumn(); stringTableColumn.setName("string"); stringTableColumn.setComment("name"); stringTableColumn.setColumnType("varchar(100)"); stringTableColumn.setDefaultValue("DATA"); tableColumnList.add(stringTableColumn); // index List<TableIndex> tableIndexList = new ArrayList<>(); newTable.setIndexList(tableIndexList); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_date") .type(IndexTypeEnum.NORMAL.getCode()) .comment("date index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("date") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', tableIndexList.add(TableIndex.builder() .name(tableName + "_uk_number") .type(IndexTypeEnum.UNIQUE.getCode()) .comment("unique index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build())) .build()); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn
|
java
|
TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number TableColumn numberTableColumn = new TableColumn(); numberTableColumn.setName("number"); numberTableColumn.setComment("long integer"); numberTableColumn.setColumnType("bigint"); tableColumnList.add(numberTableColumn); // string TableColumn stringTableColumn = new TableColumn(); stringTableColumn.setName("string"); stringTableColumn.setComment("name"); stringTableColumn.setColumnType("varchar(100)"); stringTableColumn.setDefaultValue("DATA"); tableColumnList.add(stringTableColumn); // index List<TableIndex> tableIndexList = new ArrayList<>(); newTable.setIndexList(tableIndexList); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_date") .type(IndexTypeEnum.NORMAL.getCode()) .comment("date index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("date") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', tableIndexList.add(TableIndex.builder() .name(tableName + "_uk_number") .type(IndexTypeEnum.UNIQUE.getCode()) .comment("unique index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build())) .build()); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string =
|
TableColumn(); idTableColumn.setName("id"); idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number TableColumn numberTableColumn = new TableColumn(); numberTableColumn.setName("number"); numberTableColumn.setComment("long integer"); numberTableColumn.setColumnType("bigint"); tableColumnList.add(numberTableColumn); // string TableColumn stringTableColumn = new TableColumn(); stringTableColumn.setName("string"); stringTableColumn.setComment("name"); stringTableColumn.setColumnType("varchar(100)"); stringTableColumn.setDefaultValue("DATA"); tableColumnList.add(stringTableColumn); // index List<TableIndex> tableIndexList = new ArrayList<>(); newTable.setIndexList(tableIndexList); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_date") .type(IndexTypeEnum.NORMAL.getCode()) .comment("date index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("date") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', tableIndexList.add(TableIndex.builder() .name(tableName + "_uk_number") .type(IndexTypeEnum.UNIQUE.getCode()) .comment("unique index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build())) .build()); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string =
|
java
|
idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number TableColumn numberTableColumn = new TableColumn(); numberTableColumn.setName("number"); numberTableColumn.setComment("long integer"); numberTableColumn.setColumnType("bigint"); tableColumnList.add(numberTableColumn); // string TableColumn stringTableColumn = new TableColumn(); stringTableColumn.setName("string"); stringTableColumn.setComment("name"); stringTableColumn.setColumnType("varchar(100)"); stringTableColumn.setDefaultValue("DATA"); tableColumnList.add(stringTableColumn); // index List<TableIndex> tableIndexList = new ArrayList<>(); newTable.setIndexList(tableIndexList); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_date") .type(IndexTypeEnum.NORMAL.getCode()) .comment("date index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("date") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', tableIndexList.add(TableIndex.builder() .name(tableName + "_uk_number") .type(IndexTypeEnum.UNIQUE.getCode()) .comment("unique index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build())) .build()); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"),
|
idTableColumn.setAutoIncrement(Boolean.TRUE); idTableColumn.setPrimaryKey(Boolean.TRUE); //idTableColumn.setNullable(Boolean.FALSE); idTableColumn.setComment("Primary key auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number TableColumn numberTableColumn = new TableColumn(); numberTableColumn.setName("number"); numberTableColumn.setComment("long integer"); numberTableColumn.setColumnType("bigint"); tableColumnList.add(numberTableColumn); // string TableColumn stringTableColumn = new TableColumn(); stringTableColumn.setName("string"); stringTableColumn.setComment("name"); stringTableColumn.setColumnType("varchar(100)"); stringTableColumn.setDefaultValue("DATA"); tableColumnList.add(stringTableColumn); // index List<TableIndex> tableIndexList = new ArrayList<>(); newTable.setIndexList(tableIndexList); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_date") .type(IndexTypeEnum.NORMAL.getCode()) .comment("date index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("date") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', tableIndexList.add(TableIndex.builder() .name(tableName + "_uk_number") .type(IndexTypeEnum.UNIQUE.getCode()) .comment("unique index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build())) .build()); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"),
|
java
|
auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number TableColumn numberTableColumn = new TableColumn(); numberTableColumn.setName("number"); numberTableColumn.setComment("long integer"); numberTableColumn.setColumnType("bigint"); tableColumnList.add(numberTableColumn); // string TableColumn stringTableColumn = new TableColumn(); stringTableColumn.setName("string"); stringTableColumn.setComment("name"); stringTableColumn.setColumnType("varchar(100)"); stringTableColumn.setDefaultValue("DATA"); tableColumnList.add(stringTableColumn); // index List<TableIndex> tableIndexList = new ArrayList<>(); newTable.setIndexList(tableIndexList); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_date") .type(IndexTypeEnum.NORMAL.getCode()) .comment("date index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("date") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', tableIndexList.add(TableIndex.builder() .name(tableName + "_uk_number") .type(IndexTypeEnum.UNIQUE.getCode()) .comment("unique index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build())) .build()); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed");
|
auto-increment"); idTableColumn.setColumnType("bigint"); tableColumnList.add(idTableColumn); // date TableColumn dateTableColumn = new TableColumn(); dateTableColumn.setName("date"); //dateTableColumn.setNullable(Boolean.FALSE); dateTableColumn.setComment("date"); dateTableColumn.setColumnType("datetime(3)"); tableColumnList.add(dateTableColumn); // number TableColumn numberTableColumn = new TableColumn(); numberTableColumn.setName("number"); numberTableColumn.setComment("long integer"); numberTableColumn.setColumnType("bigint"); tableColumnList.add(numberTableColumn); // string TableColumn stringTableColumn = new TableColumn(); stringTableColumn.setName("string"); stringTableColumn.setComment("name"); stringTableColumn.setColumnType("varchar(100)"); stringTableColumn.setDefaultValue("DATA"); tableColumnList.add(stringTableColumn); // index List<TableIndex> tableIndexList = new ArrayList<>(); newTable.setIndexList(tableIndexList); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_date (date desc) comment 'date index', tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_date") .type(IndexTypeEnum.NORMAL.getCode()) .comment("date index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("date") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // unique DATA_OPS_TEMPLATE_TEST_1673093980449_uk_number (number) comment 'unique index', tableIndexList.add(TableIndex.builder() .name(tableName + "_uk_number") .type(IndexTypeEnum.UNIQUE.getCode()) .comment("unique index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build())) .build()); // index DATA_OPS_TEMPLATE_TEST_1673093980449_idx_number_string (number, date) comment 'Union index' tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed");
|
java
|
index' tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(tableName + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query
|
index' tableIndexList.add(TableIndex.builder() .name(tableName + "_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(tableName + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query
|
java
|
"_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(tableName + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); }
|
"_idx_number_string") .type(IndexTypeEnum.NORMAL.getCode()) .comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(tableName + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); }
|
java
|
.comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(tableName + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); } @Test @Order(Integer.MAX_VALUE)
|
.comment("Union index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(tableName + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); } @Test @Order(Integer.MAX_VALUE)
|
java
|
.columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(tableName + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); } @Test @Order(Integer.MAX_VALUE) public void
|
.columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("number") .build(), TableIndexColumn.builder() .columnName("date") .build())) .build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(tableName + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); } @Test @Order(Integer.MAX_VALUE) public void
|
java
|
.build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(tableName + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); } @Test @Order(Integer.MAX_VALUE) public void dropTable() { for (DialectProperties dialectProperties :
|
.build()); // build sql List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData(); log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList)); for (Sql sql : buildTableSqlList) { DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId); templateQueryParam.setSql(sql.getSql()); dlTemplateService.execute(templateQueryParam); } // Check table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(tableName + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); } @Test @Order(Integer.MAX_VALUE) public void dropTable() { for (DialectProperties dialectProperties :
|
java
|
table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(tableName + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); } @Test @Order(Integer.MAX_VALUE) public void dropTable() { for (DialectProperties dialectProperties : dialectPropertiesList) { try { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId);
|
table structure checkTable(tableName, dialectProperties, dataSourceId); // Go to the database to query the table structure TableQueryParam tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(tableName + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); } @Test @Order(Integer.MAX_VALUE) public void dropTable() { for (DialectProperties dialectProperties : dialectPropertiesList) { try { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId);
|
java
|
dataSourceId); // Go to the database to query the table structure TableQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(tableName + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); } @Test @Order(Integer.MAX_VALUE) public void dropTable() { for (DialectProperties dialectProperties : dialectPropertiesList) { try { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId); consoleCreateParam.setConsoleId(consoleId); consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName()); consoleService.createConsole(consoleCreateParam); //
|
dataSourceId); // Go to the database to query the table structure TableQueryParam tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(tableName + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); } @Test @Order(Integer.MAX_VALUE) public void dropTable() { for (DialectProperties dialectProperties : dialectPropertiesList) { try { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId); consoleCreateParam.setConsoleId(consoleId); consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName()); consoleService.createConsole(consoleCreateParam); //
|
java
|
Go to the database to query the table structure TableQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(tableName + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); } @Test @Order(Integer.MAX_VALUE) public void dropTable() { for (DialectProperties dialectProperties : dialectPropertiesList) { try { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId); consoleCreateParam.setConsoleId(consoleId); consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName()); consoleService.createConsole(consoleCreateParam); // Create table
|
Go to the database to query the table structure TableQueryParam tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(tableName + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); } @Test @Order(Integer.MAX_VALUE) public void dropTable() { for (DialectProperties dialectProperties : dialectPropertiesList) { try { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId); consoleCreateParam.setConsoleId(consoleId); consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName()); consoleService.createConsole(consoleCreateParam); // Create table
|
java
|
the database to query the table structure TableQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(tableName + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); } @Test @Order(Integer.MAX_VALUE) public void dropTable() { for (DialectProperties dialectProperties : dialectPropertiesList) { try { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId); consoleCreateParam.setConsoleId(consoleId); consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName()); consoleService.createConsole(consoleCreateParam); // Create table structure DlExecuteParam
|
the database to query the table structure TableQueryParam tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(tableName + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); } @Test @Order(Integer.MAX_VALUE) public void dropTable() { for (DialectProperties dialectProperties : dialectPropertiesList) { try { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId); consoleCreateParam.setConsoleId(consoleId); consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName()); consoleService.createConsole(consoleCreateParam); // Create table structure DlExecuteParam
|
java
|
structure TableQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. <mask> <mask> <mask> <mask> <mask> <mask> = new TableQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam <mask> <mask> <mask> <mask> <mask> <mask> = new TablePageQueryParam(); <mask> <mask> <mask> <mask> <mask> <mask> .setDataSourceId(dataSourceId); <mask> <mask> <mask> <mask> <mask> <mask> .setDatabaseName(dialectProperties.getDatabaseName()); <mask> <mask> <mask> <mask> <mask> <mask> .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( <mask> <mask> <mask> <mask> <mask> <mask> , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(tableName + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); } @Test @Order(Integer.MAX_VALUE) public void dropTable() { for (DialectProperties dialectProperties : dialectPropertiesList) { try { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId); consoleCreateParam.setConsoleId(consoleId); consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName()); consoleService.createConsole(consoleCreateParam); // Create table structure DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId);
|
structure TableQueryParam tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); Table table = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(table)); Assertions.assertNotNull(table, "Query table structure failed"); Table oldTable = table; Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed"); // Modify table structure // build sql log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败"); // Let’s query again. There will be 2 objects. tablePageQueryParam = new TableQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); newTable = tableService.query( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); // Modify fields // Add a new field newTable.getColumnList().add(TableColumn.builder() .name("add_string") .columnType("varchar(20)") .comment("New string") .build()); // Add a new index newTable.getIndexList().add(TableIndex.builder() .name(tableName + "_idx_string_new") .type(IndexTypeEnum.NORMAL.getCode()) .comment("new string index") .columnList(Lists.newArrayList(TableIndexColumn.builder() .columnName("add_string") .collation(CollationEnum.DESC.getCode()) .build())) .build()); // Query table structure changes log.info("oldTable:{}", JSON.toJSONString(oldTable)); log.info("newTable:{}", JSON.toJSONString(newTable)); buildTableSqlList = tableService.buildSql(oldTable, newTable).getData(); log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList)); // Delete table structure dropTable(tableName, dialectProperties, dataSourceId); } private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Delete table structure DropParam dropParam = DropParam.builder() .dataSourceId(dataSourceId) .databaseName(dialectProperties.getDatabaseName()) .tableName(dialectProperties.toCase(tableName)) .build(); tableService.drop(dropParam); // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(0L, tableList.size(), "Query table structure failed"); } private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) { // Query table structure TablePageQueryParam tablePageQueryParam = new TablePageQueryParam(); tablePageQueryParam .setDataSourceId(dataSourceId); tablePageQueryParam .setDatabaseName(dialectProperties.getDatabaseName()); tablePageQueryParam .setTableName(dialectProperties.toCase(tableName)); List<Table> tableList = tableService.pageQuery( tablePageQueryParam , TableSelector.builder() .columnList(Boolean.TRUE) .indexList(Boolean.TRUE) .build()).getData(); log.info("Analyzing data returns {}", JSON.toJSONString(tableList)); Assertions.assertEquals(1L, tableList.size(), "Query table structure failed"); Table table = tableList.get(0); Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed"); Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed"); TableQueryParam tableQueryParam = new TableQueryParam(); tableQueryParam.setTableName(table.getName()); tableQueryParam.setDataSourceId(dataSourceId); tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName()); List<TableColumn> columnList = tableService.queryColumns(tableQueryParam); Assertions.assertEquals(4L, columnList.size(), "Query table structure failed"); TableColumn id = columnList.get(0); Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed"); Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed"); Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed"); //Assertions.assertFalse(id.getNullable(), "Query table structure failed"); Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed"); TableColumn string = columnList.get(3); Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed"); //Assertions.assertTrue(string.getNullable(), "Query table structure failed"); Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()), "Query table structure failed"); List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam); Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed"); Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList, TableIndex::getName); TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_date")); Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed"); Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed"); Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(), "Query table structure failed"); Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(), "Query table structure failed"); TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(tableName + "_uk_number")); Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed"); Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed"); TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_number_string")); Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed"); } @Test @Order(Integer.MAX_VALUE) public void dropTable() { for (DialectProperties dialectProperties : dialectPropertiesList) { try { String dbTypeEnum = dialectProperties.getDbType(); Long dataSourceId = TestUtils.nextLong(); Long consoleId = TestUtils.nextLong(); DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam(); dataSourceCreateParam.setType(dbTypeEnum); dataSourceCreateParam.setUrl(dialectProperties.getUrl()); dataSourceCreateParam.setUser(dialectProperties.getUsername()); dataSourceCreateParam.setPassword(dialectProperties.getPassword()); dataSourceService.preConnect(dataSourceCreateParam); // Create a console ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam(); consoleCreateParam.setDataSourceId(dataSourceId); consoleCreateParam.setConsoleId(consoleId); consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName()); consoleService.createConsole(consoleCreateParam); // Create table structure DlExecuteParam templateQueryParam = new DlExecuteParam(); templateQueryParam.setConsoleId(consoleId); templateQueryParam.setDataSourceId(dataSourceId);
|
java
|
getVertThumbIcon().getIconHeight(); } else { size.width = getHorizThumbIcon().getIconWidth(); size.height = getHorizThumbIcon().getIconHeight(); } return size; } /** * Gets the height of the tick area for horizontal sliders and the width of the * tick area for vertical sliders. BasicSliderUI uses the returned value to * determine the tick area rectangle. */ public int getTickLength() { return slider.getOrientation() == JSlider.HORIZONTAL ? safeLength + TICK_BUFFER + 1 : safeLength + TICK_BUFFER + 3; } /** * Returns the shorter dimension of the track. * * @return the shorter dimension of the track */ protected int getTrackWidth() { // This strange calculation is here to keep the // track in proportion to the thumb. final double kIdealTrackWidth = 7.0; final double kIdealThumbHeight = 16.0; final double kWidthScalar = kIdealTrackWidth / kIdealThumbHeight; if ( slider.getOrientation() == JSlider.HORIZONTAL ) { return (int)(kWidthScalar * thumbRect.height); } else { return (int)(kWidthScalar * thumbRect.width); } } /** * Returns the longer dimension of the slide bar. (The slide bar is only the * part that runs directly under the thumb) * * @return the longer dimension of the slide bar */ protected int getTrackLength() { if ( slider.getOrientation() == JSlider.HORIZONTAL ) { return trackRect.width; } return trackRect.height; } /** * Returns the amount that the thumb goes past the slide bar. * * @return the amount that the thumb goes past the slide bar */ protected int getThumbOverhang() { return (int)(getThumbSize().getHeight()-getTrackWidth())/2; } protected void scrollDueToClickInTrack( int dir ) { scrollByUnit( dir ); } protected void paintMinorTickForHorizSlider( Graphics g, Rectangle <mask> <mask> <mask> <mask> <mask> , int x ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); g.drawLine( x, TICK_BUFFER, x, TICK_BUFFER + (safeLength / 2) ); } protected void paintMajorTickForHorizSlider( Graphics g, Rectangle <mask> <mask> <mask> <mask> <mask> , int x ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); g.drawLine( x, TICK_BUFFER , x, TICK_BUFFER + (safeLength - 1) ); } protected void paintMinorTickForVertSlider( Graphics g, Rectangle <mask> <mask> <mask> <mask> <mask> , int y ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); if (MetalUtils.isLeftToRight(slider)) { g.drawLine( TICK_BUFFER, y, TICK_BUFFER + (safeLength / 2), y ); } else { g.drawLine( 0, y, safeLength/2, y ); } } protected void paintMajorTickForVertSlider( Graphics g, Rectangle <mask> <mask> <mask> <mask> <mask> , int y ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); if (MetalUtils.isLeftToRight(slider)) { g.drawLine( TICK_BUFFER, y, TICK_BUFFER + safeLength, y ); } else { g.drawLine( 0, y, safeLength, y ); } } }
|
getVertThumbIcon().getIconHeight(); } else { size.width = getHorizThumbIcon().getIconWidth(); size.height = getHorizThumbIcon().getIconHeight(); } return size; } /** * Gets the height of the tick area for horizontal sliders and the width of the * tick area for vertical sliders. BasicSliderUI uses the returned value to * determine the tick area rectangle. */ public int getTickLength() { return slider.getOrientation() == JSlider.HORIZONTAL ? safeLength + TICK_BUFFER + 1 : safeLength + TICK_BUFFER + 3; } /** * Returns the shorter dimension of the track. * * @return the shorter dimension of the track */ protected int getTrackWidth() { // This strange calculation is here to keep the // track in proportion to the thumb. final double kIdealTrackWidth = 7.0; final double kIdealThumbHeight = 16.0; final double kWidthScalar = kIdealTrackWidth / kIdealThumbHeight; if ( slider.getOrientation() == JSlider.HORIZONTAL ) { return (int)(kWidthScalar * thumbRect.height); } else { return (int)(kWidthScalar * thumbRect.width); } } /** * Returns the longer dimension of the slide bar. (The slide bar is only the * part that runs directly under the thumb) * * @return the longer dimension of the slide bar */ protected int getTrackLength() { if ( slider.getOrientation() == JSlider.HORIZONTAL ) { return trackRect.width; } return trackRect.height; } /** * Returns the amount that the thumb goes past the slide bar. * * @return the amount that the thumb goes past the slide bar */ protected int getThumbOverhang() { return (int)(getThumbSize().getHeight()-getTrackWidth())/2; } protected void scrollDueToClickInTrack( int dir ) { scrollByUnit( dir ); } protected void paintMinorTickForHorizSlider( Graphics g, Rectangle tickBounds , int x ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); g.drawLine( x, TICK_BUFFER, x, TICK_BUFFER + (safeLength / 2) ); } protected void paintMajorTickForHorizSlider( Graphics g, Rectangle tickBounds , int x ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); g.drawLine( x, TICK_BUFFER , x, TICK_BUFFER + (safeLength - 1) ); } protected void paintMinorTickForVertSlider( Graphics g, Rectangle tickBounds , int y ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); if (MetalUtils.isLeftToRight(slider)) { g.drawLine( TICK_BUFFER, y, TICK_BUFFER + (safeLength / 2), y ); } else { g.drawLine( 0, y, safeLength/2, y ); } } protected void paintMajorTickForVertSlider( Graphics g, Rectangle tickBounds , int y ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); if (MetalUtils.isLeftToRight(slider)) { g.drawLine( TICK_BUFFER, y, TICK_BUFFER + safeLength, y ); } else { g.drawLine( 0, y, safeLength, y ); } } }
|
java
|
the * tick area for vertical sliders. BasicSliderUI uses the returned value to * determine the tick area rectangle. */ public int getTickLength() { return slider.getOrientation() == JSlider.HORIZONTAL ? safeLength + TICK_BUFFER + 1 : safeLength + TICK_BUFFER + 3; } /** * Returns the shorter dimension of the track. * * @return the shorter dimension of the track */ protected int getTrackWidth() { // This strange calculation is here to keep the // track in proportion to the thumb. final double kIdealTrackWidth = 7.0; final double kIdealThumbHeight = 16.0; final double kWidthScalar = kIdealTrackWidth / kIdealThumbHeight; if ( slider.getOrientation() == JSlider.HORIZONTAL ) { return (int)(kWidthScalar * thumbRect.height); } else { return (int)(kWidthScalar * thumbRect.width); } } /** * Returns the longer dimension of the slide bar. (The slide bar is only the * part that runs directly under the thumb) * * @return the longer dimension of the slide bar */ protected int getTrackLength() { if ( slider.getOrientation() == JSlider.HORIZONTAL ) { return trackRect.width; } return trackRect.height; } /** * Returns the amount that the thumb goes past the slide bar. * * @return the amount that the thumb goes past the slide bar */ protected int getThumbOverhang() { return (int)(getThumbSize().getHeight()-getTrackWidth())/2; } protected void scrollDueToClickInTrack( int dir ) { scrollByUnit( dir ); } protected void paintMinorTickForHorizSlider( Graphics g, Rectangle <mask> <mask> <mask> <mask> <mask> , int x ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); g.drawLine( x, TICK_BUFFER, x, TICK_BUFFER + (safeLength / 2) ); } protected void paintMajorTickForHorizSlider( Graphics g, Rectangle <mask> <mask> <mask> <mask> <mask> , int x ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); g.drawLine( x, TICK_BUFFER , x, TICK_BUFFER + (safeLength - 1) ); } protected void paintMinorTickForVertSlider( Graphics g, Rectangle <mask> <mask> <mask> <mask> <mask> , int y ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); if (MetalUtils.isLeftToRight(slider)) { g.drawLine( TICK_BUFFER, y, TICK_BUFFER + (safeLength / 2), y ); } else { g.drawLine( 0, y, safeLength/2, y ); } } protected void paintMajorTickForVertSlider( Graphics g, Rectangle <mask> <mask> <mask> <mask> <mask> , int y ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); if (MetalUtils.isLeftToRight(slider)) { g.drawLine( TICK_BUFFER, y, TICK_BUFFER + safeLength, y ); } else { g.drawLine( 0, y, safeLength, y ); } } }
|
the * tick area for vertical sliders. BasicSliderUI uses the returned value to * determine the tick area rectangle. */ public int getTickLength() { return slider.getOrientation() == JSlider.HORIZONTAL ? safeLength + TICK_BUFFER + 1 : safeLength + TICK_BUFFER + 3; } /** * Returns the shorter dimension of the track. * * @return the shorter dimension of the track */ protected int getTrackWidth() { // This strange calculation is here to keep the // track in proportion to the thumb. final double kIdealTrackWidth = 7.0; final double kIdealThumbHeight = 16.0; final double kWidthScalar = kIdealTrackWidth / kIdealThumbHeight; if ( slider.getOrientation() == JSlider.HORIZONTAL ) { return (int)(kWidthScalar * thumbRect.height); } else { return (int)(kWidthScalar * thumbRect.width); } } /** * Returns the longer dimension of the slide bar. (The slide bar is only the * part that runs directly under the thumb) * * @return the longer dimension of the slide bar */ protected int getTrackLength() { if ( slider.getOrientation() == JSlider.HORIZONTAL ) { return trackRect.width; } return trackRect.height; } /** * Returns the amount that the thumb goes past the slide bar. * * @return the amount that the thumb goes past the slide bar */ protected int getThumbOverhang() { return (int)(getThumbSize().getHeight()-getTrackWidth())/2; } protected void scrollDueToClickInTrack( int dir ) { scrollByUnit( dir ); } protected void paintMinorTickForHorizSlider( Graphics g, Rectangle tickBounds , int x ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); g.drawLine( x, TICK_BUFFER, x, TICK_BUFFER + (safeLength / 2) ); } protected void paintMajorTickForHorizSlider( Graphics g, Rectangle tickBounds , int x ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); g.drawLine( x, TICK_BUFFER , x, TICK_BUFFER + (safeLength - 1) ); } protected void paintMinorTickForVertSlider( Graphics g, Rectangle tickBounds , int y ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); if (MetalUtils.isLeftToRight(slider)) { g.drawLine( TICK_BUFFER, y, TICK_BUFFER + (safeLength / 2), y ); } else { g.drawLine( 0, y, safeLength/2, y ); } } protected void paintMajorTickForVertSlider( Graphics g, Rectangle tickBounds , int y ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); if (MetalUtils.isLeftToRight(slider)) { g.drawLine( TICK_BUFFER, y, TICK_BUFFER + safeLength, y ); } else { g.drawLine( 0, y, safeLength, y ); } } }
|
java
|
TICK_BUFFER + 1 : safeLength + TICK_BUFFER + 3; } /** * Returns the shorter dimension of the track. * * @return the shorter dimension of the track */ protected int getTrackWidth() { // This strange calculation is here to keep the // track in proportion to the thumb. final double kIdealTrackWidth = 7.0; final double kIdealThumbHeight = 16.0; final double kWidthScalar = kIdealTrackWidth / kIdealThumbHeight; if ( slider.getOrientation() == JSlider.HORIZONTAL ) { return (int)(kWidthScalar * thumbRect.height); } else { return (int)(kWidthScalar * thumbRect.width); } } /** * Returns the longer dimension of the slide bar. (The slide bar is only the * part that runs directly under the thumb) * * @return the longer dimension of the slide bar */ protected int getTrackLength() { if ( slider.getOrientation() == JSlider.HORIZONTAL ) { return trackRect.width; } return trackRect.height; } /** * Returns the amount that the thumb goes past the slide bar. * * @return the amount that the thumb goes past the slide bar */ protected int getThumbOverhang() { return (int)(getThumbSize().getHeight()-getTrackWidth())/2; } protected void scrollDueToClickInTrack( int dir ) { scrollByUnit( dir ); } protected void paintMinorTickForHorizSlider( Graphics g, Rectangle <mask> <mask> <mask> <mask> <mask> , int x ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); g.drawLine( x, TICK_BUFFER, x, TICK_BUFFER + (safeLength / 2) ); } protected void paintMajorTickForHorizSlider( Graphics g, Rectangle <mask> <mask> <mask> <mask> <mask> , int x ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); g.drawLine( x, TICK_BUFFER , x, TICK_BUFFER + (safeLength - 1) ); } protected void paintMinorTickForVertSlider( Graphics g, Rectangle <mask> <mask> <mask> <mask> <mask> , int y ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); if (MetalUtils.isLeftToRight(slider)) { g.drawLine( TICK_BUFFER, y, TICK_BUFFER + (safeLength / 2), y ); } else { g.drawLine( 0, y, safeLength/2, y ); } } protected void paintMajorTickForVertSlider( Graphics g, Rectangle <mask> <mask> <mask> <mask> <mask> , int y ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); if (MetalUtils.isLeftToRight(slider)) { g.drawLine( TICK_BUFFER, y, TICK_BUFFER + safeLength, y ); } else { g.drawLine( 0, y, safeLength, y ); } } }
|
TICK_BUFFER + 1 : safeLength + TICK_BUFFER + 3; } /** * Returns the shorter dimension of the track. * * @return the shorter dimension of the track */ protected int getTrackWidth() { // This strange calculation is here to keep the // track in proportion to the thumb. final double kIdealTrackWidth = 7.0; final double kIdealThumbHeight = 16.0; final double kWidthScalar = kIdealTrackWidth / kIdealThumbHeight; if ( slider.getOrientation() == JSlider.HORIZONTAL ) { return (int)(kWidthScalar * thumbRect.height); } else { return (int)(kWidthScalar * thumbRect.width); } } /** * Returns the longer dimension of the slide bar. (The slide bar is only the * part that runs directly under the thumb) * * @return the longer dimension of the slide bar */ protected int getTrackLength() { if ( slider.getOrientation() == JSlider.HORIZONTAL ) { return trackRect.width; } return trackRect.height; } /** * Returns the amount that the thumb goes past the slide bar. * * @return the amount that the thumb goes past the slide bar */ protected int getThumbOverhang() { return (int)(getThumbSize().getHeight()-getTrackWidth())/2; } protected void scrollDueToClickInTrack( int dir ) { scrollByUnit( dir ); } protected void paintMinorTickForHorizSlider( Graphics g, Rectangle tickBounds , int x ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); g.drawLine( x, TICK_BUFFER, x, TICK_BUFFER + (safeLength / 2) ); } protected void paintMajorTickForHorizSlider( Graphics g, Rectangle tickBounds , int x ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); g.drawLine( x, TICK_BUFFER , x, TICK_BUFFER + (safeLength - 1) ); } protected void paintMinorTickForVertSlider( Graphics g, Rectangle tickBounds , int y ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); if (MetalUtils.isLeftToRight(slider)) { g.drawLine( TICK_BUFFER, y, TICK_BUFFER + (safeLength / 2), y ); } else { g.drawLine( 0, y, safeLength/2, y ); } } protected void paintMajorTickForVertSlider( Graphics g, Rectangle tickBounds , int y ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); if (MetalUtils.isLeftToRight(slider)) { g.drawLine( TICK_BUFFER, y, TICK_BUFFER + safeLength, y ); } else { g.drawLine( 0, y, safeLength, y ); } } }
|
java
|
track in proportion to the thumb. final double kIdealTrackWidth = 7.0; final double kIdealThumbHeight = 16.0; final double kWidthScalar = kIdealTrackWidth / kIdealThumbHeight; if ( slider.getOrientation() == JSlider.HORIZONTAL ) { return (int)(kWidthScalar * thumbRect.height); } else { return (int)(kWidthScalar * thumbRect.width); } } /** * Returns the longer dimension of the slide bar. (The slide bar is only the * part that runs directly under the thumb) * * @return the longer dimension of the slide bar */ protected int getTrackLength() { if ( slider.getOrientation() == JSlider.HORIZONTAL ) { return trackRect.width; } return trackRect.height; } /** * Returns the amount that the thumb goes past the slide bar. * * @return the amount that the thumb goes past the slide bar */ protected int getThumbOverhang() { return (int)(getThumbSize().getHeight()-getTrackWidth())/2; } protected void scrollDueToClickInTrack( int dir ) { scrollByUnit( dir ); } protected void paintMinorTickForHorizSlider( Graphics g, Rectangle <mask> <mask> <mask> <mask> <mask> , int x ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); g.drawLine( x, TICK_BUFFER, x, TICK_BUFFER + (safeLength / 2) ); } protected void paintMajorTickForHorizSlider( Graphics g, Rectangle <mask> <mask> <mask> <mask> <mask> , int x ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); g.drawLine( x, TICK_BUFFER , x, TICK_BUFFER + (safeLength - 1) ); } protected void paintMinorTickForVertSlider( Graphics g, Rectangle <mask> <mask> <mask> <mask> <mask> , int y ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); if (MetalUtils.isLeftToRight(slider)) { g.drawLine( TICK_BUFFER, y, TICK_BUFFER + (safeLength / 2), y ); } else { g.drawLine( 0, y, safeLength/2, y ); } } protected void paintMajorTickForVertSlider( Graphics g, Rectangle <mask> <mask> <mask> <mask> <mask> , int y ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); if (MetalUtils.isLeftToRight(slider)) { g.drawLine( TICK_BUFFER, y, TICK_BUFFER + safeLength, y ); } else { g.drawLine( 0, y, safeLength, y ); } } }
|
track in proportion to the thumb. final double kIdealTrackWidth = 7.0; final double kIdealThumbHeight = 16.0; final double kWidthScalar = kIdealTrackWidth / kIdealThumbHeight; if ( slider.getOrientation() == JSlider.HORIZONTAL ) { return (int)(kWidthScalar * thumbRect.height); } else { return (int)(kWidthScalar * thumbRect.width); } } /** * Returns the longer dimension of the slide bar. (The slide bar is only the * part that runs directly under the thumb) * * @return the longer dimension of the slide bar */ protected int getTrackLength() { if ( slider.getOrientation() == JSlider.HORIZONTAL ) { return trackRect.width; } return trackRect.height; } /** * Returns the amount that the thumb goes past the slide bar. * * @return the amount that the thumb goes past the slide bar */ protected int getThumbOverhang() { return (int)(getThumbSize().getHeight()-getTrackWidth())/2; } protected void scrollDueToClickInTrack( int dir ) { scrollByUnit( dir ); } protected void paintMinorTickForHorizSlider( Graphics g, Rectangle tickBounds , int x ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); g.drawLine( x, TICK_BUFFER, x, TICK_BUFFER + (safeLength / 2) ); } protected void paintMajorTickForHorizSlider( Graphics g, Rectangle tickBounds , int x ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); g.drawLine( x, TICK_BUFFER , x, TICK_BUFFER + (safeLength - 1) ); } protected void paintMinorTickForVertSlider( Graphics g, Rectangle tickBounds , int y ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); if (MetalUtils.isLeftToRight(slider)) { g.drawLine( TICK_BUFFER, y, TICK_BUFFER + (safeLength / 2), y ); } else { g.drawLine( 0, y, safeLength/2, y ); } } protected void paintMajorTickForVertSlider( Graphics g, Rectangle tickBounds , int y ) { g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() ); if (MetalUtils.isLeftToRight(slider)) { g.drawLine( TICK_BUFFER, y, TICK_BUFFER + safeLength, y ); } else { g.drawLine( 0, y, safeLength, y ); } } }
|
java
|
at all. config.setRevocationEndpoint(revocationEndpoint.toString()); config.setRevocationEndpointAuthMethodsSupported(getClientAuthMethodsSupported()); config.setRevocationEndpointAuthSigningAlgValuesSupported(getSupportedClientSigningAlgorithms(false)); config.setBackchannelLogoutSupported(true); config.setBackchannelLogoutSessionSupported(true); config.setBackchannelTokenDeliveryModesSupported(CibaConfig.CIBA_SUPPORTED_MODES); config.setBackchannelAuthenticationEndpoint(CibaGrantType.authorizationUrl(backendUriInfo.getBaseUriBuilder()).build(realm.getName()).toString()); config.setBackchannelAuthenticationRequestSigningAlgValuesSupported(getSupportedBackchannelAuthenticationRequestSigningAlgorithms()); config.setPushedAuthorizationRequestEndpoint(ParEndpoint.parUrl(backendUriInfo.getBaseUriBuilder()).build(realm.getName()).toString()); config.setRequirePushedAuthorizationRequests(Boolean.FALSE); MTLSEndpointAliases mtlsEndpointAliases = getMtlsEndpointAliases(config); config.setMtlsEndpointAliases(mtlsEndpointAliases); config.setAuthorizationResponseIssParameterSupported(true); config = checkConfigOverride(config); return config; } protected List<String> getPromptValuesSupported(RealmModel realm) { List<String> prompts = new ArrayList<>(DEFAULT_PROMPT_VALUES_SUPPORTED); if (realm.isRegistrationAllowed()) { prompts.add(OIDCLoginProtocol.PROMPT_VALUE_CREATE); } return prompts; } @Override public void close() { } private static List<String> list(String... values) { return Arrays.asList(values); } private List<String> getClientAuthMethodsSupported() { return session.getKeycloakSessionFactory().getProviderFactoriesStream(ClientAuthenticator.class) .map(ClientAuthenticatorFactory.class::cast) .map(caf -> caf.getProtocolAuthenticatorMethods(OIDCLoginProtocol.LOGIN_PROTOCOL)) .flatMap(Collection::stream) .collect(Collectors.toList()); } private List<String> getSupportedAlgorithms(Class<? extends Provider> clazz, boolean includeNone) { Stream<String> supportedAlgorithms = session.getKeycloakSessionFactory().getProviderFactoriesStream(clazz) .map(ProviderFactory::getId); if (includeNone) { supportedAlgorithms = Stream.concat(supportedAlgorithms, Stream.of("none")); } return supportedAlgorithms.collect(Collectors.toList()); } private List<String> getSupportedAsymmetricAlgorithms() { return getSupportedAlgorithms(SignatureProvider.class, false).stream() .map(algorithm -> new AbstractMap.SimpleEntry<>(algorithm, session.getProvider(SignatureProvider.class, algorithm))) .filter(entry -> entry.getValue() != null) .filter(entry -> entry.getValue().isAsymmetricAlgorithm()) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private List<String> getSupportedSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(SignatureProvider.class, includeNone); } private List<String> getSupportedClientSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(ClientSignatureVerifierProvider.class, includeNone); } private List<String> getSupportedContentEncryptionAlgorithms() { return getSupportedAlgorithms(ContentEncryptionProvider.class, false); } private List<String> getAcrValuesSupported(RealmModel realm) { // Values explicitly set on the realm mapping Map<String, Integer> realmAcrLoaMap = AcrUtils.getAcrLoaMap(realm); List<String> result = new ArrayList<>(realmAcrLoaMap.keySet()); // Add LoA levels configured in authentication flow in addition to the realm values result.addAll(LoAUtil.getLoAConfiguredInRealmBrowserFlow(realm) .map(String::valueOf) .collect(Collectors.toList())); return result; } private List<String> getSupportedEncryptionAlgorithms() { return getSupportedAlgorithms(CekManagementProvider.class, false); } private List<String> getSupportedBackchannelAuthenticationRequestSigningAlgorithms() { return getSupportedAsymmetricAlgorithms(); } private List<String> getSupportedEncryptionAlg(boolean includeNone) { return getSupportedAlgorithms(CekManagementProvider.class, includeNone); } private List<String> getSupportedEncryptionEnc(boolean includeNone) { return getSupportedAlgorithms(ContentEncryptionProvider.class, includeNone); } // Use protected method to make it easier to override in custom provider if different URLs are requested to be used as mtls_endpoint_aliases protected MTLSEndpointAliases getMtlsEndpointAliases(OIDCConfigurationRepresentation config) { MTLSEndpointAliases <mask> <mask> <mask> <mask> <mask> <mask> <mask> = new MTLSEndpointAliases(); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setTokenEndpoint(config.getTokenEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setRevocationEndpoint(config.getRevocationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setIntrospectionEndpoint(config.getIntrospectionEndpoint()); if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) { <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setDeviceAuthorizationEndpoint(config.getDeviceAuthorizationEndpoint()); } <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setRegistrationEndpoint(config.getRegistrationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setUserInfoEndpoint(config.getUserinfoEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setBackchannelAuthenticationEndpoint(config.getBackchannelAuthenticationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setPushedAuthorizationRequestEndpoint(config.getPushedAuthorizationRequestEndpoint()); return <mask> <mask> <mask> <mask> <mask> <mask> <mask> ; } private OIDCConfigurationRepresentation checkConfigOverride(OIDCConfigurationRepresentation config) { if (openidConfigOverride != null) { Map<String, Object> asMap = JsonSerialization.mapper.convertValue(config, Map.class); // Override configuration asMap.putAll(openidConfigOverride); return JsonSerialization.mapper.convertValue(asMap, OIDCConfigurationRepresentation.class); } else { return config; } } }
|
at all. config.setRevocationEndpoint(revocationEndpoint.toString()); config.setRevocationEndpointAuthMethodsSupported(getClientAuthMethodsSupported()); config.setRevocationEndpointAuthSigningAlgValuesSupported(getSupportedClientSigningAlgorithms(false)); config.setBackchannelLogoutSupported(true); config.setBackchannelLogoutSessionSupported(true); config.setBackchannelTokenDeliveryModesSupported(CibaConfig.CIBA_SUPPORTED_MODES); config.setBackchannelAuthenticationEndpoint(CibaGrantType.authorizationUrl(backendUriInfo.getBaseUriBuilder()).build(realm.getName()).toString()); config.setBackchannelAuthenticationRequestSigningAlgValuesSupported(getSupportedBackchannelAuthenticationRequestSigningAlgorithms()); config.setPushedAuthorizationRequestEndpoint(ParEndpoint.parUrl(backendUriInfo.getBaseUriBuilder()).build(realm.getName()).toString()); config.setRequirePushedAuthorizationRequests(Boolean.FALSE); MTLSEndpointAliases mtlsEndpointAliases = getMtlsEndpointAliases(config); config.setMtlsEndpointAliases(mtlsEndpointAliases); config.setAuthorizationResponseIssParameterSupported(true); config = checkConfigOverride(config); return config; } protected List<String> getPromptValuesSupported(RealmModel realm) { List<String> prompts = new ArrayList<>(DEFAULT_PROMPT_VALUES_SUPPORTED); if (realm.isRegistrationAllowed()) { prompts.add(OIDCLoginProtocol.PROMPT_VALUE_CREATE); } return prompts; } @Override public void close() { } private static List<String> list(String... values) { return Arrays.asList(values); } private List<String> getClientAuthMethodsSupported() { return session.getKeycloakSessionFactory().getProviderFactoriesStream(ClientAuthenticator.class) .map(ClientAuthenticatorFactory.class::cast) .map(caf -> caf.getProtocolAuthenticatorMethods(OIDCLoginProtocol.LOGIN_PROTOCOL)) .flatMap(Collection::stream) .collect(Collectors.toList()); } private List<String> getSupportedAlgorithms(Class<? extends Provider> clazz, boolean includeNone) { Stream<String> supportedAlgorithms = session.getKeycloakSessionFactory().getProviderFactoriesStream(clazz) .map(ProviderFactory::getId); if (includeNone) { supportedAlgorithms = Stream.concat(supportedAlgorithms, Stream.of("none")); } return supportedAlgorithms.collect(Collectors.toList()); } private List<String> getSupportedAsymmetricAlgorithms() { return getSupportedAlgorithms(SignatureProvider.class, false).stream() .map(algorithm -> new AbstractMap.SimpleEntry<>(algorithm, session.getProvider(SignatureProvider.class, algorithm))) .filter(entry -> entry.getValue() != null) .filter(entry -> entry.getValue().isAsymmetricAlgorithm()) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private List<String> getSupportedSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(SignatureProvider.class, includeNone); } private List<String> getSupportedClientSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(ClientSignatureVerifierProvider.class, includeNone); } private List<String> getSupportedContentEncryptionAlgorithms() { return getSupportedAlgorithms(ContentEncryptionProvider.class, false); } private List<String> getAcrValuesSupported(RealmModel realm) { // Values explicitly set on the realm mapping Map<String, Integer> realmAcrLoaMap = AcrUtils.getAcrLoaMap(realm); List<String> result = new ArrayList<>(realmAcrLoaMap.keySet()); // Add LoA levels configured in authentication flow in addition to the realm values result.addAll(LoAUtil.getLoAConfiguredInRealmBrowserFlow(realm) .map(String::valueOf) .collect(Collectors.toList())); return result; } private List<String> getSupportedEncryptionAlgorithms() { return getSupportedAlgorithms(CekManagementProvider.class, false); } private List<String> getSupportedBackchannelAuthenticationRequestSigningAlgorithms() { return getSupportedAsymmetricAlgorithms(); } private List<String> getSupportedEncryptionAlg(boolean includeNone) { return getSupportedAlgorithms(CekManagementProvider.class, includeNone); } private List<String> getSupportedEncryptionEnc(boolean includeNone) { return getSupportedAlgorithms(ContentEncryptionProvider.class, includeNone); } // Use protected method to make it easier to override in custom provider if different URLs are requested to be used as mtls_endpoint_aliases protected MTLSEndpointAliases getMtlsEndpointAliases(OIDCConfigurationRepresentation config) { MTLSEndpointAliases mtls_endpoints = new MTLSEndpointAliases(); mtls_endpoints .setTokenEndpoint(config.getTokenEndpoint()); mtls_endpoints .setRevocationEndpoint(config.getRevocationEndpoint()); mtls_endpoints .setIntrospectionEndpoint(config.getIntrospectionEndpoint()); if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) { mtls_endpoints .setDeviceAuthorizationEndpoint(config.getDeviceAuthorizationEndpoint()); } mtls_endpoints .setRegistrationEndpoint(config.getRegistrationEndpoint()); mtls_endpoints .setUserInfoEndpoint(config.getUserinfoEndpoint()); mtls_endpoints .setBackchannelAuthenticationEndpoint(config.getBackchannelAuthenticationEndpoint()); mtls_endpoints .setPushedAuthorizationRequestEndpoint(config.getPushedAuthorizationRequestEndpoint()); return mtls_endpoints ; } private OIDCConfigurationRepresentation checkConfigOverride(OIDCConfigurationRepresentation config) { if (openidConfigOverride != null) { Map<String, Object> asMap = JsonSerialization.mapper.convertValue(config, Map.class); // Override configuration asMap.putAll(openidConfigOverride); return JsonSerialization.mapper.convertValue(asMap, OIDCConfigurationRepresentation.class); } else { return config; } } }
|
java
|
config.setRevocationEndpointAuthSigningAlgValuesSupported(getSupportedClientSigningAlgorithms(false)); config.setBackchannelLogoutSupported(true); config.setBackchannelLogoutSessionSupported(true); config.setBackchannelTokenDeliveryModesSupported(CibaConfig.CIBA_SUPPORTED_MODES); config.setBackchannelAuthenticationEndpoint(CibaGrantType.authorizationUrl(backendUriInfo.getBaseUriBuilder()).build(realm.getName()).toString()); config.setBackchannelAuthenticationRequestSigningAlgValuesSupported(getSupportedBackchannelAuthenticationRequestSigningAlgorithms()); config.setPushedAuthorizationRequestEndpoint(ParEndpoint.parUrl(backendUriInfo.getBaseUriBuilder()).build(realm.getName()).toString()); config.setRequirePushedAuthorizationRequests(Boolean.FALSE); MTLSEndpointAliases mtlsEndpointAliases = getMtlsEndpointAliases(config); config.setMtlsEndpointAliases(mtlsEndpointAliases); config.setAuthorizationResponseIssParameterSupported(true); config = checkConfigOverride(config); return config; } protected List<String> getPromptValuesSupported(RealmModel realm) { List<String> prompts = new ArrayList<>(DEFAULT_PROMPT_VALUES_SUPPORTED); if (realm.isRegistrationAllowed()) { prompts.add(OIDCLoginProtocol.PROMPT_VALUE_CREATE); } return prompts; } @Override public void close() { } private static List<String> list(String... values) { return Arrays.asList(values); } private List<String> getClientAuthMethodsSupported() { return session.getKeycloakSessionFactory().getProviderFactoriesStream(ClientAuthenticator.class) .map(ClientAuthenticatorFactory.class::cast) .map(caf -> caf.getProtocolAuthenticatorMethods(OIDCLoginProtocol.LOGIN_PROTOCOL)) .flatMap(Collection::stream) .collect(Collectors.toList()); } private List<String> getSupportedAlgorithms(Class<? extends Provider> clazz, boolean includeNone) { Stream<String> supportedAlgorithms = session.getKeycloakSessionFactory().getProviderFactoriesStream(clazz) .map(ProviderFactory::getId); if (includeNone) { supportedAlgorithms = Stream.concat(supportedAlgorithms, Stream.of("none")); } return supportedAlgorithms.collect(Collectors.toList()); } private List<String> getSupportedAsymmetricAlgorithms() { return getSupportedAlgorithms(SignatureProvider.class, false).stream() .map(algorithm -> new AbstractMap.SimpleEntry<>(algorithm, session.getProvider(SignatureProvider.class, algorithm))) .filter(entry -> entry.getValue() != null) .filter(entry -> entry.getValue().isAsymmetricAlgorithm()) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private List<String> getSupportedSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(SignatureProvider.class, includeNone); } private List<String> getSupportedClientSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(ClientSignatureVerifierProvider.class, includeNone); } private List<String> getSupportedContentEncryptionAlgorithms() { return getSupportedAlgorithms(ContentEncryptionProvider.class, false); } private List<String> getAcrValuesSupported(RealmModel realm) { // Values explicitly set on the realm mapping Map<String, Integer> realmAcrLoaMap = AcrUtils.getAcrLoaMap(realm); List<String> result = new ArrayList<>(realmAcrLoaMap.keySet()); // Add LoA levels configured in authentication flow in addition to the realm values result.addAll(LoAUtil.getLoAConfiguredInRealmBrowserFlow(realm) .map(String::valueOf) .collect(Collectors.toList())); return result; } private List<String> getSupportedEncryptionAlgorithms() { return getSupportedAlgorithms(CekManagementProvider.class, false); } private List<String> getSupportedBackchannelAuthenticationRequestSigningAlgorithms() { return getSupportedAsymmetricAlgorithms(); } private List<String> getSupportedEncryptionAlg(boolean includeNone) { return getSupportedAlgorithms(CekManagementProvider.class, includeNone); } private List<String> getSupportedEncryptionEnc(boolean includeNone) { return getSupportedAlgorithms(ContentEncryptionProvider.class, includeNone); } // Use protected method to make it easier to override in custom provider if different URLs are requested to be used as mtls_endpoint_aliases protected MTLSEndpointAliases getMtlsEndpointAliases(OIDCConfigurationRepresentation config) { MTLSEndpointAliases <mask> <mask> <mask> <mask> <mask> <mask> <mask> = new MTLSEndpointAliases(); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setTokenEndpoint(config.getTokenEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setRevocationEndpoint(config.getRevocationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setIntrospectionEndpoint(config.getIntrospectionEndpoint()); if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) { <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setDeviceAuthorizationEndpoint(config.getDeviceAuthorizationEndpoint()); } <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setRegistrationEndpoint(config.getRegistrationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setUserInfoEndpoint(config.getUserinfoEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setBackchannelAuthenticationEndpoint(config.getBackchannelAuthenticationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setPushedAuthorizationRequestEndpoint(config.getPushedAuthorizationRequestEndpoint()); return <mask> <mask> <mask> <mask> <mask> <mask> <mask> ; } private OIDCConfigurationRepresentation checkConfigOverride(OIDCConfigurationRepresentation config) { if (openidConfigOverride != null) { Map<String, Object> asMap = JsonSerialization.mapper.convertValue(config, Map.class); // Override configuration asMap.putAll(openidConfigOverride); return JsonSerialization.mapper.convertValue(asMap, OIDCConfigurationRepresentation.class); } else { return config; } } }
|
config.setRevocationEndpointAuthSigningAlgValuesSupported(getSupportedClientSigningAlgorithms(false)); config.setBackchannelLogoutSupported(true); config.setBackchannelLogoutSessionSupported(true); config.setBackchannelTokenDeliveryModesSupported(CibaConfig.CIBA_SUPPORTED_MODES); config.setBackchannelAuthenticationEndpoint(CibaGrantType.authorizationUrl(backendUriInfo.getBaseUriBuilder()).build(realm.getName()).toString()); config.setBackchannelAuthenticationRequestSigningAlgValuesSupported(getSupportedBackchannelAuthenticationRequestSigningAlgorithms()); config.setPushedAuthorizationRequestEndpoint(ParEndpoint.parUrl(backendUriInfo.getBaseUriBuilder()).build(realm.getName()).toString()); config.setRequirePushedAuthorizationRequests(Boolean.FALSE); MTLSEndpointAliases mtlsEndpointAliases = getMtlsEndpointAliases(config); config.setMtlsEndpointAliases(mtlsEndpointAliases); config.setAuthorizationResponseIssParameterSupported(true); config = checkConfigOverride(config); return config; } protected List<String> getPromptValuesSupported(RealmModel realm) { List<String> prompts = new ArrayList<>(DEFAULT_PROMPT_VALUES_SUPPORTED); if (realm.isRegistrationAllowed()) { prompts.add(OIDCLoginProtocol.PROMPT_VALUE_CREATE); } return prompts; } @Override public void close() { } private static List<String> list(String... values) { return Arrays.asList(values); } private List<String> getClientAuthMethodsSupported() { return session.getKeycloakSessionFactory().getProviderFactoriesStream(ClientAuthenticator.class) .map(ClientAuthenticatorFactory.class::cast) .map(caf -> caf.getProtocolAuthenticatorMethods(OIDCLoginProtocol.LOGIN_PROTOCOL)) .flatMap(Collection::stream) .collect(Collectors.toList()); } private List<String> getSupportedAlgorithms(Class<? extends Provider> clazz, boolean includeNone) { Stream<String> supportedAlgorithms = session.getKeycloakSessionFactory().getProviderFactoriesStream(clazz) .map(ProviderFactory::getId); if (includeNone) { supportedAlgorithms = Stream.concat(supportedAlgorithms, Stream.of("none")); } return supportedAlgorithms.collect(Collectors.toList()); } private List<String> getSupportedAsymmetricAlgorithms() { return getSupportedAlgorithms(SignatureProvider.class, false).stream() .map(algorithm -> new AbstractMap.SimpleEntry<>(algorithm, session.getProvider(SignatureProvider.class, algorithm))) .filter(entry -> entry.getValue() != null) .filter(entry -> entry.getValue().isAsymmetricAlgorithm()) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private List<String> getSupportedSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(SignatureProvider.class, includeNone); } private List<String> getSupportedClientSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(ClientSignatureVerifierProvider.class, includeNone); } private List<String> getSupportedContentEncryptionAlgorithms() { return getSupportedAlgorithms(ContentEncryptionProvider.class, false); } private List<String> getAcrValuesSupported(RealmModel realm) { // Values explicitly set on the realm mapping Map<String, Integer> realmAcrLoaMap = AcrUtils.getAcrLoaMap(realm); List<String> result = new ArrayList<>(realmAcrLoaMap.keySet()); // Add LoA levels configured in authentication flow in addition to the realm values result.addAll(LoAUtil.getLoAConfiguredInRealmBrowserFlow(realm) .map(String::valueOf) .collect(Collectors.toList())); return result; } private List<String> getSupportedEncryptionAlgorithms() { return getSupportedAlgorithms(CekManagementProvider.class, false); } private List<String> getSupportedBackchannelAuthenticationRequestSigningAlgorithms() { return getSupportedAsymmetricAlgorithms(); } private List<String> getSupportedEncryptionAlg(boolean includeNone) { return getSupportedAlgorithms(CekManagementProvider.class, includeNone); } private List<String> getSupportedEncryptionEnc(boolean includeNone) { return getSupportedAlgorithms(ContentEncryptionProvider.class, includeNone); } // Use protected method to make it easier to override in custom provider if different URLs are requested to be used as mtls_endpoint_aliases protected MTLSEndpointAliases getMtlsEndpointAliases(OIDCConfigurationRepresentation config) { MTLSEndpointAliases mtls_endpoints = new MTLSEndpointAliases(); mtls_endpoints .setTokenEndpoint(config.getTokenEndpoint()); mtls_endpoints .setRevocationEndpoint(config.getRevocationEndpoint()); mtls_endpoints .setIntrospectionEndpoint(config.getIntrospectionEndpoint()); if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) { mtls_endpoints .setDeviceAuthorizationEndpoint(config.getDeviceAuthorizationEndpoint()); } mtls_endpoints .setRegistrationEndpoint(config.getRegistrationEndpoint()); mtls_endpoints .setUserInfoEndpoint(config.getUserinfoEndpoint()); mtls_endpoints .setBackchannelAuthenticationEndpoint(config.getBackchannelAuthenticationEndpoint()); mtls_endpoints .setPushedAuthorizationRequestEndpoint(config.getPushedAuthorizationRequestEndpoint()); return mtls_endpoints ; } private OIDCConfigurationRepresentation checkConfigOverride(OIDCConfigurationRepresentation config) { if (openidConfigOverride != null) { Map<String, Object> asMap = JsonSerialization.mapper.convertValue(config, Map.class); // Override configuration asMap.putAll(openidConfigOverride); return JsonSerialization.mapper.convertValue(asMap, OIDCConfigurationRepresentation.class); } else { return config; } } }
|
java
|
config.setBackchannelLogoutSessionSupported(true); config.setBackchannelTokenDeliveryModesSupported(CibaConfig.CIBA_SUPPORTED_MODES); config.setBackchannelAuthenticationEndpoint(CibaGrantType.authorizationUrl(backendUriInfo.getBaseUriBuilder()).build(realm.getName()).toString()); config.setBackchannelAuthenticationRequestSigningAlgValuesSupported(getSupportedBackchannelAuthenticationRequestSigningAlgorithms()); config.setPushedAuthorizationRequestEndpoint(ParEndpoint.parUrl(backendUriInfo.getBaseUriBuilder()).build(realm.getName()).toString()); config.setRequirePushedAuthorizationRequests(Boolean.FALSE); MTLSEndpointAliases mtlsEndpointAliases = getMtlsEndpointAliases(config); config.setMtlsEndpointAliases(mtlsEndpointAliases); config.setAuthorizationResponseIssParameterSupported(true); config = checkConfigOverride(config); return config; } protected List<String> getPromptValuesSupported(RealmModel realm) { List<String> prompts = new ArrayList<>(DEFAULT_PROMPT_VALUES_SUPPORTED); if (realm.isRegistrationAllowed()) { prompts.add(OIDCLoginProtocol.PROMPT_VALUE_CREATE); } return prompts; } @Override public void close() { } private static List<String> list(String... values) { return Arrays.asList(values); } private List<String> getClientAuthMethodsSupported() { return session.getKeycloakSessionFactory().getProviderFactoriesStream(ClientAuthenticator.class) .map(ClientAuthenticatorFactory.class::cast) .map(caf -> caf.getProtocolAuthenticatorMethods(OIDCLoginProtocol.LOGIN_PROTOCOL)) .flatMap(Collection::stream) .collect(Collectors.toList()); } private List<String> getSupportedAlgorithms(Class<? extends Provider> clazz, boolean includeNone) { Stream<String> supportedAlgorithms = session.getKeycloakSessionFactory().getProviderFactoriesStream(clazz) .map(ProviderFactory::getId); if (includeNone) { supportedAlgorithms = Stream.concat(supportedAlgorithms, Stream.of("none")); } return supportedAlgorithms.collect(Collectors.toList()); } private List<String> getSupportedAsymmetricAlgorithms() { return getSupportedAlgorithms(SignatureProvider.class, false).stream() .map(algorithm -> new AbstractMap.SimpleEntry<>(algorithm, session.getProvider(SignatureProvider.class, algorithm))) .filter(entry -> entry.getValue() != null) .filter(entry -> entry.getValue().isAsymmetricAlgorithm()) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private List<String> getSupportedSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(SignatureProvider.class, includeNone); } private List<String> getSupportedClientSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(ClientSignatureVerifierProvider.class, includeNone); } private List<String> getSupportedContentEncryptionAlgorithms() { return getSupportedAlgorithms(ContentEncryptionProvider.class, false); } private List<String> getAcrValuesSupported(RealmModel realm) { // Values explicitly set on the realm mapping Map<String, Integer> realmAcrLoaMap = AcrUtils.getAcrLoaMap(realm); List<String> result = new ArrayList<>(realmAcrLoaMap.keySet()); // Add LoA levels configured in authentication flow in addition to the realm values result.addAll(LoAUtil.getLoAConfiguredInRealmBrowserFlow(realm) .map(String::valueOf) .collect(Collectors.toList())); return result; } private List<String> getSupportedEncryptionAlgorithms() { return getSupportedAlgorithms(CekManagementProvider.class, false); } private List<String> getSupportedBackchannelAuthenticationRequestSigningAlgorithms() { return getSupportedAsymmetricAlgorithms(); } private List<String> getSupportedEncryptionAlg(boolean includeNone) { return getSupportedAlgorithms(CekManagementProvider.class, includeNone); } private List<String> getSupportedEncryptionEnc(boolean includeNone) { return getSupportedAlgorithms(ContentEncryptionProvider.class, includeNone); } // Use protected method to make it easier to override in custom provider if different URLs are requested to be used as mtls_endpoint_aliases protected MTLSEndpointAliases getMtlsEndpointAliases(OIDCConfigurationRepresentation config) { MTLSEndpointAliases <mask> <mask> <mask> <mask> <mask> <mask> <mask> = new MTLSEndpointAliases(); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setTokenEndpoint(config.getTokenEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setRevocationEndpoint(config.getRevocationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setIntrospectionEndpoint(config.getIntrospectionEndpoint()); if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) { <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setDeviceAuthorizationEndpoint(config.getDeviceAuthorizationEndpoint()); } <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setRegistrationEndpoint(config.getRegistrationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setUserInfoEndpoint(config.getUserinfoEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setBackchannelAuthenticationEndpoint(config.getBackchannelAuthenticationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setPushedAuthorizationRequestEndpoint(config.getPushedAuthorizationRequestEndpoint()); return <mask> <mask> <mask> <mask> <mask> <mask> <mask> ; } private OIDCConfigurationRepresentation checkConfigOverride(OIDCConfigurationRepresentation config) { if (openidConfigOverride != null) { Map<String, Object> asMap = JsonSerialization.mapper.convertValue(config, Map.class); // Override configuration asMap.putAll(openidConfigOverride); return JsonSerialization.mapper.convertValue(asMap, OIDCConfigurationRepresentation.class); } else { return config; } } }
|
config.setBackchannelLogoutSessionSupported(true); config.setBackchannelTokenDeliveryModesSupported(CibaConfig.CIBA_SUPPORTED_MODES); config.setBackchannelAuthenticationEndpoint(CibaGrantType.authorizationUrl(backendUriInfo.getBaseUriBuilder()).build(realm.getName()).toString()); config.setBackchannelAuthenticationRequestSigningAlgValuesSupported(getSupportedBackchannelAuthenticationRequestSigningAlgorithms()); config.setPushedAuthorizationRequestEndpoint(ParEndpoint.parUrl(backendUriInfo.getBaseUriBuilder()).build(realm.getName()).toString()); config.setRequirePushedAuthorizationRequests(Boolean.FALSE); MTLSEndpointAliases mtlsEndpointAliases = getMtlsEndpointAliases(config); config.setMtlsEndpointAliases(mtlsEndpointAliases); config.setAuthorizationResponseIssParameterSupported(true); config = checkConfigOverride(config); return config; } protected List<String> getPromptValuesSupported(RealmModel realm) { List<String> prompts = new ArrayList<>(DEFAULT_PROMPT_VALUES_SUPPORTED); if (realm.isRegistrationAllowed()) { prompts.add(OIDCLoginProtocol.PROMPT_VALUE_CREATE); } return prompts; } @Override public void close() { } private static List<String> list(String... values) { return Arrays.asList(values); } private List<String> getClientAuthMethodsSupported() { return session.getKeycloakSessionFactory().getProviderFactoriesStream(ClientAuthenticator.class) .map(ClientAuthenticatorFactory.class::cast) .map(caf -> caf.getProtocolAuthenticatorMethods(OIDCLoginProtocol.LOGIN_PROTOCOL)) .flatMap(Collection::stream) .collect(Collectors.toList()); } private List<String> getSupportedAlgorithms(Class<? extends Provider> clazz, boolean includeNone) { Stream<String> supportedAlgorithms = session.getKeycloakSessionFactory().getProviderFactoriesStream(clazz) .map(ProviderFactory::getId); if (includeNone) { supportedAlgorithms = Stream.concat(supportedAlgorithms, Stream.of("none")); } return supportedAlgorithms.collect(Collectors.toList()); } private List<String> getSupportedAsymmetricAlgorithms() { return getSupportedAlgorithms(SignatureProvider.class, false).stream() .map(algorithm -> new AbstractMap.SimpleEntry<>(algorithm, session.getProvider(SignatureProvider.class, algorithm))) .filter(entry -> entry.getValue() != null) .filter(entry -> entry.getValue().isAsymmetricAlgorithm()) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private List<String> getSupportedSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(SignatureProvider.class, includeNone); } private List<String> getSupportedClientSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(ClientSignatureVerifierProvider.class, includeNone); } private List<String> getSupportedContentEncryptionAlgorithms() { return getSupportedAlgorithms(ContentEncryptionProvider.class, false); } private List<String> getAcrValuesSupported(RealmModel realm) { // Values explicitly set on the realm mapping Map<String, Integer> realmAcrLoaMap = AcrUtils.getAcrLoaMap(realm); List<String> result = new ArrayList<>(realmAcrLoaMap.keySet()); // Add LoA levels configured in authentication flow in addition to the realm values result.addAll(LoAUtil.getLoAConfiguredInRealmBrowserFlow(realm) .map(String::valueOf) .collect(Collectors.toList())); return result; } private List<String> getSupportedEncryptionAlgorithms() { return getSupportedAlgorithms(CekManagementProvider.class, false); } private List<String> getSupportedBackchannelAuthenticationRequestSigningAlgorithms() { return getSupportedAsymmetricAlgorithms(); } private List<String> getSupportedEncryptionAlg(boolean includeNone) { return getSupportedAlgorithms(CekManagementProvider.class, includeNone); } private List<String> getSupportedEncryptionEnc(boolean includeNone) { return getSupportedAlgorithms(ContentEncryptionProvider.class, includeNone); } // Use protected method to make it easier to override in custom provider if different URLs are requested to be used as mtls_endpoint_aliases protected MTLSEndpointAliases getMtlsEndpointAliases(OIDCConfigurationRepresentation config) { MTLSEndpointAliases mtls_endpoints = new MTLSEndpointAliases(); mtls_endpoints .setTokenEndpoint(config.getTokenEndpoint()); mtls_endpoints .setRevocationEndpoint(config.getRevocationEndpoint()); mtls_endpoints .setIntrospectionEndpoint(config.getIntrospectionEndpoint()); if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) { mtls_endpoints .setDeviceAuthorizationEndpoint(config.getDeviceAuthorizationEndpoint()); } mtls_endpoints .setRegistrationEndpoint(config.getRegistrationEndpoint()); mtls_endpoints .setUserInfoEndpoint(config.getUserinfoEndpoint()); mtls_endpoints .setBackchannelAuthenticationEndpoint(config.getBackchannelAuthenticationEndpoint()); mtls_endpoints .setPushedAuthorizationRequestEndpoint(config.getPushedAuthorizationRequestEndpoint()); return mtls_endpoints ; } private OIDCConfigurationRepresentation checkConfigOverride(OIDCConfigurationRepresentation config) { if (openidConfigOverride != null) { Map<String, Object> asMap = JsonSerialization.mapper.convertValue(config, Map.class); // Override configuration asMap.putAll(openidConfigOverride); return JsonSerialization.mapper.convertValue(asMap, OIDCConfigurationRepresentation.class); } else { return config; } } }
|
java
|
config.setBackchannelAuthenticationEndpoint(CibaGrantType.authorizationUrl(backendUriInfo.getBaseUriBuilder()).build(realm.getName()).toString()); config.setBackchannelAuthenticationRequestSigningAlgValuesSupported(getSupportedBackchannelAuthenticationRequestSigningAlgorithms()); config.setPushedAuthorizationRequestEndpoint(ParEndpoint.parUrl(backendUriInfo.getBaseUriBuilder()).build(realm.getName()).toString()); config.setRequirePushedAuthorizationRequests(Boolean.FALSE); MTLSEndpointAliases mtlsEndpointAliases = getMtlsEndpointAliases(config); config.setMtlsEndpointAliases(mtlsEndpointAliases); config.setAuthorizationResponseIssParameterSupported(true); config = checkConfigOverride(config); return config; } protected List<String> getPromptValuesSupported(RealmModel realm) { List<String> prompts = new ArrayList<>(DEFAULT_PROMPT_VALUES_SUPPORTED); if (realm.isRegistrationAllowed()) { prompts.add(OIDCLoginProtocol.PROMPT_VALUE_CREATE); } return prompts; } @Override public void close() { } private static List<String> list(String... values) { return Arrays.asList(values); } private List<String> getClientAuthMethodsSupported() { return session.getKeycloakSessionFactory().getProviderFactoriesStream(ClientAuthenticator.class) .map(ClientAuthenticatorFactory.class::cast) .map(caf -> caf.getProtocolAuthenticatorMethods(OIDCLoginProtocol.LOGIN_PROTOCOL)) .flatMap(Collection::stream) .collect(Collectors.toList()); } private List<String> getSupportedAlgorithms(Class<? extends Provider> clazz, boolean includeNone) { Stream<String> supportedAlgorithms = session.getKeycloakSessionFactory().getProviderFactoriesStream(clazz) .map(ProviderFactory::getId); if (includeNone) { supportedAlgorithms = Stream.concat(supportedAlgorithms, Stream.of("none")); } return supportedAlgorithms.collect(Collectors.toList()); } private List<String> getSupportedAsymmetricAlgorithms() { return getSupportedAlgorithms(SignatureProvider.class, false).stream() .map(algorithm -> new AbstractMap.SimpleEntry<>(algorithm, session.getProvider(SignatureProvider.class, algorithm))) .filter(entry -> entry.getValue() != null) .filter(entry -> entry.getValue().isAsymmetricAlgorithm()) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private List<String> getSupportedSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(SignatureProvider.class, includeNone); } private List<String> getSupportedClientSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(ClientSignatureVerifierProvider.class, includeNone); } private List<String> getSupportedContentEncryptionAlgorithms() { return getSupportedAlgorithms(ContentEncryptionProvider.class, false); } private List<String> getAcrValuesSupported(RealmModel realm) { // Values explicitly set on the realm mapping Map<String, Integer> realmAcrLoaMap = AcrUtils.getAcrLoaMap(realm); List<String> result = new ArrayList<>(realmAcrLoaMap.keySet()); // Add LoA levels configured in authentication flow in addition to the realm values result.addAll(LoAUtil.getLoAConfiguredInRealmBrowserFlow(realm) .map(String::valueOf) .collect(Collectors.toList())); return result; } private List<String> getSupportedEncryptionAlgorithms() { return getSupportedAlgorithms(CekManagementProvider.class, false); } private List<String> getSupportedBackchannelAuthenticationRequestSigningAlgorithms() { return getSupportedAsymmetricAlgorithms(); } private List<String> getSupportedEncryptionAlg(boolean includeNone) { return getSupportedAlgorithms(CekManagementProvider.class, includeNone); } private List<String> getSupportedEncryptionEnc(boolean includeNone) { return getSupportedAlgorithms(ContentEncryptionProvider.class, includeNone); } // Use protected method to make it easier to override in custom provider if different URLs are requested to be used as mtls_endpoint_aliases protected MTLSEndpointAliases getMtlsEndpointAliases(OIDCConfigurationRepresentation config) { MTLSEndpointAliases <mask> <mask> <mask> <mask> <mask> <mask> <mask> = new MTLSEndpointAliases(); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setTokenEndpoint(config.getTokenEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setRevocationEndpoint(config.getRevocationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setIntrospectionEndpoint(config.getIntrospectionEndpoint()); if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) { <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setDeviceAuthorizationEndpoint(config.getDeviceAuthorizationEndpoint()); } <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setRegistrationEndpoint(config.getRegistrationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setUserInfoEndpoint(config.getUserinfoEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setBackchannelAuthenticationEndpoint(config.getBackchannelAuthenticationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setPushedAuthorizationRequestEndpoint(config.getPushedAuthorizationRequestEndpoint()); return <mask> <mask> <mask> <mask> <mask> <mask> <mask> ; } private OIDCConfigurationRepresentation checkConfigOverride(OIDCConfigurationRepresentation config) { if (openidConfigOverride != null) { Map<String, Object> asMap = JsonSerialization.mapper.convertValue(config, Map.class); // Override configuration asMap.putAll(openidConfigOverride); return JsonSerialization.mapper.convertValue(asMap, OIDCConfigurationRepresentation.class); } else { return config; } } }
|
config.setBackchannelAuthenticationEndpoint(CibaGrantType.authorizationUrl(backendUriInfo.getBaseUriBuilder()).build(realm.getName()).toString()); config.setBackchannelAuthenticationRequestSigningAlgValuesSupported(getSupportedBackchannelAuthenticationRequestSigningAlgorithms()); config.setPushedAuthorizationRequestEndpoint(ParEndpoint.parUrl(backendUriInfo.getBaseUriBuilder()).build(realm.getName()).toString()); config.setRequirePushedAuthorizationRequests(Boolean.FALSE); MTLSEndpointAliases mtlsEndpointAliases = getMtlsEndpointAliases(config); config.setMtlsEndpointAliases(mtlsEndpointAliases); config.setAuthorizationResponseIssParameterSupported(true); config = checkConfigOverride(config); return config; } protected List<String> getPromptValuesSupported(RealmModel realm) { List<String> prompts = new ArrayList<>(DEFAULT_PROMPT_VALUES_SUPPORTED); if (realm.isRegistrationAllowed()) { prompts.add(OIDCLoginProtocol.PROMPT_VALUE_CREATE); } return prompts; } @Override public void close() { } private static List<String> list(String... values) { return Arrays.asList(values); } private List<String> getClientAuthMethodsSupported() { return session.getKeycloakSessionFactory().getProviderFactoriesStream(ClientAuthenticator.class) .map(ClientAuthenticatorFactory.class::cast) .map(caf -> caf.getProtocolAuthenticatorMethods(OIDCLoginProtocol.LOGIN_PROTOCOL)) .flatMap(Collection::stream) .collect(Collectors.toList()); } private List<String> getSupportedAlgorithms(Class<? extends Provider> clazz, boolean includeNone) { Stream<String> supportedAlgorithms = session.getKeycloakSessionFactory().getProviderFactoriesStream(clazz) .map(ProviderFactory::getId); if (includeNone) { supportedAlgorithms = Stream.concat(supportedAlgorithms, Stream.of("none")); } return supportedAlgorithms.collect(Collectors.toList()); } private List<String> getSupportedAsymmetricAlgorithms() { return getSupportedAlgorithms(SignatureProvider.class, false).stream() .map(algorithm -> new AbstractMap.SimpleEntry<>(algorithm, session.getProvider(SignatureProvider.class, algorithm))) .filter(entry -> entry.getValue() != null) .filter(entry -> entry.getValue().isAsymmetricAlgorithm()) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private List<String> getSupportedSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(SignatureProvider.class, includeNone); } private List<String> getSupportedClientSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(ClientSignatureVerifierProvider.class, includeNone); } private List<String> getSupportedContentEncryptionAlgorithms() { return getSupportedAlgorithms(ContentEncryptionProvider.class, false); } private List<String> getAcrValuesSupported(RealmModel realm) { // Values explicitly set on the realm mapping Map<String, Integer> realmAcrLoaMap = AcrUtils.getAcrLoaMap(realm); List<String> result = new ArrayList<>(realmAcrLoaMap.keySet()); // Add LoA levels configured in authentication flow in addition to the realm values result.addAll(LoAUtil.getLoAConfiguredInRealmBrowserFlow(realm) .map(String::valueOf) .collect(Collectors.toList())); return result; } private List<String> getSupportedEncryptionAlgorithms() { return getSupportedAlgorithms(CekManagementProvider.class, false); } private List<String> getSupportedBackchannelAuthenticationRequestSigningAlgorithms() { return getSupportedAsymmetricAlgorithms(); } private List<String> getSupportedEncryptionAlg(boolean includeNone) { return getSupportedAlgorithms(CekManagementProvider.class, includeNone); } private List<String> getSupportedEncryptionEnc(boolean includeNone) { return getSupportedAlgorithms(ContentEncryptionProvider.class, includeNone); } // Use protected method to make it easier to override in custom provider if different URLs are requested to be used as mtls_endpoint_aliases protected MTLSEndpointAliases getMtlsEndpointAliases(OIDCConfigurationRepresentation config) { MTLSEndpointAliases mtls_endpoints = new MTLSEndpointAliases(); mtls_endpoints .setTokenEndpoint(config.getTokenEndpoint()); mtls_endpoints .setRevocationEndpoint(config.getRevocationEndpoint()); mtls_endpoints .setIntrospectionEndpoint(config.getIntrospectionEndpoint()); if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) { mtls_endpoints .setDeviceAuthorizationEndpoint(config.getDeviceAuthorizationEndpoint()); } mtls_endpoints .setRegistrationEndpoint(config.getRegistrationEndpoint()); mtls_endpoints .setUserInfoEndpoint(config.getUserinfoEndpoint()); mtls_endpoints .setBackchannelAuthenticationEndpoint(config.getBackchannelAuthenticationEndpoint()); mtls_endpoints .setPushedAuthorizationRequestEndpoint(config.getPushedAuthorizationRequestEndpoint()); return mtls_endpoints ; } private OIDCConfigurationRepresentation checkConfigOverride(OIDCConfigurationRepresentation config) { if (openidConfigOverride != null) { Map<String, Object> asMap = JsonSerialization.mapper.convertValue(config, Map.class); // Override configuration asMap.putAll(openidConfigOverride); return JsonSerialization.mapper.convertValue(asMap, OIDCConfigurationRepresentation.class); } else { return config; } } }
|
java
|
mtlsEndpointAliases = getMtlsEndpointAliases(config); config.setMtlsEndpointAliases(mtlsEndpointAliases); config.setAuthorizationResponseIssParameterSupported(true); config = checkConfigOverride(config); return config; } protected List<String> getPromptValuesSupported(RealmModel realm) { List<String> prompts = new ArrayList<>(DEFAULT_PROMPT_VALUES_SUPPORTED); if (realm.isRegistrationAllowed()) { prompts.add(OIDCLoginProtocol.PROMPT_VALUE_CREATE); } return prompts; } @Override public void close() { } private static List<String> list(String... values) { return Arrays.asList(values); } private List<String> getClientAuthMethodsSupported() { return session.getKeycloakSessionFactory().getProviderFactoriesStream(ClientAuthenticator.class) .map(ClientAuthenticatorFactory.class::cast) .map(caf -> caf.getProtocolAuthenticatorMethods(OIDCLoginProtocol.LOGIN_PROTOCOL)) .flatMap(Collection::stream) .collect(Collectors.toList()); } private List<String> getSupportedAlgorithms(Class<? extends Provider> clazz, boolean includeNone) { Stream<String> supportedAlgorithms = session.getKeycloakSessionFactory().getProviderFactoriesStream(clazz) .map(ProviderFactory::getId); if (includeNone) { supportedAlgorithms = Stream.concat(supportedAlgorithms, Stream.of("none")); } return supportedAlgorithms.collect(Collectors.toList()); } private List<String> getSupportedAsymmetricAlgorithms() { return getSupportedAlgorithms(SignatureProvider.class, false).stream() .map(algorithm -> new AbstractMap.SimpleEntry<>(algorithm, session.getProvider(SignatureProvider.class, algorithm))) .filter(entry -> entry.getValue() != null) .filter(entry -> entry.getValue().isAsymmetricAlgorithm()) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private List<String> getSupportedSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(SignatureProvider.class, includeNone); } private List<String> getSupportedClientSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(ClientSignatureVerifierProvider.class, includeNone); } private List<String> getSupportedContentEncryptionAlgorithms() { return getSupportedAlgorithms(ContentEncryptionProvider.class, false); } private List<String> getAcrValuesSupported(RealmModel realm) { // Values explicitly set on the realm mapping Map<String, Integer> realmAcrLoaMap = AcrUtils.getAcrLoaMap(realm); List<String> result = new ArrayList<>(realmAcrLoaMap.keySet()); // Add LoA levels configured in authentication flow in addition to the realm values result.addAll(LoAUtil.getLoAConfiguredInRealmBrowserFlow(realm) .map(String::valueOf) .collect(Collectors.toList())); return result; } private List<String> getSupportedEncryptionAlgorithms() { return getSupportedAlgorithms(CekManagementProvider.class, false); } private List<String> getSupportedBackchannelAuthenticationRequestSigningAlgorithms() { return getSupportedAsymmetricAlgorithms(); } private List<String> getSupportedEncryptionAlg(boolean includeNone) { return getSupportedAlgorithms(CekManagementProvider.class, includeNone); } private List<String> getSupportedEncryptionEnc(boolean includeNone) { return getSupportedAlgorithms(ContentEncryptionProvider.class, includeNone); } // Use protected method to make it easier to override in custom provider if different URLs are requested to be used as mtls_endpoint_aliases protected MTLSEndpointAliases getMtlsEndpointAliases(OIDCConfigurationRepresentation config) { MTLSEndpointAliases <mask> <mask> <mask> <mask> <mask> <mask> <mask> = new MTLSEndpointAliases(); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setTokenEndpoint(config.getTokenEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setRevocationEndpoint(config.getRevocationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setIntrospectionEndpoint(config.getIntrospectionEndpoint()); if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) { <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setDeviceAuthorizationEndpoint(config.getDeviceAuthorizationEndpoint()); } <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setRegistrationEndpoint(config.getRegistrationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setUserInfoEndpoint(config.getUserinfoEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setBackchannelAuthenticationEndpoint(config.getBackchannelAuthenticationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setPushedAuthorizationRequestEndpoint(config.getPushedAuthorizationRequestEndpoint()); return <mask> <mask> <mask> <mask> <mask> <mask> <mask> ; } private OIDCConfigurationRepresentation checkConfigOverride(OIDCConfigurationRepresentation config) { if (openidConfigOverride != null) { Map<String, Object> asMap = JsonSerialization.mapper.convertValue(config, Map.class); // Override configuration asMap.putAll(openidConfigOverride); return JsonSerialization.mapper.convertValue(asMap, OIDCConfigurationRepresentation.class); } else { return config; } } }
|
mtlsEndpointAliases = getMtlsEndpointAliases(config); config.setMtlsEndpointAliases(mtlsEndpointAliases); config.setAuthorizationResponseIssParameterSupported(true); config = checkConfigOverride(config); return config; } protected List<String> getPromptValuesSupported(RealmModel realm) { List<String> prompts = new ArrayList<>(DEFAULT_PROMPT_VALUES_SUPPORTED); if (realm.isRegistrationAllowed()) { prompts.add(OIDCLoginProtocol.PROMPT_VALUE_CREATE); } return prompts; } @Override public void close() { } private static List<String> list(String... values) { return Arrays.asList(values); } private List<String> getClientAuthMethodsSupported() { return session.getKeycloakSessionFactory().getProviderFactoriesStream(ClientAuthenticator.class) .map(ClientAuthenticatorFactory.class::cast) .map(caf -> caf.getProtocolAuthenticatorMethods(OIDCLoginProtocol.LOGIN_PROTOCOL)) .flatMap(Collection::stream) .collect(Collectors.toList()); } private List<String> getSupportedAlgorithms(Class<? extends Provider> clazz, boolean includeNone) { Stream<String> supportedAlgorithms = session.getKeycloakSessionFactory().getProviderFactoriesStream(clazz) .map(ProviderFactory::getId); if (includeNone) { supportedAlgorithms = Stream.concat(supportedAlgorithms, Stream.of("none")); } return supportedAlgorithms.collect(Collectors.toList()); } private List<String> getSupportedAsymmetricAlgorithms() { return getSupportedAlgorithms(SignatureProvider.class, false).stream() .map(algorithm -> new AbstractMap.SimpleEntry<>(algorithm, session.getProvider(SignatureProvider.class, algorithm))) .filter(entry -> entry.getValue() != null) .filter(entry -> entry.getValue().isAsymmetricAlgorithm()) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private List<String> getSupportedSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(SignatureProvider.class, includeNone); } private List<String> getSupportedClientSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(ClientSignatureVerifierProvider.class, includeNone); } private List<String> getSupportedContentEncryptionAlgorithms() { return getSupportedAlgorithms(ContentEncryptionProvider.class, false); } private List<String> getAcrValuesSupported(RealmModel realm) { // Values explicitly set on the realm mapping Map<String, Integer> realmAcrLoaMap = AcrUtils.getAcrLoaMap(realm); List<String> result = new ArrayList<>(realmAcrLoaMap.keySet()); // Add LoA levels configured in authentication flow in addition to the realm values result.addAll(LoAUtil.getLoAConfiguredInRealmBrowserFlow(realm) .map(String::valueOf) .collect(Collectors.toList())); return result; } private List<String> getSupportedEncryptionAlgorithms() { return getSupportedAlgorithms(CekManagementProvider.class, false); } private List<String> getSupportedBackchannelAuthenticationRequestSigningAlgorithms() { return getSupportedAsymmetricAlgorithms(); } private List<String> getSupportedEncryptionAlg(boolean includeNone) { return getSupportedAlgorithms(CekManagementProvider.class, includeNone); } private List<String> getSupportedEncryptionEnc(boolean includeNone) { return getSupportedAlgorithms(ContentEncryptionProvider.class, includeNone); } // Use protected method to make it easier to override in custom provider if different URLs are requested to be used as mtls_endpoint_aliases protected MTLSEndpointAliases getMtlsEndpointAliases(OIDCConfigurationRepresentation config) { MTLSEndpointAliases mtls_endpoints = new MTLSEndpointAliases(); mtls_endpoints .setTokenEndpoint(config.getTokenEndpoint()); mtls_endpoints .setRevocationEndpoint(config.getRevocationEndpoint()); mtls_endpoints .setIntrospectionEndpoint(config.getIntrospectionEndpoint()); if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) { mtls_endpoints .setDeviceAuthorizationEndpoint(config.getDeviceAuthorizationEndpoint()); } mtls_endpoints .setRegistrationEndpoint(config.getRegistrationEndpoint()); mtls_endpoints .setUserInfoEndpoint(config.getUserinfoEndpoint()); mtls_endpoints .setBackchannelAuthenticationEndpoint(config.getBackchannelAuthenticationEndpoint()); mtls_endpoints .setPushedAuthorizationRequestEndpoint(config.getPushedAuthorizationRequestEndpoint()); return mtls_endpoints ; } private OIDCConfigurationRepresentation checkConfigOverride(OIDCConfigurationRepresentation config) { if (openidConfigOverride != null) { Map<String, Object> asMap = JsonSerialization.mapper.convertValue(config, Map.class); // Override configuration asMap.putAll(openidConfigOverride); return JsonSerialization.mapper.convertValue(asMap, OIDCConfigurationRepresentation.class); } else { return config; } } }
|
java
|
config.setMtlsEndpointAliases(mtlsEndpointAliases); config.setAuthorizationResponseIssParameterSupported(true); config = checkConfigOverride(config); return config; } protected List<String> getPromptValuesSupported(RealmModel realm) { List<String> prompts = new ArrayList<>(DEFAULT_PROMPT_VALUES_SUPPORTED); if (realm.isRegistrationAllowed()) { prompts.add(OIDCLoginProtocol.PROMPT_VALUE_CREATE); } return prompts; } @Override public void close() { } private static List<String> list(String... values) { return Arrays.asList(values); } private List<String> getClientAuthMethodsSupported() { return session.getKeycloakSessionFactory().getProviderFactoriesStream(ClientAuthenticator.class) .map(ClientAuthenticatorFactory.class::cast) .map(caf -> caf.getProtocolAuthenticatorMethods(OIDCLoginProtocol.LOGIN_PROTOCOL)) .flatMap(Collection::stream) .collect(Collectors.toList()); } private List<String> getSupportedAlgorithms(Class<? extends Provider> clazz, boolean includeNone) { Stream<String> supportedAlgorithms = session.getKeycloakSessionFactory().getProviderFactoriesStream(clazz) .map(ProviderFactory::getId); if (includeNone) { supportedAlgorithms = Stream.concat(supportedAlgorithms, Stream.of("none")); } return supportedAlgorithms.collect(Collectors.toList()); } private List<String> getSupportedAsymmetricAlgorithms() { return getSupportedAlgorithms(SignatureProvider.class, false).stream() .map(algorithm -> new AbstractMap.SimpleEntry<>(algorithm, session.getProvider(SignatureProvider.class, algorithm))) .filter(entry -> entry.getValue() != null) .filter(entry -> entry.getValue().isAsymmetricAlgorithm()) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private List<String> getSupportedSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(SignatureProvider.class, includeNone); } private List<String> getSupportedClientSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(ClientSignatureVerifierProvider.class, includeNone); } private List<String> getSupportedContentEncryptionAlgorithms() { return getSupportedAlgorithms(ContentEncryptionProvider.class, false); } private List<String> getAcrValuesSupported(RealmModel realm) { // Values explicitly set on the realm mapping Map<String, Integer> realmAcrLoaMap = AcrUtils.getAcrLoaMap(realm); List<String> result = new ArrayList<>(realmAcrLoaMap.keySet()); // Add LoA levels configured in authentication flow in addition to the realm values result.addAll(LoAUtil.getLoAConfiguredInRealmBrowserFlow(realm) .map(String::valueOf) .collect(Collectors.toList())); return result; } private List<String> getSupportedEncryptionAlgorithms() { return getSupportedAlgorithms(CekManagementProvider.class, false); } private List<String> getSupportedBackchannelAuthenticationRequestSigningAlgorithms() { return getSupportedAsymmetricAlgorithms(); } private List<String> getSupportedEncryptionAlg(boolean includeNone) { return getSupportedAlgorithms(CekManagementProvider.class, includeNone); } private List<String> getSupportedEncryptionEnc(boolean includeNone) { return getSupportedAlgorithms(ContentEncryptionProvider.class, includeNone); } // Use protected method to make it easier to override in custom provider if different URLs are requested to be used as mtls_endpoint_aliases protected MTLSEndpointAliases getMtlsEndpointAliases(OIDCConfigurationRepresentation config) { MTLSEndpointAliases <mask> <mask> <mask> <mask> <mask> <mask> <mask> = new MTLSEndpointAliases(); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setTokenEndpoint(config.getTokenEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setRevocationEndpoint(config.getRevocationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setIntrospectionEndpoint(config.getIntrospectionEndpoint()); if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) { <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setDeviceAuthorizationEndpoint(config.getDeviceAuthorizationEndpoint()); } <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setRegistrationEndpoint(config.getRegistrationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setUserInfoEndpoint(config.getUserinfoEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setBackchannelAuthenticationEndpoint(config.getBackchannelAuthenticationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setPushedAuthorizationRequestEndpoint(config.getPushedAuthorizationRequestEndpoint()); return <mask> <mask> <mask> <mask> <mask> <mask> <mask> ; } private OIDCConfigurationRepresentation checkConfigOverride(OIDCConfigurationRepresentation config) { if (openidConfigOverride != null) { Map<String, Object> asMap = JsonSerialization.mapper.convertValue(config, Map.class); // Override configuration asMap.putAll(openidConfigOverride); return JsonSerialization.mapper.convertValue(asMap, OIDCConfigurationRepresentation.class); } else { return config; } } }
|
config.setMtlsEndpointAliases(mtlsEndpointAliases); config.setAuthorizationResponseIssParameterSupported(true); config = checkConfigOverride(config); return config; } protected List<String> getPromptValuesSupported(RealmModel realm) { List<String> prompts = new ArrayList<>(DEFAULT_PROMPT_VALUES_SUPPORTED); if (realm.isRegistrationAllowed()) { prompts.add(OIDCLoginProtocol.PROMPT_VALUE_CREATE); } return prompts; } @Override public void close() { } private static List<String> list(String... values) { return Arrays.asList(values); } private List<String> getClientAuthMethodsSupported() { return session.getKeycloakSessionFactory().getProviderFactoriesStream(ClientAuthenticator.class) .map(ClientAuthenticatorFactory.class::cast) .map(caf -> caf.getProtocolAuthenticatorMethods(OIDCLoginProtocol.LOGIN_PROTOCOL)) .flatMap(Collection::stream) .collect(Collectors.toList()); } private List<String> getSupportedAlgorithms(Class<? extends Provider> clazz, boolean includeNone) { Stream<String> supportedAlgorithms = session.getKeycloakSessionFactory().getProviderFactoriesStream(clazz) .map(ProviderFactory::getId); if (includeNone) { supportedAlgorithms = Stream.concat(supportedAlgorithms, Stream.of("none")); } return supportedAlgorithms.collect(Collectors.toList()); } private List<String> getSupportedAsymmetricAlgorithms() { return getSupportedAlgorithms(SignatureProvider.class, false).stream() .map(algorithm -> new AbstractMap.SimpleEntry<>(algorithm, session.getProvider(SignatureProvider.class, algorithm))) .filter(entry -> entry.getValue() != null) .filter(entry -> entry.getValue().isAsymmetricAlgorithm()) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private List<String> getSupportedSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(SignatureProvider.class, includeNone); } private List<String> getSupportedClientSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(ClientSignatureVerifierProvider.class, includeNone); } private List<String> getSupportedContentEncryptionAlgorithms() { return getSupportedAlgorithms(ContentEncryptionProvider.class, false); } private List<String> getAcrValuesSupported(RealmModel realm) { // Values explicitly set on the realm mapping Map<String, Integer> realmAcrLoaMap = AcrUtils.getAcrLoaMap(realm); List<String> result = new ArrayList<>(realmAcrLoaMap.keySet()); // Add LoA levels configured in authentication flow in addition to the realm values result.addAll(LoAUtil.getLoAConfiguredInRealmBrowserFlow(realm) .map(String::valueOf) .collect(Collectors.toList())); return result; } private List<String> getSupportedEncryptionAlgorithms() { return getSupportedAlgorithms(CekManagementProvider.class, false); } private List<String> getSupportedBackchannelAuthenticationRequestSigningAlgorithms() { return getSupportedAsymmetricAlgorithms(); } private List<String> getSupportedEncryptionAlg(boolean includeNone) { return getSupportedAlgorithms(CekManagementProvider.class, includeNone); } private List<String> getSupportedEncryptionEnc(boolean includeNone) { return getSupportedAlgorithms(ContentEncryptionProvider.class, includeNone); } // Use protected method to make it easier to override in custom provider if different URLs are requested to be used as mtls_endpoint_aliases protected MTLSEndpointAliases getMtlsEndpointAliases(OIDCConfigurationRepresentation config) { MTLSEndpointAliases mtls_endpoints = new MTLSEndpointAliases(); mtls_endpoints .setTokenEndpoint(config.getTokenEndpoint()); mtls_endpoints .setRevocationEndpoint(config.getRevocationEndpoint()); mtls_endpoints .setIntrospectionEndpoint(config.getIntrospectionEndpoint()); if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) { mtls_endpoints .setDeviceAuthorizationEndpoint(config.getDeviceAuthorizationEndpoint()); } mtls_endpoints .setRegistrationEndpoint(config.getRegistrationEndpoint()); mtls_endpoints .setUserInfoEndpoint(config.getUserinfoEndpoint()); mtls_endpoints .setBackchannelAuthenticationEndpoint(config.getBackchannelAuthenticationEndpoint()); mtls_endpoints .setPushedAuthorizationRequestEndpoint(config.getPushedAuthorizationRequestEndpoint()); return mtls_endpoints ; } private OIDCConfigurationRepresentation checkConfigOverride(OIDCConfigurationRepresentation config) { if (openidConfigOverride != null) { Map<String, Object> asMap = JsonSerialization.mapper.convertValue(config, Map.class); // Override configuration asMap.putAll(openidConfigOverride); return JsonSerialization.mapper.convertValue(asMap, OIDCConfigurationRepresentation.class); } else { return config; } } }
|
java
|
config = checkConfigOverride(config); return config; } protected List<String> getPromptValuesSupported(RealmModel realm) { List<String> prompts = new ArrayList<>(DEFAULT_PROMPT_VALUES_SUPPORTED); if (realm.isRegistrationAllowed()) { prompts.add(OIDCLoginProtocol.PROMPT_VALUE_CREATE); } return prompts; } @Override public void close() { } private static List<String> list(String... values) { return Arrays.asList(values); } private List<String> getClientAuthMethodsSupported() { return session.getKeycloakSessionFactory().getProviderFactoriesStream(ClientAuthenticator.class) .map(ClientAuthenticatorFactory.class::cast) .map(caf -> caf.getProtocolAuthenticatorMethods(OIDCLoginProtocol.LOGIN_PROTOCOL)) .flatMap(Collection::stream) .collect(Collectors.toList()); } private List<String> getSupportedAlgorithms(Class<? extends Provider> clazz, boolean includeNone) { Stream<String> supportedAlgorithms = session.getKeycloakSessionFactory().getProviderFactoriesStream(clazz) .map(ProviderFactory::getId); if (includeNone) { supportedAlgorithms = Stream.concat(supportedAlgorithms, Stream.of("none")); } return supportedAlgorithms.collect(Collectors.toList()); } private List<String> getSupportedAsymmetricAlgorithms() { return getSupportedAlgorithms(SignatureProvider.class, false).stream() .map(algorithm -> new AbstractMap.SimpleEntry<>(algorithm, session.getProvider(SignatureProvider.class, algorithm))) .filter(entry -> entry.getValue() != null) .filter(entry -> entry.getValue().isAsymmetricAlgorithm()) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private List<String> getSupportedSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(SignatureProvider.class, includeNone); } private List<String> getSupportedClientSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(ClientSignatureVerifierProvider.class, includeNone); } private List<String> getSupportedContentEncryptionAlgorithms() { return getSupportedAlgorithms(ContentEncryptionProvider.class, false); } private List<String> getAcrValuesSupported(RealmModel realm) { // Values explicitly set on the realm mapping Map<String, Integer> realmAcrLoaMap = AcrUtils.getAcrLoaMap(realm); List<String> result = new ArrayList<>(realmAcrLoaMap.keySet()); // Add LoA levels configured in authentication flow in addition to the realm values result.addAll(LoAUtil.getLoAConfiguredInRealmBrowserFlow(realm) .map(String::valueOf) .collect(Collectors.toList())); return result; } private List<String> getSupportedEncryptionAlgorithms() { return getSupportedAlgorithms(CekManagementProvider.class, false); } private List<String> getSupportedBackchannelAuthenticationRequestSigningAlgorithms() { return getSupportedAsymmetricAlgorithms(); } private List<String> getSupportedEncryptionAlg(boolean includeNone) { return getSupportedAlgorithms(CekManagementProvider.class, includeNone); } private List<String> getSupportedEncryptionEnc(boolean includeNone) { return getSupportedAlgorithms(ContentEncryptionProvider.class, includeNone); } // Use protected method to make it easier to override in custom provider if different URLs are requested to be used as mtls_endpoint_aliases protected MTLSEndpointAliases getMtlsEndpointAliases(OIDCConfigurationRepresentation config) { MTLSEndpointAliases <mask> <mask> <mask> <mask> <mask> <mask> <mask> = new MTLSEndpointAliases(); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setTokenEndpoint(config.getTokenEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setRevocationEndpoint(config.getRevocationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setIntrospectionEndpoint(config.getIntrospectionEndpoint()); if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) { <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setDeviceAuthorizationEndpoint(config.getDeviceAuthorizationEndpoint()); } <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setRegistrationEndpoint(config.getRegistrationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setUserInfoEndpoint(config.getUserinfoEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setBackchannelAuthenticationEndpoint(config.getBackchannelAuthenticationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setPushedAuthorizationRequestEndpoint(config.getPushedAuthorizationRequestEndpoint()); return <mask> <mask> <mask> <mask> <mask> <mask> <mask> ; } private OIDCConfigurationRepresentation checkConfigOverride(OIDCConfigurationRepresentation config) { if (openidConfigOverride != null) { Map<String, Object> asMap = JsonSerialization.mapper.convertValue(config, Map.class); // Override configuration asMap.putAll(openidConfigOverride); return JsonSerialization.mapper.convertValue(asMap, OIDCConfigurationRepresentation.class); } else { return config; } } }
|
config = checkConfigOverride(config); return config; } protected List<String> getPromptValuesSupported(RealmModel realm) { List<String> prompts = new ArrayList<>(DEFAULT_PROMPT_VALUES_SUPPORTED); if (realm.isRegistrationAllowed()) { prompts.add(OIDCLoginProtocol.PROMPT_VALUE_CREATE); } return prompts; } @Override public void close() { } private static List<String> list(String... values) { return Arrays.asList(values); } private List<String> getClientAuthMethodsSupported() { return session.getKeycloakSessionFactory().getProviderFactoriesStream(ClientAuthenticator.class) .map(ClientAuthenticatorFactory.class::cast) .map(caf -> caf.getProtocolAuthenticatorMethods(OIDCLoginProtocol.LOGIN_PROTOCOL)) .flatMap(Collection::stream) .collect(Collectors.toList()); } private List<String> getSupportedAlgorithms(Class<? extends Provider> clazz, boolean includeNone) { Stream<String> supportedAlgorithms = session.getKeycloakSessionFactory().getProviderFactoriesStream(clazz) .map(ProviderFactory::getId); if (includeNone) { supportedAlgorithms = Stream.concat(supportedAlgorithms, Stream.of("none")); } return supportedAlgorithms.collect(Collectors.toList()); } private List<String> getSupportedAsymmetricAlgorithms() { return getSupportedAlgorithms(SignatureProvider.class, false).stream() .map(algorithm -> new AbstractMap.SimpleEntry<>(algorithm, session.getProvider(SignatureProvider.class, algorithm))) .filter(entry -> entry.getValue() != null) .filter(entry -> entry.getValue().isAsymmetricAlgorithm()) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private List<String> getSupportedSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(SignatureProvider.class, includeNone); } private List<String> getSupportedClientSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(ClientSignatureVerifierProvider.class, includeNone); } private List<String> getSupportedContentEncryptionAlgorithms() { return getSupportedAlgorithms(ContentEncryptionProvider.class, false); } private List<String> getAcrValuesSupported(RealmModel realm) { // Values explicitly set on the realm mapping Map<String, Integer> realmAcrLoaMap = AcrUtils.getAcrLoaMap(realm); List<String> result = new ArrayList<>(realmAcrLoaMap.keySet()); // Add LoA levels configured in authentication flow in addition to the realm values result.addAll(LoAUtil.getLoAConfiguredInRealmBrowserFlow(realm) .map(String::valueOf) .collect(Collectors.toList())); return result; } private List<String> getSupportedEncryptionAlgorithms() { return getSupportedAlgorithms(CekManagementProvider.class, false); } private List<String> getSupportedBackchannelAuthenticationRequestSigningAlgorithms() { return getSupportedAsymmetricAlgorithms(); } private List<String> getSupportedEncryptionAlg(boolean includeNone) { return getSupportedAlgorithms(CekManagementProvider.class, includeNone); } private List<String> getSupportedEncryptionEnc(boolean includeNone) { return getSupportedAlgorithms(ContentEncryptionProvider.class, includeNone); } // Use protected method to make it easier to override in custom provider if different URLs are requested to be used as mtls_endpoint_aliases protected MTLSEndpointAliases getMtlsEndpointAliases(OIDCConfigurationRepresentation config) { MTLSEndpointAliases mtls_endpoints = new MTLSEndpointAliases(); mtls_endpoints .setTokenEndpoint(config.getTokenEndpoint()); mtls_endpoints .setRevocationEndpoint(config.getRevocationEndpoint()); mtls_endpoints .setIntrospectionEndpoint(config.getIntrospectionEndpoint()); if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) { mtls_endpoints .setDeviceAuthorizationEndpoint(config.getDeviceAuthorizationEndpoint()); } mtls_endpoints .setRegistrationEndpoint(config.getRegistrationEndpoint()); mtls_endpoints .setUserInfoEndpoint(config.getUserinfoEndpoint()); mtls_endpoints .setBackchannelAuthenticationEndpoint(config.getBackchannelAuthenticationEndpoint()); mtls_endpoints .setPushedAuthorizationRequestEndpoint(config.getPushedAuthorizationRequestEndpoint()); return mtls_endpoints ; } private OIDCConfigurationRepresentation checkConfigOverride(OIDCConfigurationRepresentation config) { if (openidConfigOverride != null) { Map<String, Object> asMap = JsonSerialization.mapper.convertValue(config, Map.class); // Override configuration asMap.putAll(openidConfigOverride); return JsonSerialization.mapper.convertValue(asMap, OIDCConfigurationRepresentation.class); } else { return config; } } }
|
java
|
checkConfigOverride(config); return config; } protected List<String> getPromptValuesSupported(RealmModel realm) { List<String> prompts = new ArrayList<>(DEFAULT_PROMPT_VALUES_SUPPORTED); if (realm.isRegistrationAllowed()) { prompts.add(OIDCLoginProtocol.PROMPT_VALUE_CREATE); } return prompts; } @Override public void close() { } private static List<String> list(String... values) { return Arrays.asList(values); } private List<String> getClientAuthMethodsSupported() { return session.getKeycloakSessionFactory().getProviderFactoriesStream(ClientAuthenticator.class) .map(ClientAuthenticatorFactory.class::cast) .map(caf -> caf.getProtocolAuthenticatorMethods(OIDCLoginProtocol.LOGIN_PROTOCOL)) .flatMap(Collection::stream) .collect(Collectors.toList()); } private List<String> getSupportedAlgorithms(Class<? extends Provider> clazz, boolean includeNone) { Stream<String> supportedAlgorithms = session.getKeycloakSessionFactory().getProviderFactoriesStream(clazz) .map(ProviderFactory::getId); if (includeNone) { supportedAlgorithms = Stream.concat(supportedAlgorithms, Stream.of("none")); } return supportedAlgorithms.collect(Collectors.toList()); } private List<String> getSupportedAsymmetricAlgorithms() { return getSupportedAlgorithms(SignatureProvider.class, false).stream() .map(algorithm -> new AbstractMap.SimpleEntry<>(algorithm, session.getProvider(SignatureProvider.class, algorithm))) .filter(entry -> entry.getValue() != null) .filter(entry -> entry.getValue().isAsymmetricAlgorithm()) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private List<String> getSupportedSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(SignatureProvider.class, includeNone); } private List<String> getSupportedClientSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(ClientSignatureVerifierProvider.class, includeNone); } private List<String> getSupportedContentEncryptionAlgorithms() { return getSupportedAlgorithms(ContentEncryptionProvider.class, false); } private List<String> getAcrValuesSupported(RealmModel realm) { // Values explicitly set on the realm mapping Map<String, Integer> realmAcrLoaMap = AcrUtils.getAcrLoaMap(realm); List<String> result = new ArrayList<>(realmAcrLoaMap.keySet()); // Add LoA levels configured in authentication flow in addition to the realm values result.addAll(LoAUtil.getLoAConfiguredInRealmBrowserFlow(realm) .map(String::valueOf) .collect(Collectors.toList())); return result; } private List<String> getSupportedEncryptionAlgorithms() { return getSupportedAlgorithms(CekManagementProvider.class, false); } private List<String> getSupportedBackchannelAuthenticationRequestSigningAlgorithms() { return getSupportedAsymmetricAlgorithms(); } private List<String> getSupportedEncryptionAlg(boolean includeNone) { return getSupportedAlgorithms(CekManagementProvider.class, includeNone); } private List<String> getSupportedEncryptionEnc(boolean includeNone) { return getSupportedAlgorithms(ContentEncryptionProvider.class, includeNone); } // Use protected method to make it easier to override in custom provider if different URLs are requested to be used as mtls_endpoint_aliases protected MTLSEndpointAliases getMtlsEndpointAliases(OIDCConfigurationRepresentation config) { MTLSEndpointAliases <mask> <mask> <mask> <mask> <mask> <mask> <mask> = new MTLSEndpointAliases(); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setTokenEndpoint(config.getTokenEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setRevocationEndpoint(config.getRevocationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setIntrospectionEndpoint(config.getIntrospectionEndpoint()); if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) { <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setDeviceAuthorizationEndpoint(config.getDeviceAuthorizationEndpoint()); } <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setRegistrationEndpoint(config.getRegistrationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setUserInfoEndpoint(config.getUserinfoEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setBackchannelAuthenticationEndpoint(config.getBackchannelAuthenticationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setPushedAuthorizationRequestEndpoint(config.getPushedAuthorizationRequestEndpoint()); return <mask> <mask> <mask> <mask> <mask> <mask> <mask> ; } private OIDCConfigurationRepresentation checkConfigOverride(OIDCConfigurationRepresentation config) { if (openidConfigOverride != null) { Map<String, Object> asMap = JsonSerialization.mapper.convertValue(config, Map.class); // Override configuration asMap.putAll(openidConfigOverride); return JsonSerialization.mapper.convertValue(asMap, OIDCConfigurationRepresentation.class); } else { return config; } } }
|
checkConfigOverride(config); return config; } protected List<String> getPromptValuesSupported(RealmModel realm) { List<String> prompts = new ArrayList<>(DEFAULT_PROMPT_VALUES_SUPPORTED); if (realm.isRegistrationAllowed()) { prompts.add(OIDCLoginProtocol.PROMPT_VALUE_CREATE); } return prompts; } @Override public void close() { } private static List<String> list(String... values) { return Arrays.asList(values); } private List<String> getClientAuthMethodsSupported() { return session.getKeycloakSessionFactory().getProviderFactoriesStream(ClientAuthenticator.class) .map(ClientAuthenticatorFactory.class::cast) .map(caf -> caf.getProtocolAuthenticatorMethods(OIDCLoginProtocol.LOGIN_PROTOCOL)) .flatMap(Collection::stream) .collect(Collectors.toList()); } private List<String> getSupportedAlgorithms(Class<? extends Provider> clazz, boolean includeNone) { Stream<String> supportedAlgorithms = session.getKeycloakSessionFactory().getProviderFactoriesStream(clazz) .map(ProviderFactory::getId); if (includeNone) { supportedAlgorithms = Stream.concat(supportedAlgorithms, Stream.of("none")); } return supportedAlgorithms.collect(Collectors.toList()); } private List<String> getSupportedAsymmetricAlgorithms() { return getSupportedAlgorithms(SignatureProvider.class, false).stream() .map(algorithm -> new AbstractMap.SimpleEntry<>(algorithm, session.getProvider(SignatureProvider.class, algorithm))) .filter(entry -> entry.getValue() != null) .filter(entry -> entry.getValue().isAsymmetricAlgorithm()) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private List<String> getSupportedSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(SignatureProvider.class, includeNone); } private List<String> getSupportedClientSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(ClientSignatureVerifierProvider.class, includeNone); } private List<String> getSupportedContentEncryptionAlgorithms() { return getSupportedAlgorithms(ContentEncryptionProvider.class, false); } private List<String> getAcrValuesSupported(RealmModel realm) { // Values explicitly set on the realm mapping Map<String, Integer> realmAcrLoaMap = AcrUtils.getAcrLoaMap(realm); List<String> result = new ArrayList<>(realmAcrLoaMap.keySet()); // Add LoA levels configured in authentication flow in addition to the realm values result.addAll(LoAUtil.getLoAConfiguredInRealmBrowserFlow(realm) .map(String::valueOf) .collect(Collectors.toList())); return result; } private List<String> getSupportedEncryptionAlgorithms() { return getSupportedAlgorithms(CekManagementProvider.class, false); } private List<String> getSupportedBackchannelAuthenticationRequestSigningAlgorithms() { return getSupportedAsymmetricAlgorithms(); } private List<String> getSupportedEncryptionAlg(boolean includeNone) { return getSupportedAlgorithms(CekManagementProvider.class, includeNone); } private List<String> getSupportedEncryptionEnc(boolean includeNone) { return getSupportedAlgorithms(ContentEncryptionProvider.class, includeNone); } // Use protected method to make it easier to override in custom provider if different URLs are requested to be used as mtls_endpoint_aliases protected MTLSEndpointAliases getMtlsEndpointAliases(OIDCConfigurationRepresentation config) { MTLSEndpointAliases mtls_endpoints = new MTLSEndpointAliases(); mtls_endpoints .setTokenEndpoint(config.getTokenEndpoint()); mtls_endpoints .setRevocationEndpoint(config.getRevocationEndpoint()); mtls_endpoints .setIntrospectionEndpoint(config.getIntrospectionEndpoint()); if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) { mtls_endpoints .setDeviceAuthorizationEndpoint(config.getDeviceAuthorizationEndpoint()); } mtls_endpoints .setRegistrationEndpoint(config.getRegistrationEndpoint()); mtls_endpoints .setUserInfoEndpoint(config.getUserinfoEndpoint()); mtls_endpoints .setBackchannelAuthenticationEndpoint(config.getBackchannelAuthenticationEndpoint()); mtls_endpoints .setPushedAuthorizationRequestEndpoint(config.getPushedAuthorizationRequestEndpoint()); return mtls_endpoints ; } private OIDCConfigurationRepresentation checkConfigOverride(OIDCConfigurationRepresentation config) { if (openidConfigOverride != null) { Map<String, Object> asMap = JsonSerialization.mapper.convertValue(config, Map.class); // Override configuration asMap.putAll(openidConfigOverride); return JsonSerialization.mapper.convertValue(asMap, OIDCConfigurationRepresentation.class); } else { return config; } } }
|
java
|
config; } protected List<String> getPromptValuesSupported(RealmModel realm) { List<String> prompts = new ArrayList<>(DEFAULT_PROMPT_VALUES_SUPPORTED); if (realm.isRegistrationAllowed()) { prompts.add(OIDCLoginProtocol.PROMPT_VALUE_CREATE); } return prompts; } @Override public void close() { } private static List<String> list(String... values) { return Arrays.asList(values); } private List<String> getClientAuthMethodsSupported() { return session.getKeycloakSessionFactory().getProviderFactoriesStream(ClientAuthenticator.class) .map(ClientAuthenticatorFactory.class::cast) .map(caf -> caf.getProtocolAuthenticatorMethods(OIDCLoginProtocol.LOGIN_PROTOCOL)) .flatMap(Collection::stream) .collect(Collectors.toList()); } private List<String> getSupportedAlgorithms(Class<? extends Provider> clazz, boolean includeNone) { Stream<String> supportedAlgorithms = session.getKeycloakSessionFactory().getProviderFactoriesStream(clazz) .map(ProviderFactory::getId); if (includeNone) { supportedAlgorithms = Stream.concat(supportedAlgorithms, Stream.of("none")); } return supportedAlgorithms.collect(Collectors.toList()); } private List<String> getSupportedAsymmetricAlgorithms() { return getSupportedAlgorithms(SignatureProvider.class, false).stream() .map(algorithm -> new AbstractMap.SimpleEntry<>(algorithm, session.getProvider(SignatureProvider.class, algorithm))) .filter(entry -> entry.getValue() != null) .filter(entry -> entry.getValue().isAsymmetricAlgorithm()) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private List<String> getSupportedSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(SignatureProvider.class, includeNone); } private List<String> getSupportedClientSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(ClientSignatureVerifierProvider.class, includeNone); } private List<String> getSupportedContentEncryptionAlgorithms() { return getSupportedAlgorithms(ContentEncryptionProvider.class, false); } private List<String> getAcrValuesSupported(RealmModel realm) { // Values explicitly set on the realm mapping Map<String, Integer> realmAcrLoaMap = AcrUtils.getAcrLoaMap(realm); List<String> result = new ArrayList<>(realmAcrLoaMap.keySet()); // Add LoA levels configured in authentication flow in addition to the realm values result.addAll(LoAUtil.getLoAConfiguredInRealmBrowserFlow(realm) .map(String::valueOf) .collect(Collectors.toList())); return result; } private List<String> getSupportedEncryptionAlgorithms() { return getSupportedAlgorithms(CekManagementProvider.class, false); } private List<String> getSupportedBackchannelAuthenticationRequestSigningAlgorithms() { return getSupportedAsymmetricAlgorithms(); } private List<String> getSupportedEncryptionAlg(boolean includeNone) { return getSupportedAlgorithms(CekManagementProvider.class, includeNone); } private List<String> getSupportedEncryptionEnc(boolean includeNone) { return getSupportedAlgorithms(ContentEncryptionProvider.class, includeNone); } // Use protected method to make it easier to override in custom provider if different URLs are requested to be used as mtls_endpoint_aliases protected MTLSEndpointAliases getMtlsEndpointAliases(OIDCConfigurationRepresentation config) { MTLSEndpointAliases <mask> <mask> <mask> <mask> <mask> <mask> <mask> = new MTLSEndpointAliases(); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setTokenEndpoint(config.getTokenEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setRevocationEndpoint(config.getRevocationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setIntrospectionEndpoint(config.getIntrospectionEndpoint()); if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) { <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setDeviceAuthorizationEndpoint(config.getDeviceAuthorizationEndpoint()); } <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setRegistrationEndpoint(config.getRegistrationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setUserInfoEndpoint(config.getUserinfoEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setBackchannelAuthenticationEndpoint(config.getBackchannelAuthenticationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setPushedAuthorizationRequestEndpoint(config.getPushedAuthorizationRequestEndpoint()); return <mask> <mask> <mask> <mask> <mask> <mask> <mask> ; } private OIDCConfigurationRepresentation checkConfigOverride(OIDCConfigurationRepresentation config) { if (openidConfigOverride != null) { Map<String, Object> asMap = JsonSerialization.mapper.convertValue(config, Map.class); // Override configuration asMap.putAll(openidConfigOverride); return JsonSerialization.mapper.convertValue(asMap, OIDCConfigurationRepresentation.class); } else { return config; } } }
|
config; } protected List<String> getPromptValuesSupported(RealmModel realm) { List<String> prompts = new ArrayList<>(DEFAULT_PROMPT_VALUES_SUPPORTED); if (realm.isRegistrationAllowed()) { prompts.add(OIDCLoginProtocol.PROMPT_VALUE_CREATE); } return prompts; } @Override public void close() { } private static List<String> list(String... values) { return Arrays.asList(values); } private List<String> getClientAuthMethodsSupported() { return session.getKeycloakSessionFactory().getProviderFactoriesStream(ClientAuthenticator.class) .map(ClientAuthenticatorFactory.class::cast) .map(caf -> caf.getProtocolAuthenticatorMethods(OIDCLoginProtocol.LOGIN_PROTOCOL)) .flatMap(Collection::stream) .collect(Collectors.toList()); } private List<String> getSupportedAlgorithms(Class<? extends Provider> clazz, boolean includeNone) { Stream<String> supportedAlgorithms = session.getKeycloakSessionFactory().getProviderFactoriesStream(clazz) .map(ProviderFactory::getId); if (includeNone) { supportedAlgorithms = Stream.concat(supportedAlgorithms, Stream.of("none")); } return supportedAlgorithms.collect(Collectors.toList()); } private List<String> getSupportedAsymmetricAlgorithms() { return getSupportedAlgorithms(SignatureProvider.class, false).stream() .map(algorithm -> new AbstractMap.SimpleEntry<>(algorithm, session.getProvider(SignatureProvider.class, algorithm))) .filter(entry -> entry.getValue() != null) .filter(entry -> entry.getValue().isAsymmetricAlgorithm()) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private List<String> getSupportedSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(SignatureProvider.class, includeNone); } private List<String> getSupportedClientSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(ClientSignatureVerifierProvider.class, includeNone); } private List<String> getSupportedContentEncryptionAlgorithms() { return getSupportedAlgorithms(ContentEncryptionProvider.class, false); } private List<String> getAcrValuesSupported(RealmModel realm) { // Values explicitly set on the realm mapping Map<String, Integer> realmAcrLoaMap = AcrUtils.getAcrLoaMap(realm); List<String> result = new ArrayList<>(realmAcrLoaMap.keySet()); // Add LoA levels configured in authentication flow in addition to the realm values result.addAll(LoAUtil.getLoAConfiguredInRealmBrowserFlow(realm) .map(String::valueOf) .collect(Collectors.toList())); return result; } private List<String> getSupportedEncryptionAlgorithms() { return getSupportedAlgorithms(CekManagementProvider.class, false); } private List<String> getSupportedBackchannelAuthenticationRequestSigningAlgorithms() { return getSupportedAsymmetricAlgorithms(); } private List<String> getSupportedEncryptionAlg(boolean includeNone) { return getSupportedAlgorithms(CekManagementProvider.class, includeNone); } private List<String> getSupportedEncryptionEnc(boolean includeNone) { return getSupportedAlgorithms(ContentEncryptionProvider.class, includeNone); } // Use protected method to make it easier to override in custom provider if different URLs are requested to be used as mtls_endpoint_aliases protected MTLSEndpointAliases getMtlsEndpointAliases(OIDCConfigurationRepresentation config) { MTLSEndpointAliases mtls_endpoints = new MTLSEndpointAliases(); mtls_endpoints .setTokenEndpoint(config.getTokenEndpoint()); mtls_endpoints .setRevocationEndpoint(config.getRevocationEndpoint()); mtls_endpoints .setIntrospectionEndpoint(config.getIntrospectionEndpoint()); if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) { mtls_endpoints .setDeviceAuthorizationEndpoint(config.getDeviceAuthorizationEndpoint()); } mtls_endpoints .setRegistrationEndpoint(config.getRegistrationEndpoint()); mtls_endpoints .setUserInfoEndpoint(config.getUserinfoEndpoint()); mtls_endpoints .setBackchannelAuthenticationEndpoint(config.getBackchannelAuthenticationEndpoint()); mtls_endpoints .setPushedAuthorizationRequestEndpoint(config.getPushedAuthorizationRequestEndpoint()); return mtls_endpoints ; } private OIDCConfigurationRepresentation checkConfigOverride(OIDCConfigurationRepresentation config) { if (openidConfigOverride != null) { Map<String, Object> asMap = JsonSerialization.mapper.convertValue(config, Map.class); // Override configuration asMap.putAll(openidConfigOverride); return JsonSerialization.mapper.convertValue(asMap, OIDCConfigurationRepresentation.class); } else { return config; } } }
|
java
|
List<String> getPromptValuesSupported(RealmModel realm) { List<String> prompts = new ArrayList<>(DEFAULT_PROMPT_VALUES_SUPPORTED); if (realm.isRegistrationAllowed()) { prompts.add(OIDCLoginProtocol.PROMPT_VALUE_CREATE); } return prompts; } @Override public void close() { } private static List<String> list(String... values) { return Arrays.asList(values); } private List<String> getClientAuthMethodsSupported() { return session.getKeycloakSessionFactory().getProviderFactoriesStream(ClientAuthenticator.class) .map(ClientAuthenticatorFactory.class::cast) .map(caf -> caf.getProtocolAuthenticatorMethods(OIDCLoginProtocol.LOGIN_PROTOCOL)) .flatMap(Collection::stream) .collect(Collectors.toList()); } private List<String> getSupportedAlgorithms(Class<? extends Provider> clazz, boolean includeNone) { Stream<String> supportedAlgorithms = session.getKeycloakSessionFactory().getProviderFactoriesStream(clazz) .map(ProviderFactory::getId); if (includeNone) { supportedAlgorithms = Stream.concat(supportedAlgorithms, Stream.of("none")); } return supportedAlgorithms.collect(Collectors.toList()); } private List<String> getSupportedAsymmetricAlgorithms() { return getSupportedAlgorithms(SignatureProvider.class, false).stream() .map(algorithm -> new AbstractMap.SimpleEntry<>(algorithm, session.getProvider(SignatureProvider.class, algorithm))) .filter(entry -> entry.getValue() != null) .filter(entry -> entry.getValue().isAsymmetricAlgorithm()) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private List<String> getSupportedSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(SignatureProvider.class, includeNone); } private List<String> getSupportedClientSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(ClientSignatureVerifierProvider.class, includeNone); } private List<String> getSupportedContentEncryptionAlgorithms() { return getSupportedAlgorithms(ContentEncryptionProvider.class, false); } private List<String> getAcrValuesSupported(RealmModel realm) { // Values explicitly set on the realm mapping Map<String, Integer> realmAcrLoaMap = AcrUtils.getAcrLoaMap(realm); List<String> result = new ArrayList<>(realmAcrLoaMap.keySet()); // Add LoA levels configured in authentication flow in addition to the realm values result.addAll(LoAUtil.getLoAConfiguredInRealmBrowserFlow(realm) .map(String::valueOf) .collect(Collectors.toList())); return result; } private List<String> getSupportedEncryptionAlgorithms() { return getSupportedAlgorithms(CekManagementProvider.class, false); } private List<String> getSupportedBackchannelAuthenticationRequestSigningAlgorithms() { return getSupportedAsymmetricAlgorithms(); } private List<String> getSupportedEncryptionAlg(boolean includeNone) { return getSupportedAlgorithms(CekManagementProvider.class, includeNone); } private List<String> getSupportedEncryptionEnc(boolean includeNone) { return getSupportedAlgorithms(ContentEncryptionProvider.class, includeNone); } // Use protected method to make it easier to override in custom provider if different URLs are requested to be used as mtls_endpoint_aliases protected MTLSEndpointAliases getMtlsEndpointAliases(OIDCConfigurationRepresentation config) { MTLSEndpointAliases <mask> <mask> <mask> <mask> <mask> <mask> <mask> = new MTLSEndpointAliases(); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setTokenEndpoint(config.getTokenEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setRevocationEndpoint(config.getRevocationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setIntrospectionEndpoint(config.getIntrospectionEndpoint()); if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) { <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setDeviceAuthorizationEndpoint(config.getDeviceAuthorizationEndpoint()); } <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setRegistrationEndpoint(config.getRegistrationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setUserInfoEndpoint(config.getUserinfoEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setBackchannelAuthenticationEndpoint(config.getBackchannelAuthenticationEndpoint()); <mask> <mask> <mask> <mask> <mask> <mask> <mask> .setPushedAuthorizationRequestEndpoint(config.getPushedAuthorizationRequestEndpoint()); return <mask> <mask> <mask> <mask> <mask> <mask> <mask> ; } private OIDCConfigurationRepresentation checkConfigOverride(OIDCConfigurationRepresentation config) { if (openidConfigOverride != null) { Map<String, Object> asMap = JsonSerialization.mapper.convertValue(config, Map.class); // Override configuration asMap.putAll(openidConfigOverride); return JsonSerialization.mapper.convertValue(asMap, OIDCConfigurationRepresentation.class); } else { return config; } } }
|
List<String> getPromptValuesSupported(RealmModel realm) { List<String> prompts = new ArrayList<>(DEFAULT_PROMPT_VALUES_SUPPORTED); if (realm.isRegistrationAllowed()) { prompts.add(OIDCLoginProtocol.PROMPT_VALUE_CREATE); } return prompts; } @Override public void close() { } private static List<String> list(String... values) { return Arrays.asList(values); } private List<String> getClientAuthMethodsSupported() { return session.getKeycloakSessionFactory().getProviderFactoriesStream(ClientAuthenticator.class) .map(ClientAuthenticatorFactory.class::cast) .map(caf -> caf.getProtocolAuthenticatorMethods(OIDCLoginProtocol.LOGIN_PROTOCOL)) .flatMap(Collection::stream) .collect(Collectors.toList()); } private List<String> getSupportedAlgorithms(Class<? extends Provider> clazz, boolean includeNone) { Stream<String> supportedAlgorithms = session.getKeycloakSessionFactory().getProviderFactoriesStream(clazz) .map(ProviderFactory::getId); if (includeNone) { supportedAlgorithms = Stream.concat(supportedAlgorithms, Stream.of("none")); } return supportedAlgorithms.collect(Collectors.toList()); } private List<String> getSupportedAsymmetricAlgorithms() { return getSupportedAlgorithms(SignatureProvider.class, false).stream() .map(algorithm -> new AbstractMap.SimpleEntry<>(algorithm, session.getProvider(SignatureProvider.class, algorithm))) .filter(entry -> entry.getValue() != null) .filter(entry -> entry.getValue().isAsymmetricAlgorithm()) .map(Map.Entry::getKey) .collect(Collectors.toList()); } private List<String> getSupportedSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(SignatureProvider.class, includeNone); } private List<String> getSupportedClientSigningAlgorithms(boolean includeNone) { return getSupportedAlgorithms(ClientSignatureVerifierProvider.class, includeNone); } private List<String> getSupportedContentEncryptionAlgorithms() { return getSupportedAlgorithms(ContentEncryptionProvider.class, false); } private List<String> getAcrValuesSupported(RealmModel realm) { // Values explicitly set on the realm mapping Map<String, Integer> realmAcrLoaMap = AcrUtils.getAcrLoaMap(realm); List<String> result = new ArrayList<>(realmAcrLoaMap.keySet()); // Add LoA levels configured in authentication flow in addition to the realm values result.addAll(LoAUtil.getLoAConfiguredInRealmBrowserFlow(realm) .map(String::valueOf) .collect(Collectors.toList())); return result; } private List<String> getSupportedEncryptionAlgorithms() { return getSupportedAlgorithms(CekManagementProvider.class, false); } private List<String> getSupportedBackchannelAuthenticationRequestSigningAlgorithms() { return getSupportedAsymmetricAlgorithms(); } private List<String> getSupportedEncryptionAlg(boolean includeNone) { return getSupportedAlgorithms(CekManagementProvider.class, includeNone); } private List<String> getSupportedEncryptionEnc(boolean includeNone) { return getSupportedAlgorithms(ContentEncryptionProvider.class, includeNone); } // Use protected method to make it easier to override in custom provider if different URLs are requested to be used as mtls_endpoint_aliases protected MTLSEndpointAliases getMtlsEndpointAliases(OIDCConfigurationRepresentation config) { MTLSEndpointAliases mtls_endpoints = new MTLSEndpointAliases(); mtls_endpoints .setTokenEndpoint(config.getTokenEndpoint()); mtls_endpoints .setRevocationEndpoint(config.getRevocationEndpoint()); mtls_endpoints .setIntrospectionEndpoint(config.getIntrospectionEndpoint()); if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) { mtls_endpoints .setDeviceAuthorizationEndpoint(config.getDeviceAuthorizationEndpoint()); } mtls_endpoints .setRegistrationEndpoint(config.getRegistrationEndpoint()); mtls_endpoints .setUserInfoEndpoint(config.getUserinfoEndpoint()); mtls_endpoints .setBackchannelAuthenticationEndpoint(config.getBackchannelAuthenticationEndpoint()); mtls_endpoints .setPushedAuthorizationRequestEndpoint(config.getPushedAuthorizationRequestEndpoint()); return mtls_endpoints ; } private OIDCConfigurationRepresentation checkConfigOverride(OIDCConfigurationRepresentation config) { if (openidConfigOverride != null) { Map<String, Object> asMap = JsonSerialization.mapper.convertValue(config, Map.class); // Override configuration asMap.putAll(openidConfigOverride); return JsonSerialization.mapper.convertValue(asMap, OIDCConfigurationRepresentation.class); } else { return config; } } }
|
java
|
package cn.binarywang.wx.miniapp.api; import cn.binarywang.wx.miniapp.bean.WxMaApiResponse; import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult; import cn.binarywang.wx.miniapp.config.WxMaConfig; import cn.binarywang.wx.miniapp.executor.ApiSignaturePostRequestExecutor; import com.google.gson.JsonObject; import java.util.Map; import java.util.function.Function; import me.chanjar.weixin.common.error. <mask> <mask> <mask> <mask> <mask> <mask> ; import me.chanjar.weixin.common.service.WxImgProcService; import me.chanjar.weixin.common.service.WxOcrService; import me.chanjar.weixin.common.service.WxService; import me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor; import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; /** * The interface Wx ma service. * * @author <a href="https://github.com/binarywang">Binary Wang</a> */ public interface WxMaService extends WxService { /** 获取access_token. */ String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"; String GET_STABLE_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/stable_token"; /** The constant JSCODE_TO_SESSION_URL. */ String JSCODE_TO_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session"; /** getPaidUnionId */ String GET_PAID_UNION_ID_URL = "https://api.weixin.qq.com/wxa/getpaidunionid"; /** 导入抽样数据 */ String SET_DYNAMIC_DATA_URL = "https://api.weixin.qq.com/wxa/setdynamicdata"; /** * 获取登录后的session信息. * * @param jsCode 登录时获取的 code * @return the wx ma jscode 2 session result * @throws <mask> <mask> <mask> <mask> <mask> <mask> the wx error exception */ WxMaJscode2SessionResult jsCode2SessionInfo(String jsCode) throws <mask> <mask> <mask> <mask> <mask> <mask> ; /** * 导入抽样数据 * * <pre> * 第三方通过调用微信API,将数据写入到setdynamicdata这个API。每个Post数据包不超过5K,若数据过多可开多进(线)程并发导入数据(例如:数据量为十万量级可以开50个线程并行导数据)。 * 文档地址:https://wsad.weixin.qq.com/wsad/zh_CN/htmledition/widget-docs-v3/html/custom/quickstart/implement/import/index.html * http请求方式:POST http(s)://api.weixin.qq.com/wxa/setdynamicdata?access_token=ACCESS_TOKEN * </pre> * * @param lifespan 数据有效时间,秒为单位,一般为86400,一天一次导入的频率 * @param type 用于标识数据所属的服务类目 * @param scene 1代表用于搜索的数据 * @param data 推送到微信后台的数据列表,该数据被微信用于流量分配,注意该字段为string类型而不是object * @throws <mask> <mask> <mask> <mask> <mask> <mask> . */ void setDynamicData(int lifespan, String type, int scene, String data) throws <mask> <mask> <mask> <mask> <mask> <mask> ; /** * * * <pre> * 验证消息的确来自微信服务器. * 详情请见: http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421135319&token=&lang=zh_CN * </pre> * * @param timestamp the timestamp * @param nonce the nonce * @param signature the signature * @return the boolean */ boolean checkSignature(String timestamp, String nonce, String signature); /** * 获取access_token, 不强制刷新access_token. * * @return the access token * @throws <mask> <mask> <mask> <mask> <mask> <mask> the wx error exception * @see #getAccessToken(boolean) #getAccessToken(boolean) */ String getAccessToken() throws <mask> <mask> <mask> <mask> <mask> <mask> ; /** * * * <pre> * 获取access_token,本方法线程安全. * 且在多线程同时刷新时只刷新一次,避免超出2000次/日的调用次数上限 * * 另:本service的所有方法都会在access_token过期是调用此方法 * * 程序员在非必要情况下尽量不要主动调用此方法 * * 详情请见: http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183&token=&lang=zh_CN * </pre> * * @param forceRefresh 强制刷新 * @return the access token * @throws <mask> <mask> <mask> <mask> <mask> <mask> the
|
package cn.binarywang.wx.miniapp.api; import cn.binarywang.wx.miniapp.bean.WxMaApiResponse; import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult; import cn.binarywang.wx.miniapp.config.WxMaConfig; import cn.binarywang.wx.miniapp.executor.ApiSignaturePostRequestExecutor; import com.google.gson.JsonObject; import java.util.Map; import java.util.function.Function; import me.chanjar.weixin.common.error. WxErrorException ; import me.chanjar.weixin.common.service.WxImgProcService; import me.chanjar.weixin.common.service.WxOcrService; import me.chanjar.weixin.common.service.WxService; import me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor; import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; /** * The interface Wx ma service. * * @author <a href="https://github.com/binarywang">Binary Wang</a> */ public interface WxMaService extends WxService { /** 获取access_token. */ String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"; String GET_STABLE_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/stable_token"; /** The constant JSCODE_TO_SESSION_URL. */ String JSCODE_TO_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session"; /** getPaidUnionId */ String GET_PAID_UNION_ID_URL = "https://api.weixin.qq.com/wxa/getpaidunionid"; /** 导入抽样数据 */ String SET_DYNAMIC_DATA_URL = "https://api.weixin.qq.com/wxa/setdynamicdata"; /** * 获取登录后的session信息. * * @param jsCode 登录时获取的 code * @return the wx ma jscode 2 session result * @throws WxErrorException the wx error exception */ WxMaJscode2SessionResult jsCode2SessionInfo(String jsCode) throws WxErrorException ; /** * 导入抽样数据 * * <pre> * 第三方通过调用微信API,将数据写入到setdynamicdata这个API。每个Post数据包不超过5K,若数据过多可开多进(线)程并发导入数据(例如:数据量为十万量级可以开50个线程并行导数据)。 * 文档地址:https://wsad.weixin.qq.com/wsad/zh_CN/htmledition/widget-docs-v3/html/custom/quickstart/implement/import/index.html * http请求方式:POST http(s)://api.weixin.qq.com/wxa/setdynamicdata?access_token=ACCESS_TOKEN * </pre> * * @param lifespan 数据有效时间,秒为单位,一般为86400,一天一次导入的频率 * @param type 用于标识数据所属的服务类目 * @param scene 1代表用于搜索的数据 * @param data 推送到微信后台的数据列表,该数据被微信用于流量分配,注意该字段为string类型而不是object * @throws WxErrorException . */ void setDynamicData(int lifespan, String type, int scene, String data) throws WxErrorException ; /** * * * <pre> * 验证消息的确来自微信服务器. * 详情请见: http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421135319&token=&lang=zh_CN * </pre> * * @param timestamp the timestamp * @param nonce the nonce * @param signature the signature * @return the boolean */ boolean checkSignature(String timestamp, String nonce, String signature); /** * 获取access_token, 不强制刷新access_token. * * @return the access token * @throws WxErrorException the wx error exception * @see #getAccessToken(boolean) #getAccessToken(boolean) */ String getAccessToken() throws WxErrorException ; /** * * * <pre> * 获取access_token,本方法线程安全. * 且在多线程同时刷新时只刷新一次,避免超出2000次/日的调用次数上限 * * 另:本service的所有方法都会在access_token过期是调用此方法 * * 程序员在非必要情况下尽量不要主动调用此方法 * * 详情请见: http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183&token=&lang=zh_CN * </pre> * * @param forceRefresh 强制刷新 * @return the access token * @throws WxErrorException the
|
java
|
package cn.binarywang.wx.miniapp.api; import cn.binarywang.wx.miniapp.bean.WxMaApiResponse; import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult; import cn.binarywang.wx.miniapp.config.WxMaConfig; import cn.binarywang.wx.miniapp.executor.ApiSignaturePostRequestExecutor; import com.google.gson.JsonObject; import java.util.Map; import java.util.function.Function; import me.chanjar.weixin.common.error. <mask> <mask> <mask> <mask> <mask> <mask> ; import me.chanjar.weixin.common.service.WxImgProcService; import me.chanjar.weixin.common.service.WxOcrService; import me.chanjar.weixin.common.service.WxService; import me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor; import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; /** * The interface Wx ma service. * * @author <a href="https://github.com/binarywang">Binary Wang</a> */ public interface WxMaService extends WxService { /** 获取access_token. */ String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"; String GET_STABLE_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/stable_token"; /** The constant JSCODE_TO_SESSION_URL. */ String JSCODE_TO_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session"; /** getPaidUnionId */ String GET_PAID_UNION_ID_URL = "https://api.weixin.qq.com/wxa/getpaidunionid"; /** 导入抽样数据 */ String SET_DYNAMIC_DATA_URL = "https://api.weixin.qq.com/wxa/setdynamicdata"; /** * 获取登录后的session信息. * * @param jsCode 登录时获取的 code * @return the wx ma jscode 2 session result * @throws <mask> <mask> <mask> <mask> <mask> <mask> the wx error exception */ WxMaJscode2SessionResult jsCode2SessionInfo(String jsCode) throws <mask> <mask> <mask> <mask> <mask> <mask> ; /** * 导入抽样数据 * * <pre> * 第三方通过调用微信API,将数据写入到setdynamicdata这个API。每个Post数据包不超过5K,若数据过多可开多进(线)程并发导入数据(例如:数据量为十万量级可以开50个线程并行导数据)。 * 文档地址:https://wsad.weixin.qq.com/wsad/zh_CN/htmledition/widget-docs-v3/html/custom/quickstart/implement/import/index.html * http请求方式:POST http(s)://api.weixin.qq.com/wxa/setdynamicdata?access_token=ACCESS_TOKEN * </pre> * * @param lifespan 数据有效时间,秒为单位,一般为86400,一天一次导入的频率 * @param type 用于标识数据所属的服务类目 * @param scene 1代表用于搜索的数据 * @param data 推送到微信后台的数据列表,该数据被微信用于流量分配,注意该字段为string类型而不是object * @throws <mask> <mask> <mask> <mask> <mask> <mask> . */ void setDynamicData(int lifespan, String type, int scene, String data) throws <mask> <mask> <mask> <mask> <mask> <mask> ; /** * * * <pre> * 验证消息的确来自微信服务器. * 详情请见: http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421135319&token=&lang=zh_CN * </pre> * * @param timestamp the timestamp * @param nonce the nonce * @param signature the signature * @return the boolean */ boolean checkSignature(String timestamp, String nonce, String signature); /** * 获取access_token, 不强制刷新access_token. * * @return the access token * @throws <mask> <mask> <mask> <mask> <mask> <mask> the wx error exception * @see #getAccessToken(boolean) #getAccessToken(boolean) */ String getAccessToken() throws <mask> <mask> <mask> <mask> <mask> <mask> ; /** * * * <pre> * 获取access_token,本方法线程安全. * 且在多线程同时刷新时只刷新一次,避免超出2000次/日的调用次数上限 * * 另:本service的所有方法都会在access_token过期是调用此方法 * * 程序员在非必要情况下尽量不要主动调用此方法 * * 详情请见: http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183&token=&lang=zh_CN * </pre> * * @param forceRefresh 强制刷新 * @return the access token * @throws <mask> <mask> <mask> <mask> <mask> <mask> the wx error exception */ String getAccessToken(boolean forceRefresh) throws <mask> <mask> <mask> <mask> <mask> <mask> ; /** * * * <pre> * 用户支付完成后,获取该用户的 UnionId,无需用户授权。本接口支持第三方平台代理查询。 * * 注意:调用前需要用户完成支付,且在支付后的五分钟内有效。 * 请求地址: GET https://api.weixin.qq.com/wxa/getpaidunionid?access_token=ACCESS_TOKEN&openid=OPENID * 文档地址:https://developers.weixin.qq.com/miniprogram/dev/api/getPaidUnionId.html * </pre> * * @param openid 必填 支付用户唯一标识 * @param transactionId 非必填 微信支付订单号 * @param mchId 非必填 微信支付分配的商户号,和商户订单号配合使用 * @param outTradeNo 非必填 微信支付商户订单号,和商户号配合使用 * @return UnionId. paid union id * @throws <mask> <mask> <mask> <mask> <mask> <mask> . */ String getPaidUnionId(String openid, String transactionId, String mchId, String outTradeNo) throws <mask> <mask> <mask> <mask> <mask> <mask> ; /** * * * <pre> * Service没有实现某个API的时候,可以用这个, * 比{@link #get}和{@link #post}方法更灵活,可以自己构造RequestExecutor用来处理不同的参数和不同的返回类型。 * 可以参考,{@link MediaUploadRequestExecutor}的实现方法 *
|
package cn.binarywang.wx.miniapp.api; import cn.binarywang.wx.miniapp.bean.WxMaApiResponse; import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult; import cn.binarywang.wx.miniapp.config.WxMaConfig; import cn.binarywang.wx.miniapp.executor.ApiSignaturePostRequestExecutor; import com.google.gson.JsonObject; import java.util.Map; import java.util.function.Function; import me.chanjar.weixin.common.error. WxErrorException ; import me.chanjar.weixin.common.service.WxImgProcService; import me.chanjar.weixin.common.service.WxOcrService; import me.chanjar.weixin.common.service.WxService; import me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor; import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; /** * The interface Wx ma service. * * @author <a href="https://github.com/binarywang">Binary Wang</a> */ public interface WxMaService extends WxService { /** 获取access_token. */ String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"; String GET_STABLE_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/stable_token"; /** The constant JSCODE_TO_SESSION_URL. */ String JSCODE_TO_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session"; /** getPaidUnionId */ String GET_PAID_UNION_ID_URL = "https://api.weixin.qq.com/wxa/getpaidunionid"; /** 导入抽样数据 */ String SET_DYNAMIC_DATA_URL = "https://api.weixin.qq.com/wxa/setdynamicdata"; /** * 获取登录后的session信息. * * @param jsCode 登录时获取的 code * @return the wx ma jscode 2 session result * @throws WxErrorException the wx error exception */ WxMaJscode2SessionResult jsCode2SessionInfo(String jsCode) throws WxErrorException ; /** * 导入抽样数据 * * <pre> * 第三方通过调用微信API,将数据写入到setdynamicdata这个API。每个Post数据包不超过5K,若数据过多可开多进(线)程并发导入数据(例如:数据量为十万量级可以开50个线程并行导数据)。 * 文档地址:https://wsad.weixin.qq.com/wsad/zh_CN/htmledition/widget-docs-v3/html/custom/quickstart/implement/import/index.html * http请求方式:POST http(s)://api.weixin.qq.com/wxa/setdynamicdata?access_token=ACCESS_TOKEN * </pre> * * @param lifespan 数据有效时间,秒为单位,一般为86400,一天一次导入的频率 * @param type 用于标识数据所属的服务类目 * @param scene 1代表用于搜索的数据 * @param data 推送到微信后台的数据列表,该数据被微信用于流量分配,注意该字段为string类型而不是object * @throws WxErrorException . */ void setDynamicData(int lifespan, String type, int scene, String data) throws WxErrorException ; /** * * * <pre> * 验证消息的确来自微信服务器. * 详情请见: http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421135319&token=&lang=zh_CN * </pre> * * @param timestamp the timestamp * @param nonce the nonce * @param signature the signature * @return the boolean */ boolean checkSignature(String timestamp, String nonce, String signature); /** * 获取access_token, 不强制刷新access_token. * * @return the access token * @throws WxErrorException the wx error exception * @see #getAccessToken(boolean) #getAccessToken(boolean) */ String getAccessToken() throws WxErrorException ; /** * * * <pre> * 获取access_token,本方法线程安全. * 且在多线程同时刷新时只刷新一次,避免超出2000次/日的调用次数上限 * * 另:本service的所有方法都会在access_token过期是调用此方法 * * 程序员在非必要情况下尽量不要主动调用此方法 * * 详情请见: http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183&token=&lang=zh_CN * </pre> * * @param forceRefresh 强制刷新 * @return the access token * @throws WxErrorException the wx error exception */ String getAccessToken(boolean forceRefresh) throws WxErrorException ; /** * * * <pre> * 用户支付完成后,获取该用户的 UnionId,无需用户授权。本接口支持第三方平台代理查询。 * * 注意:调用前需要用户完成支付,且在支付后的五分钟内有效。 * 请求地址: GET https://api.weixin.qq.com/wxa/getpaidunionid?access_token=ACCESS_TOKEN&openid=OPENID * 文档地址:https://developers.weixin.qq.com/miniprogram/dev/api/getPaidUnionId.html * </pre> * * @param openid 必填 支付用户唯一标识 * @param transactionId 非必填 微信支付订单号 * @param mchId 非必填 微信支付分配的商户号,和商户订单号配合使用 * @param outTradeNo 非必填 微信支付商户订单号,和商户号配合使用 * @return UnionId. paid union id * @throws WxErrorException . */ String getPaidUnionId(String openid, String transactionId, String mchId, String outTradeNo) throws WxErrorException ; /** * * * <pre> * Service没有实现某个API的时候,可以用这个, * 比{@link #get}和{@link #post}方法更灵活,可以自己构造RequestExecutor用来处理不同的参数和不同的返回类型。 * 可以参考,{@link MediaUploadRequestExecutor}的实现方法 *
|
java
|
package cn.binarywang.wx.miniapp.api; import cn.binarywang.wx.miniapp.bean.WxMaApiResponse; import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult; import cn.binarywang.wx.miniapp.config.WxMaConfig; import cn.binarywang.wx.miniapp.executor.ApiSignaturePostRequestExecutor; import com.google.gson.JsonObject; import java.util.Map; import java.util.function.Function; import me.chanjar.weixin.common.error. <mask> <mask> <mask> <mask> <mask> <mask> ; import me.chanjar.weixin.common.service.WxImgProcService; import me.chanjar.weixin.common.service.WxOcrService; import me.chanjar.weixin.common.service.WxService; import me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor; import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; /** * The interface Wx ma service. * * @author <a href="https://github.com/binarywang">Binary Wang</a> */ public interface WxMaService extends WxService { /** 获取access_token. */ String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"; String GET_STABLE_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/stable_token"; /** The constant JSCODE_TO_SESSION_URL. */ String JSCODE_TO_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session"; /** getPaidUnionId */ String GET_PAID_UNION_ID_URL = "https://api.weixin.qq.com/wxa/getpaidunionid"; /** 导入抽样数据 */ String SET_DYNAMIC_DATA_URL = "https://api.weixin.qq.com/wxa/setdynamicdata"; /** * 获取登录后的session信息. * * @param jsCode 登录时获取的 code * @return the wx ma jscode 2 session result * @throws <mask> <mask> <mask> <mask> <mask> <mask> the wx error exception */ WxMaJscode2SessionResult jsCode2SessionInfo(String jsCode) throws <mask> <mask> <mask> <mask> <mask> <mask> ; /** * 导入抽样数据 * * <pre> * 第三方通过调用微信API,将数据写入到setdynamicdata这个API。每个Post数据包不超过5K,若数据过多可开多进(线)程并发导入数据(例如:数据量为十万量级可以开50个线程并行导数据)。 * 文档地址:https://wsad.weixin.qq.com/wsad/zh_CN/htmledition/widget-docs-v3/html/custom/quickstart/implement/import/index.html * http请求方式:POST http(s)://api.weixin.qq.com/wxa/setdynamicdata?access_token=ACCESS_TOKEN * </pre> * * @param lifespan 数据有效时间,秒为单位,一般为86400,一天一次导入的频率 * @param type 用于标识数据所属的服务类目 * @param scene 1代表用于搜索的数据 * @param data 推送到微信后台的数据列表,该数据被微信用于流量分配,注意该字段为string类型而不是object * @throws <mask> <mask> <mask> <mask> <mask> <mask> . */ void setDynamicData(int lifespan, String type, int scene, String data) throws <mask> <mask> <mask> <mask> <mask> <mask> ; /** * * * <pre> * 验证消息的确来自微信服务器. * 详情请见: http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421135319&token=&lang=zh_CN * </pre> * * @param timestamp the timestamp * @param nonce the nonce * @param signature the signature * @return the boolean */ boolean checkSignature(String timestamp, String nonce, String signature); /** * 获取access_token, 不强制刷新access_token. * * @return the access token * @throws <mask> <mask> <mask> <mask> <mask> <mask> the wx error exception * @see #getAccessToken(boolean) #getAccessToken(boolean) */ String getAccessToken() throws <mask> <mask> <mask> <mask> <mask> <mask> ; /** * * * <pre> * 获取access_token,本方法线程安全. * 且在多线程同时刷新时只刷新一次,避免超出2000次/日的调用次数上限 * * 另:本service的所有方法都会在access_token过期是调用此方法 * * 程序员在非必要情况下尽量不要主动调用此方法 * * 详情请见: http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183&token=&lang=zh_CN * </pre> * * @param forceRefresh 强制刷新 * @return the access token * @throws <mask> <mask> <mask> <mask> <mask> <mask> the wx error exception */ String getAccessToken(boolean forceRefresh) throws <mask> <mask> <mask> <mask> <mask> <mask> ; /** * * * <pre> * 用户支付完成后,获取该用户的 UnionId,无需用户授权。本接口支持第三方平台代理查询。 * * 注意:调用前需要用户完成支付,且在支付后的五分钟内有效。 * 请求地址: GET https://api.weixin.qq.com/wxa/getpaidunionid?access_token=ACCESS_TOKEN&openid=OPENID * 文档地址:https://developers.weixin.qq.com/miniprogram/dev/api/getPaidUnionId.html * </pre> * * @param openid 必填 支付用户唯一标识 * @param transactionId 非必填 微信支付订单号 * @param mchId 非必填 微信支付分配的商户号,和商户订单号配合使用 * @param outTradeNo 非必填 微信支付商户订单号,和商户号配合使用 * @return UnionId. paid union id * @throws <mask> <mask> <mask> <mask> <mask> <mask> . */ String getPaidUnionId(String openid, String transactionId, String mchId, String outTradeNo) throws <mask> <mask> <mask> <mask> <mask> <mask> ; /** * * * <pre> * Service没有实现某个API的时候,可以用这个, * 比{@link #get}和{@link #post}方法更灵活,可以自己构造RequestExecutor用来处理不同的参数和不同的返回类型。 * 可以参考,{@link MediaUploadRequestExecutor}的实现方法 * </pre> * * @param <T> . * @param <E> .
|
package cn.binarywang.wx.miniapp.api; import cn.binarywang.wx.miniapp.bean.WxMaApiResponse; import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult; import cn.binarywang.wx.miniapp.config.WxMaConfig; import cn.binarywang.wx.miniapp.executor.ApiSignaturePostRequestExecutor; import com.google.gson.JsonObject; import java.util.Map; import java.util.function.Function; import me.chanjar.weixin.common.error. WxErrorException ; import me.chanjar.weixin.common.service.WxImgProcService; import me.chanjar.weixin.common.service.WxOcrService; import me.chanjar.weixin.common.service.WxService; import me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor; import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; /** * The interface Wx ma service. * * @author <a href="https://github.com/binarywang">Binary Wang</a> */ public interface WxMaService extends WxService { /** 获取access_token. */ String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"; String GET_STABLE_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/stable_token"; /** The constant JSCODE_TO_SESSION_URL. */ String JSCODE_TO_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session"; /** getPaidUnionId */ String GET_PAID_UNION_ID_URL = "https://api.weixin.qq.com/wxa/getpaidunionid"; /** 导入抽样数据 */ String SET_DYNAMIC_DATA_URL = "https://api.weixin.qq.com/wxa/setdynamicdata"; /** * 获取登录后的session信息. * * @param jsCode 登录时获取的 code * @return the wx ma jscode 2 session result * @throws WxErrorException the wx error exception */ WxMaJscode2SessionResult jsCode2SessionInfo(String jsCode) throws WxErrorException ; /** * 导入抽样数据 * * <pre> * 第三方通过调用微信API,将数据写入到setdynamicdata这个API。每个Post数据包不超过5K,若数据过多可开多进(线)程并发导入数据(例如:数据量为十万量级可以开50个线程并行导数据)。 * 文档地址:https://wsad.weixin.qq.com/wsad/zh_CN/htmledition/widget-docs-v3/html/custom/quickstart/implement/import/index.html * http请求方式:POST http(s)://api.weixin.qq.com/wxa/setdynamicdata?access_token=ACCESS_TOKEN * </pre> * * @param lifespan 数据有效时间,秒为单位,一般为86400,一天一次导入的频率 * @param type 用于标识数据所属的服务类目 * @param scene 1代表用于搜索的数据 * @param data 推送到微信后台的数据列表,该数据被微信用于流量分配,注意该字段为string类型而不是object * @throws WxErrorException . */ void setDynamicData(int lifespan, String type, int scene, String data) throws WxErrorException ; /** * * * <pre> * 验证消息的确来自微信服务器. * 详情请见: http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421135319&token=&lang=zh_CN * </pre> * * @param timestamp the timestamp * @param nonce the nonce * @param signature the signature * @return the boolean */ boolean checkSignature(String timestamp, String nonce, String signature); /** * 获取access_token, 不强制刷新access_token. * * @return the access token * @throws WxErrorException the wx error exception * @see #getAccessToken(boolean) #getAccessToken(boolean) */ String getAccessToken() throws WxErrorException ; /** * * * <pre> * 获取access_token,本方法线程安全. * 且在多线程同时刷新时只刷新一次,避免超出2000次/日的调用次数上限 * * 另:本service的所有方法都会在access_token过期是调用此方法 * * 程序员在非必要情况下尽量不要主动调用此方法 * * 详情请见: http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183&token=&lang=zh_CN * </pre> * * @param forceRefresh 强制刷新 * @return the access token * @throws WxErrorException the wx error exception */ String getAccessToken(boolean forceRefresh) throws WxErrorException ; /** * * * <pre> * 用户支付完成后,获取该用户的 UnionId,无需用户授权。本接口支持第三方平台代理查询。 * * 注意:调用前需要用户完成支付,且在支付后的五分钟内有效。 * 请求地址: GET https://api.weixin.qq.com/wxa/getpaidunionid?access_token=ACCESS_TOKEN&openid=OPENID * 文档地址:https://developers.weixin.qq.com/miniprogram/dev/api/getPaidUnionId.html * </pre> * * @param openid 必填 支付用户唯一标识 * @param transactionId 非必填 微信支付订单号 * @param mchId 非必填 微信支付分配的商户号,和商户订单号配合使用 * @param outTradeNo 非必填 微信支付商户订单号,和商户号配合使用 * @return UnionId. paid union id * @throws WxErrorException . */ String getPaidUnionId(String openid, String transactionId, String mchId, String outTradeNo) throws WxErrorException ; /** * * * <pre> * Service没有实现某个API的时候,可以用这个, * 比{@link #get}和{@link #post}方法更灵活,可以自己构造RequestExecutor用来处理不同的参数和不同的返回类型。 * 可以参考,{@link MediaUploadRequestExecutor}的实现方法 * </pre> * * @param <T> . * @param <E> .
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.