-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
CQLTester.java
1801 lines (1553 loc) · 63.7 KB
/
CQLTester.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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.cassandra.cql3;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.google.common.base.Objects;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import org.junit.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datastax.driver.core.*;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.ResultSet;
import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.concurrent.ScheduledExecutors;
import org.apache.cassandra.index.SecondaryIndexManager;
import org.apache.cassandra.schema.*;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.cql3.functions.FunctionName;
import org.apache.cassandra.cql3.functions.ThreadAwareSecurityManager;
import org.apache.cassandra.cql3.statements.ParsedStatement;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.commitlog.CommitLog;
import org.apache.cassandra.db.marshal.*;
import org.apache.cassandra.db.marshal.TupleType;
import org.apache.cassandra.dht.Murmur3Partitioner;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.exceptions.SyntaxException;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.locator.AbstractEndpointSnitch;
import org.apache.cassandra.schema.TableMetadata;
import org.apache.cassandra.serializers.TypeSerializer;
import org.apache.cassandra.service.ClientState;
import org.apache.cassandra.service.QueryState;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.transport.*;
import org.apache.cassandra.transport.ProtocolVersion;
import org.apache.cassandra.transport.messages.ResultMessage;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
import static junit.framework.Assert.assertNotNull;
/**
* Base class for CQL tests.
*/
public abstract class CQLTester
{
protected static final Logger logger = LoggerFactory.getLogger(CQLTester.class);
public static final String KEYSPACE = "cql_test_keyspace";
public static final String KEYSPACE_PER_TEST = "cql_test_keyspace_alt";
protected static final boolean USE_PREPARED_VALUES = Boolean.valueOf(System.getProperty("cassandra.test.use_prepared", "true"));
protected static final boolean REUSE_PREPARED = Boolean.valueOf(System.getProperty("cassandra.test.reuse_prepared", "true"));
protected static final long ROW_CACHE_SIZE_IN_MB = Integer.valueOf(System.getProperty("cassandra.test.row_cache_size_in_mb", "0"));
private static final AtomicInteger seqNumber = new AtomicInteger();
protected static final ByteBuffer TOO_BIG = ByteBuffer.allocate(FBUtilities.MAX_UNSIGNED_SHORT + 1024);
public static final String DATA_CENTER = "datacenter1";
public static final String RACK1 = "rack1";
private static org.apache.cassandra.transport.Server server;
protected static final int nativePort;
protected static final InetAddress nativeAddr;
private static final Map<ProtocolVersion, Cluster> clusters = new HashMap<>();
protected static final Map<ProtocolVersion, Session> sessions = new HashMap<>();
private static boolean isServerPrepared = false;
public static final List<ProtocolVersion> PROTOCOL_VERSIONS = new ArrayList<>(ProtocolVersion.SUPPORTED.size());
private static final String CREATE_INDEX_NAME_REGEX = "(\\s*(\\w*|\"\\w*\")\\s*)";
private static final String CREATE_INDEX_REGEX = String.format("\\A\\s*CREATE(?:\\s+CUSTOM)?\\s+INDEX" +
"(?:\\s+IF\\s+NOT\\s+EXISTS)?\\s*" +
"%s?\\s*ON\\s+(%<s\\.)?%<s\\s*" +
"(\\((?:\\s*\\w+\\s*\\()?%<s\\))?",
CREATE_INDEX_NAME_REGEX);
private static final Pattern CREATE_INDEX_PATTERN = Pattern.compile(CREATE_INDEX_REGEX, Pattern.CASE_INSENSITIVE);
/** Return the current server version if supported by the driver, else
* the latest that is supported.
*
* @return - the preferred versions that is also supported by the driver
*/
public static final ProtocolVersion getDefaultVersion()
{
return PROTOCOL_VERSIONS.contains(ProtocolVersion.CURRENT)
? ProtocolVersion.CURRENT
: PROTOCOL_VERSIONS.get(PROTOCOL_VERSIONS.size() - 1);
}
static
{
DatabaseDescriptor.daemonInitialization();
// The latest versions might not be supported yet by the java driver
for (ProtocolVersion version : ProtocolVersion.SUPPORTED)
{
try
{
com.datastax.driver.core.ProtocolVersion.fromInt(version.asInt());
PROTOCOL_VERSIONS.add(version);
}
catch (IllegalArgumentException e)
{
logger.warn("Protocol Version {} not supported by java driver", version);
}
}
nativeAddr = InetAddress.getLoopbackAddress();
// Register an EndpointSnitch which returns fixed values for test.
DatabaseDescriptor.setEndpointSnitch(new AbstractEndpointSnitch()
{
@Override public String getRack(InetAddress endpoint) { return RACK1; }
@Override public String getDatacenter(InetAddress endpoint) { return DATA_CENTER; }
@Override public int compareEndpoints(InetAddress target, InetAddress a1, InetAddress a2) { return 0; }
});
try
{
try (ServerSocket serverSocket = new ServerSocket(0))
{
nativePort = serverSocket.getLocalPort();
}
Thread.sleep(250);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public static ResultMessage lastSchemaChangeResult;
private List<String> keyspaces = new ArrayList<>();
private List<String> tables = new ArrayList<>();
private List<String> types = new ArrayList<>();
private List<String> functions = new ArrayList<>();
private List<String> aggregates = new ArrayList<>();
// We don't use USE_PREPARED_VALUES in the code below so some test can foce value preparation (if the result
// is not expected to be the same without preparation)
private boolean usePrepared = USE_PREPARED_VALUES;
private static boolean reusePrepared = REUSE_PREPARED;
protected boolean usePrepared()
{
return usePrepared;
}
public static void prepareServer()
{
if (isServerPrepared)
return;
DatabaseDescriptor.daemonInitialization();
// Cleanup first
try
{
cleanupAndLeaveDirs();
}
catch (IOException e)
{
logger.error("Failed to cleanup and recreate directories.");
throw new RuntimeException(e);
}
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
{
public void uncaughtException(Thread t, Throwable e)
{
logger.error("Fatal exception in thread " + t, e);
}
});
ThreadAwareSecurityManager.install();
Keyspace.setInitialized();
SystemKeyspace.persistLocalMetadata();
isServerPrepared = true;
}
public static void cleanupAndLeaveDirs() throws IOException
{
// We need to stop and unmap all CLS instances prior to cleanup() or we'll get failures on Windows.
CommitLog.instance.stopUnsafe(true);
mkdirs();
cleanup();
mkdirs();
CommitLog.instance.restartUnsafe();
}
public static void cleanup()
{
// clean up commitlog
String[] directoryNames = { DatabaseDescriptor.getCommitLogLocation(), };
for (String dirName : directoryNames)
{
File dir = new File(dirName);
if (!dir.exists())
throw new RuntimeException("No such directory: " + dir.getAbsolutePath());
FileUtils.deleteRecursive(dir);
}
File cdcDir = new File(DatabaseDescriptor.getCDCLogLocation());
if (cdcDir.exists())
FileUtils.deleteRecursive(cdcDir);
cleanupSavedCaches();
// clean up data directory which are stored as data directory/keyspace/data files
for (String dirName : DatabaseDescriptor.getAllDataFileLocations())
{
File dir = new File(dirName);
if (!dir.exists())
throw new RuntimeException("No such directory: " + dir.getAbsolutePath());
FileUtils.deleteRecursive(dir);
}
}
public static void mkdirs()
{
DatabaseDescriptor.createAllDirectories();
}
public static void cleanupSavedCaches()
{
File cachesDir = new File(DatabaseDescriptor.getSavedCachesLocation());
if (!cachesDir.exists() || !cachesDir.isDirectory())
return;
FileUtils.delete(cachesDir.listFiles());
}
@BeforeClass
public static void setUpClass()
{
if (ROW_CACHE_SIZE_IN_MB > 0)
DatabaseDescriptor.setRowCacheSizeInMB(ROW_CACHE_SIZE_IN_MB);
StorageService.instance.setPartitionerUnsafe(Murmur3Partitioner.instance);
// Once per-JVM is enough
prepareServer();
}
@AfterClass
public static void tearDownClass()
{
for (Session sess : sessions.values())
sess.close();
for (Cluster cl : clusters.values())
cl.close();
if (server != null)
server.stop();
// We use queryInternal for CQLTester so prepared statement will populate our internal cache (if reusePrepared is used; otherwise prepared
// statements are not cached but re-prepared every time). So we clear the cache between test files to avoid accumulating too much.
if (reusePrepared)
QueryProcessor.clearInternalStatementsCache();
}
@Before
public void beforeTest() throws Throwable
{
schemaChange(String.format("CREATE KEYSPACE IF NOT EXISTS %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'}", KEYSPACE));
schemaChange(String.format("CREATE KEYSPACE IF NOT EXISTS %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'}", KEYSPACE_PER_TEST));
}
@After
public void afterTest() throws Throwable
{
dropPerTestKeyspace();
// Restore standard behavior in case it was changed
usePrepared = USE_PREPARED_VALUES;
reusePrepared = REUSE_PREPARED;
final List<String> keyspacesToDrop = copy(keyspaces);
final List<String> tablesToDrop = copy(tables);
final List<String> typesToDrop = copy(types);
final List<String> functionsToDrop = copy(functions);
final List<String> aggregatesToDrop = copy(aggregates);
keyspaces = null;
tables = null;
types = null;
functions = null;
aggregates = null;
// We want to clean up after the test, but dropping a table is rather long so just do that asynchronously
ScheduledExecutors.optionalTasks.execute(new Runnable()
{
public void run()
{
try
{
for (int i = tablesToDrop.size() - 1; i >= 0; i--)
schemaChange(String.format("DROP TABLE IF EXISTS %s.%s", KEYSPACE, tablesToDrop.get(i)));
for (int i = aggregatesToDrop.size() - 1; i >= 0; i--)
schemaChange(String.format("DROP AGGREGATE IF EXISTS %s", aggregatesToDrop.get(i)));
for (int i = functionsToDrop.size() - 1; i >= 0; i--)
schemaChange(String.format("DROP FUNCTION IF EXISTS %s", functionsToDrop.get(i)));
for (int i = typesToDrop.size() - 1; i >= 0; i--)
schemaChange(String.format("DROP TYPE IF EXISTS %s.%s", KEYSPACE, typesToDrop.get(i)));
for (int i = keyspacesToDrop.size() - 1; i >= 0; i--)
schemaChange(String.format("DROP KEYSPACE IF EXISTS %s", keyspacesToDrop.get(i)));
// Dropping doesn't delete the sstables. It's not a huge deal but it's cleaner to cleanup after us
// Thas said, we shouldn't delete blindly before the TransactionLogs.SSTableTidier for the table we drop
// have run or they will be unhappy. Since those taks are scheduled on StorageService.tasks and that's
// mono-threaded, just push a task on the queue to find when it's empty. No perfect but good enough.
final CountDownLatch latch = new CountDownLatch(1);
ScheduledExecutors.nonPeriodicTasks.execute(new Runnable()
{
public void run()
{
latch.countDown();
}
});
latch.await(2, TimeUnit.SECONDS);
removeAllSSTables(KEYSPACE, tablesToDrop);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
});
}
// lazy initialization for all tests that require Java Driver
protected static void requireNetwork() throws ConfigurationException
{
if (server != null)
return;
SystemKeyspace.finishStartup();
StorageService.instance.initServer();
SchemaLoader.startGossiper();
server = new Server.Builder().withHost(nativeAddr).withPort(nativePort).build();
server.start();
for (ProtocolVersion version : PROTOCOL_VERSIONS)
{
if (clusters.containsKey(version))
continue;
Cluster.Builder builder = Cluster.builder()
.withoutJMXReporting()
.addContactPoints(nativeAddr)
.withClusterName("Test Cluster")
.withPort(nativePort);
if (version.isBeta())
builder = builder.allowBetaProtocolVersion();
else
builder = builder.withProtocolVersion(com.datastax.driver.core.ProtocolVersion.fromInt(version.asInt()));
Cluster cluster = builder.build();
clusters.put(version, cluster);
sessions.put(version, cluster.connect());
logger.info("Started Java Driver instance for protocol version {}", version);
}
}
protected void dropPerTestKeyspace() throws Throwable
{
execute(String.format("DROP KEYSPACE IF EXISTS %s", KEYSPACE_PER_TEST));
}
/**
* Returns a copy of the specified list.
* @return a copy of the specified list.
*/
private static List<String> copy(List<String> list)
{
return list.isEmpty() ? Collections.<String>emptyList() : new ArrayList<>(list);
}
public ColumnFamilyStore getCurrentColumnFamilyStore()
{
return getCurrentColumnFamilyStore(KEYSPACE);
}
public ColumnFamilyStore getCurrentColumnFamilyStore(String keyspace)
{
String currentTable = currentTable();
return currentTable == null
? null
: Keyspace.open(keyspace).getColumnFamilyStore(currentTable);
}
public void flush(boolean forceFlush)
{
if (forceFlush)
flush();
}
public void flush()
{
flush(KEYSPACE);
}
public void flush(String keyspace)
{
ColumnFamilyStore store = getCurrentColumnFamilyStore(keyspace);
if (store != null)
store.forceBlockingFlush();
}
public void disableCompaction(String keyspace)
{
ColumnFamilyStore store = getCurrentColumnFamilyStore(keyspace);
if (store != null)
store.disableAutoCompaction();
}
public void compact()
{
try
{
ColumnFamilyStore store = getCurrentColumnFamilyStore();
if (store != null)
store.forceMajorCompaction();
}
catch (InterruptedException | ExecutionException e)
{
throw new RuntimeException(e);
}
}
public void disableCompaction()
{
disableCompaction(KEYSPACE);
}
public void enableCompaction(String keyspace)
{
ColumnFamilyStore store = getCurrentColumnFamilyStore(keyspace);
if (store != null)
store.enableAutoCompaction();
}
public void enableCompaction()
{
enableCompaction(KEYSPACE);
}
public void cleanupCache()
{
ColumnFamilyStore store = getCurrentColumnFamilyStore();
if (store != null)
store.cleanupCache();
}
public static FunctionName parseFunctionName(String qualifiedName)
{
int i = qualifiedName.indexOf('.');
return i == -1
? FunctionName.nativeFunction(qualifiedName)
: new FunctionName(qualifiedName.substring(0, i).trim(), qualifiedName.substring(i+1).trim());
}
public static String shortFunctionName(String f)
{
return parseFunctionName(f).name;
}
private static void removeAllSSTables(String ks, List<String> tables)
{
// clean up data directory which are stored as data directory/keyspace/data files
for (File d : Directories.getKSChildDirectories(ks))
{
if (d.exists() && containsAny(d.getName(), tables))
FileUtils.deleteRecursive(d);
}
}
private static boolean containsAny(String filename, List<String> tables)
{
for (int i = 0, m = tables.size(); i < m; i++)
// don't accidentally delete in-use directories with the
// same prefix as a table to delete, i.e. table_1 & table_11
if (filename.contains(tables.get(i) + "-"))
return true;
return false;
}
protected String keyspace()
{
return KEYSPACE;
}
protected String currentTable()
{
if (tables.isEmpty())
return null;
return tables.get(tables.size() - 1);
}
protected ByteBuffer unset()
{
return ByteBufferUtil.UNSET_BYTE_BUFFER;
}
protected void forcePreparedValues()
{
this.usePrepared = true;
}
protected void stopForcingPreparedValues()
{
this.usePrepared = USE_PREPARED_VALUES;
}
protected void disablePreparedReuseForTest()
{
this.reusePrepared = false;
}
protected String createType(String query)
{
String typeName = "type_" + seqNumber.getAndIncrement();
String fullQuery = String.format(query, KEYSPACE + "." + typeName);
types.add(typeName);
logger.info(fullQuery);
schemaChange(fullQuery);
return typeName;
}
protected String createFunction(String keyspace, String argTypes, String query) throws Throwable
{
String functionName = keyspace + ".function_" + seqNumber.getAndIncrement();
createFunctionOverload(functionName, argTypes, query);
return functionName;
}
protected void createFunctionOverload(String functionName, String argTypes, String query) throws Throwable
{
String fullQuery = String.format(query, functionName);
functions.add(functionName + '(' + argTypes + ')');
logger.info(fullQuery);
schemaChange(fullQuery);
}
protected String createAggregate(String keyspace, String argTypes, String query) throws Throwable
{
String aggregateName = keyspace + "." + "aggregate_" + seqNumber.getAndIncrement();
createAggregateOverload(aggregateName, argTypes, query);
return aggregateName;
}
protected void createAggregateOverload(String aggregateName, String argTypes, String query) throws Throwable
{
String fullQuery = String.format(query, aggregateName);
aggregates.add(aggregateName + '(' + argTypes + ')');
logger.info(fullQuery);
schemaChange(fullQuery);
}
protected String createKeyspace(String query)
{
String currentKeyspace = createKeyspaceName();
String fullQuery = String.format(query, currentKeyspace);
logger.info(fullQuery);
schemaChange(fullQuery);
return currentKeyspace;
}
protected String createKeyspaceName()
{
String currentKeyspace = "keyspace_" + seqNumber.getAndIncrement();
keyspaces.add(currentKeyspace);
return currentKeyspace;
}
protected String createTable(String query)
{
return createTable(KEYSPACE, query);
}
protected String createTable(String keyspace, String query)
{
String currentTable = createTableName();
String fullQuery = formatQuery(keyspace, query);
logger.info(fullQuery);
schemaChange(fullQuery);
return currentTable;
}
protected String createTableName()
{
String currentTable = "table_" + seqNumber.getAndIncrement();
tables.add(currentTable);
return currentTable;
}
protected void createTableMayThrow(String query) throws Throwable
{
String currentTable = createTableName();
String fullQuery = formatQuery(query);
logger.info(fullQuery);
QueryProcessor.executeOnceInternal(fullQuery);
}
protected void alterTable(String query)
{
String fullQuery = formatQuery(query);
logger.info(fullQuery);
schemaChange(fullQuery);
}
protected void alterTableMayThrow(String query) throws Throwable
{
String fullQuery = formatQuery(query);
logger.info(fullQuery);
QueryProcessor.executeOnceInternal(fullQuery);
}
protected void dropTable(String query)
{
dropFormattedTable(String.format(query, KEYSPACE + "." + currentTable()));
}
protected void dropFormattedTable(String formattedQuery)
{
logger.info(formattedQuery);
schemaChange(formattedQuery);
}
protected String createIndex(String query)
{
String formattedQuery = formatQuery(query);
return createFormattedIndex(formattedQuery);
}
protected String createFormattedIndex(String formattedQuery)
{
logger.info(formattedQuery);
String indexName = getCreateIndexName(formattedQuery);
schemaChange(formattedQuery);
return indexName;
}
protected static String getCreateIndexName(String formattedQuery)
{
Matcher matcher = CREATE_INDEX_PATTERN.matcher(formattedQuery);
if (!matcher.find())
throw new IllegalArgumentException("Expected valid create index query but found: " + formattedQuery);
String index = matcher.group(2);
if (!Strings.isNullOrEmpty(index))
return index;
String keyspace = matcher.group(5);
if (Strings.isNullOrEmpty(keyspace))
throw new IllegalArgumentException("Keyspace name should be specified: " + formattedQuery);
String table = matcher.group(7);
if (Strings.isNullOrEmpty(table))
throw new IllegalArgumentException("Table name should be specified: " + formattedQuery);
String column = matcher.group(9);
return Indexes.getAvailableIndexName(keyspace, table, Strings.isNullOrEmpty(column) ? null : column);
}
/**
* Index creation is asynchronous, this method searches in the system table IndexInfo
* for the specified index and returns true if it finds it, which indicates the
* index was built. If we haven't found it after 5 seconds we give-up.
*/
protected boolean waitForIndex(String keyspace, String table, String index) throws Throwable
{
long start = System.currentTimeMillis();
boolean indexCreated = false;
while (!indexCreated)
{
Object[][] results = getRows(execute("select index_name from system.\"IndexInfo\" where table_name = ?", keyspace));
for(int i = 0; i < results.length; i++)
{
if (index.equals(results[i][0]))
{
indexCreated = true;
break;
}
}
if (System.currentTimeMillis() - start > 5000)
break;
Thread.sleep(10);
}
return indexCreated;
}
/**
* Index creation is asynchronous, this method waits until the specified index hasn't any building task running.
* <p>
* This method differs from {@link #waitForIndex(String, String, String)} in that it doesn't require the index to be
* fully nor successfully built, so it can be used to wait for failing index builds.
*
* @param keyspace the index keyspace name
* @param indexName the index name
* @return {@code true} if the index build tasks have finished in 5 seconds, {@code false} otherwise
*/
protected boolean waitForIndexBuilds(String keyspace, String indexName) throws InterruptedException
{
long start = System.currentTimeMillis();
SecondaryIndexManager indexManager = getCurrentColumnFamilyStore(keyspace).indexManager;
while (true)
{
if (!indexManager.isIndexBuilding(indexName))
{
return true;
}
else if (System.currentTimeMillis() - start > 5000)
{
return false;
}
else
{
Thread.sleep(10);
}
}
}
protected void createIndexMayThrow(String query) throws Throwable
{
String fullQuery = formatQuery(query);
logger.info(fullQuery);
QueryProcessor.executeOnceInternal(fullQuery);
}
protected void dropIndex(String query) throws Throwable
{
String fullQuery = String.format(query, KEYSPACE);
logger.info(fullQuery);
schemaChange(fullQuery);
}
protected void assertLastSchemaChange(Event.SchemaChange.Change change, Event.SchemaChange.Target target,
String keyspace, String name,
String... argTypes)
{
Assert.assertTrue(lastSchemaChangeResult instanceof ResultMessage.SchemaChange);
ResultMessage.SchemaChange schemaChange = (ResultMessage.SchemaChange) lastSchemaChangeResult;
Assert.assertSame(change, schemaChange.change.change);
Assert.assertSame(target, schemaChange.change.target);
Assert.assertEquals(keyspace, schemaChange.change.keyspace);
Assert.assertEquals(name, schemaChange.change.name);
Assert.assertEquals(argTypes != null ? Arrays.asList(argTypes) : null, schemaChange.change.argTypes);
}
protected static void schemaChange(String query)
{
try
{
ClientState state = ClientState.forInternalCalls();
state.setKeyspace(SchemaConstants.SYSTEM_KEYSPACE_NAME);
QueryState queryState = new QueryState(state);
ParsedStatement.Prepared prepared = QueryProcessor.parseStatement(query, queryState.getClientState());
prepared.statement.validate(state);
QueryOptions options = QueryOptions.forInternalCalls(Collections.<ByteBuffer>emptyList());
lastSchemaChangeResult = prepared.statement.executeInternal(queryState, options);
}
catch (Exception e)
{
logger.info("Error performing schema change", e);
throw new RuntimeException("Error setting schema for test (query was: " + query + ")", e);
}
}
protected TableMetadata currentTableMetadata()
{
return Schema.instance.getTableMetadata(KEYSPACE, currentTable());
}
protected com.datastax.driver.core.ResultSet executeNet(ProtocolVersion protocolVersion, String query, Object... values) throws Throwable
{
return sessionNet(protocolVersion).execute(formatQuery(query), values);
}
protected com.datastax.driver.core.ResultSet executeNetWithPaging(String query, int pageSize) throws Throwable
{
return sessionNet().execute(new SimpleStatement(formatQuery(query)).setFetchSize(pageSize));
}
protected Session sessionNet()
{
return sessionNet(getDefaultVersion());
}
protected Session sessionNet(ProtocolVersion protocolVersion)
{
requireNetwork();
return sessions.get(protocolVersion);
}
protected String formatQuery(String query)
{
return formatQuery(KEYSPACE, query);
}
protected final String formatQuery(String keyspace, String query)
{
String currentTable = currentTable();
return currentTable == null ? query : String.format(query, keyspace + "." + currentTable);
}
protected ResultMessage.Prepared prepare(String query) throws Throwable
{
return QueryProcessor.prepare(formatQuery(query), ClientState.forInternalCalls());
}
protected UntypedResultSet execute(String query, Object... values) throws Throwable
{
return executeFormattedQuery(formatQuery(query), values);
}
protected UntypedResultSet executeFormattedQuery(String query, Object... values) throws Throwable
{
UntypedResultSet rs;
if (usePrepared)
{
if (logger.isTraceEnabled())
logger.trace("Executing: {} with values {}", query, formatAllValues(values));
if (reusePrepared)
{
rs = QueryProcessor.executeInternal(query, transformValues(values));
// If a test uses a "USE ...", then presumably its statements use relative table. In that case, a USE
// change the meaning of the current keyspace, so we don't want a following statement to reuse a previously
// prepared statement at this wouldn't use the right keyspace. To avoid that, we drop the previously
// prepared statement.
if (query.startsWith("USE"))
QueryProcessor.clearInternalStatementsCache();
}
else
{
rs = QueryProcessor.executeOnceInternal(query, transformValues(values));
}
}
else
{
query = replaceValues(query, values);
if (logger.isTraceEnabled())
logger.trace("Executing: {}", query);
rs = QueryProcessor.executeOnceInternal(query);
}
if (rs != null)
{
if (logger.isTraceEnabled())
logger.trace("Got {} rows", rs.size());
}
return rs;
}
protected void assertRowsNet(ResultSet result, Object[]... rows)
{
assertRowsNet(getDefaultVersion(), result, rows);
}
protected void assertRowsNet(ProtocolVersion protocolVersion, ResultSet result, Object[]... rows)
{
// necessary as we need cluster objects to supply CodecRegistry.
// It's reasonably certain that the network setup has already been done
// by the time we arrive at this point, but adding this check doesn't hurt
requireNetwork();
if (result == null)
{
if (rows.length > 0)
Assert.fail(String.format("No rows returned by query but %d expected", rows.length));
return;
}
ColumnDefinitions meta = result.getColumnDefinitions();
Iterator<Row> iter = result.iterator();
int i = 0;
while (iter.hasNext() && i < rows.length)
{
Object[] expected = rows[i];
Row actual = iter.next();
Assert.assertEquals(String.format("Invalid number of (expected) values provided for row %d (using protocol version %s)",
i, protocolVersion),
meta.size(), expected.length);
for (int j = 0; j < meta.size(); j++)
{
DataType type = meta.getType(j);
com.datastax.driver.core.TypeCodec<Object> codec = clusters.get(protocolVersion).getConfiguration()
.getCodecRegistry()
.codecFor(type);
ByteBuffer expectedByteValue = codec.serialize(expected[j], com.datastax.driver.core.ProtocolVersion.fromInt(protocolVersion.asInt()));
int expectedBytes = expectedByteValue == null ? -1 : expectedByteValue.remaining();
ByteBuffer actualValue = actual.getBytesUnsafe(meta.getName(j));
int actualBytes = actualValue == null ? -1 : actualValue.remaining();
if (!Objects.equal(expectedByteValue, actualValue))
Assert.fail(String.format("Invalid value for row %d column %d (%s of type %s), " +
"expected <%s> (%d bytes) but got <%s> (%d bytes) " +
"(using protocol version %s)",
i, j, meta.getName(j), type,
codec.format(expected[j]),
expectedBytes,
codec.format(codec.deserialize(actualValue, com.datastax.driver.core.ProtocolVersion.fromInt(protocolVersion.asInt()))),
actualBytes,
protocolVersion));
}
i++;
}
if (iter.hasNext())
{
while (iter.hasNext())
{
iter.next();
i++;
}
Assert.fail(String.format("Got less rows than expected. Expected %d but got %d (using protocol version %s).",
rows.length, i, protocolVersion));
}
Assert.assertTrue(String.format("Got %s rows than expected. Expected %d but got %d (using protocol version %s)",
rows.length>i ? "less" : "more", rows.length, i, protocolVersion), i == rows.length);
}
public static void assertRows(UntypedResultSet result, Object[]... rows)
{
if (result == null)
{
if (rows.length > 0)
Assert.fail(String.format("No rows returned by query but %d expected", rows.length));
return;
}
List<ColumnSpecification> meta = result.metadata();
Iterator<UntypedResultSet.Row> iter = result.iterator();
int i = 0;
while (iter.hasNext() && i < rows.length)
{
Object[] expected = rows[i];
UntypedResultSet.Row actual = iter.next();
Assert.assertEquals(String.format("Invalid number of (expected) values provided for row %d", i), expected == null ? 1 : expected.length, meta.size());
for (int j = 0; j < meta.size(); j++)
{
ColumnSpecification column = meta.get(j);
ByteBuffer expectedByteValue = makeByteBuffer(expected == null ? null : expected[j], column.type);
ByteBuffer actualValue = actual.getBytes(column.name.toString());