-
Notifications
You must be signed in to change notification settings - Fork 993
/
TestUtil.java
996 lines (899 loc) · 47.4 KB
/
TestUtil.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
/*
* 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.phoenix.util;
import static org.apache.phoenix.query.BaseTest.generateUniqueName;
import static org.apache.phoenix.query.QueryConstants.MILLIS_IN_DAY;
import static org.apache.phoenix.query.QueryConstants.SINGLE_COLUMN_FAMILY_NAME;
import static org.apache.phoenix.query.QueryConstants.SINGLE_COLUMN_NAME;
import static org.apache.phoenix.util.PhoenixRuntime.CONNECTIONLESS;
import static org.apache.phoenix.util.PhoenixRuntime.JDBC_PROTOCOL;
import static org.apache.phoenix.util.PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR;
import static org.apache.phoenix.util.PhoenixRuntime.JDBC_PROTOCOL_TERMINATOR;
import static org.apache.phoenix.util.PhoenixRuntime.PHOENIX_TEST_DRIVER_URL_PARAM;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellScanner;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.coprocessor.Batch;
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.ipc.BlockingRpcCallback;
import org.apache.hadoop.hbase.ipc.ServerRpcController;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.phoenix.compile.AggregationManager;
import org.apache.phoenix.compile.SequenceManager;
import org.apache.phoenix.compile.StatementContext;
import org.apache.phoenix.coprocessor.generated.MetaDataProtos.ClearCacheRequest;
import org.apache.phoenix.coprocessor.generated.MetaDataProtos.ClearCacheResponse;
import org.apache.phoenix.coprocessor.generated.MetaDataProtos.MetaDataService;
import org.apache.phoenix.execute.MutationState;
import org.apache.phoenix.expression.AndExpression;
import org.apache.phoenix.expression.ByteBasedLikeExpression;
import org.apache.phoenix.expression.ComparisonExpression;
import org.apache.phoenix.expression.Expression;
import org.apache.phoenix.expression.InListExpression;
import org.apache.phoenix.expression.KeyValueColumnExpression;
import org.apache.phoenix.expression.LiteralExpression;
import org.apache.phoenix.expression.NotExpression;
import org.apache.phoenix.expression.OrExpression;
import org.apache.phoenix.expression.RowKeyColumnExpression;
import org.apache.phoenix.expression.StringBasedLikeExpression;
import org.apache.phoenix.expression.aggregator.ClientAggregators;
import org.apache.phoenix.expression.function.SingleAggregateFunction;
import org.apache.phoenix.expression.function.SubstrFunction;
import org.apache.phoenix.expression.function.SumAggregateFunction;
import org.apache.phoenix.filter.MultiCQKeyValueComparisonFilter;
import org.apache.phoenix.filter.MultiEncodedCQKeyValueComparisonFilter;
import org.apache.phoenix.filter.MultiKeyValueComparisonFilter;
import org.apache.phoenix.filter.RowKeyComparisonFilter;
import org.apache.phoenix.filter.SingleCQKeyValueComparisonFilter;
import org.apache.phoenix.filter.SingleKeyValueComparisonFilter;
import org.apache.phoenix.jdbc.PhoenixConnection;
import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData;
import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
import org.apache.phoenix.jdbc.PhoenixStatement;
import org.apache.phoenix.parse.LikeParseNode.LikeType;
import org.apache.phoenix.query.ConnectionQueryServices;
import org.apache.phoenix.query.KeyRange;
import org.apache.phoenix.query.QueryConstants;
import org.apache.phoenix.query.QueryServices;
import org.apache.phoenix.query.QueryServicesOptions;
import org.apache.phoenix.schema.PColumn;
import org.apache.phoenix.schema.PIndexState;
import org.apache.phoenix.schema.PLongColumn;
import org.apache.phoenix.schema.PName;
import org.apache.phoenix.schema.PTable;
import org.apache.phoenix.schema.PTable.QualifierEncodingScheme;
import org.apache.phoenix.schema.PTableKey;
import org.apache.phoenix.schema.RowKeyValueAccessor;
import org.apache.phoenix.schema.SortOrder;
import org.apache.phoenix.schema.TableRef;
import org.apache.phoenix.schema.stats.GuidePostsInfo;
import org.apache.phoenix.schema.stats.GuidePostsKey;
import org.apache.phoenix.schema.tuple.Tuple;
import org.apache.phoenix.schema.types.PDataType;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
public class TestUtil {
private static final Log LOG = LogFactory.getLog(TestUtil.class);
public static final String DEFAULT_SCHEMA_NAME = "";
public static final String DEFAULT_DATA_TABLE_NAME = "T";
public static final String DEFAULT_INDEX_TABLE_NAME = "I";
public static final String DEFAULT_DATA_TABLE_FULL_NAME = SchemaUtil.getTableName(DEFAULT_SCHEMA_NAME, "T");
public static final String DEFAULT_INDEX_TABLE_FULL_NAME = SchemaUtil.getTableName(DEFAULT_SCHEMA_NAME, "I");
public static final String TEST_TABLE_SCHEMA = "(" +
" varchar_pk VARCHAR NOT NULL, " +
" char_pk CHAR(10) NOT NULL, " +
" int_pk INTEGER NOT NULL, "+
" long_pk BIGINT NOT NULL, " +
" decimal_pk DECIMAL(31, 10) NOT NULL, " +
" date_pk DATE NOT NULL, " +
" a.varchar_col1 VARCHAR, " +
" a.char_col1 CHAR(10), " +
" a.int_col1 INTEGER, " +
" a.long_col1 BIGINT, " +
" a.decimal_col1 DECIMAL(31, 10), " +
" a.date1 DATE, " +
" b.varchar_col2 VARCHAR, " +
" b.char_col2 CHAR(10), " +
" b.int_col2 INTEGER, " +
" b.long_col2 BIGINT, " +
" b.decimal_col2 DECIMAL(31, 10), " +
" b.date2 DATE " +
" CONSTRAINT pk PRIMARY KEY (varchar_pk, char_pk, int_pk, long_pk DESC, decimal_pk, date_pk)) ";
private TestUtil() {
}
public static final String CF_NAME = "a";
public static final byte[] CF = Bytes.toBytes(CF_NAME);
public static final String CF2_NAME = "b";
public final static String A_VALUE = "a";
public final static byte[] A = Bytes.toBytes(A_VALUE);
public final static String B_VALUE = "b";
public final static byte[] B = Bytes.toBytes(B_VALUE);
public final static String C_VALUE = "c";
public final static byte[] C = Bytes.toBytes(C_VALUE);
public final static String D_VALUE = "d";
public final static byte[] D = Bytes.toBytes(D_VALUE);
public final static String E_VALUE = "e";
public final static byte[] E = Bytes.toBytes(E_VALUE);
public final static String ROW1 = "00A123122312312";
public final static String ROW2 = "00A223122312312";
public final static String ROW3 = "00A323122312312";
public final static String ROW4 = "00A423122312312";
public final static String ROW5 = "00B523122312312";
public final static String ROW6 = "00B623122312312";
public final static String ROW7 = "00B723122312312";
public final static String ROW8 = "00B823122312312";
public final static String ROW9 = "00C923122312312";
public final static String PARENTID1 = "0500x0000000001";
public final static String PARENTID2 = "0500x0000000002";
public final static String PARENTID3 = "0500x0000000003";
public final static String PARENTID4 = "0500x0000000004";
public final static String PARENTID5 = "0500x0000000005";
public final static String PARENTID6 = "0500x0000000006";
public final static String PARENTID7 = "0500x0000000007";
public final static String PARENTID8 = "0500x0000000008";
public final static String PARENTID9 = "0500x0000000009";
public final static List<String> PARENTIDS = Lists.newArrayList(PARENTID1, PARENTID2, PARENTID3, PARENTID4, PARENTID5, PARENTID6, PARENTID7, PARENTID8, PARENTID9);
public final static String ENTITYHISTID1 = "017x00000000001";
public final static String ENTITYHISTID2 = "017x00000000002";
public final static String ENTITYHISTID3 = "017x00000000003";
public final static String ENTITYHISTID4 = "017x00000000004";
public final static String ENTITYHISTID5 = "017x00000000005";
public final static String ENTITYHISTID6 = "017x00000000006";
public final static String ENTITYHISTID7 = "017x00000000007";
public final static String ENTITYHISTID8 = "017x00000000008";
public final static String ENTITYHISTID9 = "017x00000000009";
public final static List<String> ENTITYHISTIDS = Lists.newArrayList(ENTITYHISTID1, ENTITYHISTID2, ENTITYHISTID3, ENTITYHISTID4, ENTITYHISTID5, ENTITYHISTID6, ENTITYHISTID7, ENTITYHISTID8, ENTITYHISTID9);
public static final String LOCALHOST = "localhost";
public static final String PHOENIX_JDBC_URL = JDBC_PROTOCOL + JDBC_PROTOCOL_SEPARATOR + LOCALHOST + JDBC_PROTOCOL_TERMINATOR + PHOENIX_TEST_DRIVER_URL_PARAM;
public static final String PHOENIX_CONNECTIONLESS_JDBC_URL = JDBC_PROTOCOL + JDBC_PROTOCOL_SEPARATOR + CONNECTIONLESS + JDBC_PROTOCOL_TERMINATOR + PHOENIX_TEST_DRIVER_URL_PARAM;
public static final String TEST_SCHEMA_FILE_NAME = "config" + File.separator + "test-schema.xml";
public static final String CED_SCHEMA_FILE_NAME = "config" + File.separator + "schema.xml";
public static final String ENTITY_HISTORY_TABLE_NAME = "ENTITY_HISTORY";
public static final String ENTITY_HISTORY_SALTED_TABLE_NAME = "ENTITY_HISTORY_SALTED";
public static final String ATABLE_NAME = "ATABLE";
public static final String TABLE_WITH_ARRAY = "TABLE_WITH_ARRAY";
public static final String SUM_DOUBLE_NAME = "SumDoubleTest";
public static final String ATABLE_SCHEMA_NAME = "";
public static final String BTABLE_NAME = "BTABLE";
public static final String STABLE_NAME = "STABLE";
public static final String STABLE_PK_NAME = "ID";
public static final String STABLE_SCHEMA_NAME = "";
public static final String GROUPBYTEST_NAME = "GROUPBYTEST";
public static final String CUSTOM_ENTITY_DATA_FULL_NAME = "CORE.CUSTOM_ENTITY_DATA";
public static final String CUSTOM_ENTITY_DATA_NAME = "CUSTOM_ENTITY_DATA";
public static final String CUSTOM_ENTITY_DATA_SCHEMA_NAME = "CORE";
public static final String HBASE_NATIVE = "HBASE_NATIVE";
public static final String HBASE_NATIVE_SCHEMA_NAME = "";
public static final String HBASE_DYNAMIC_COLUMNS = "HBASE_DYNAMIC_COLUMNS";
public static final String HBASE_DYNAMIC_COLUMNS_SCHEMA_NAME = "";
public static final String PRODUCT_METRICS_NAME = "PRODUCT_METRICS";
public static final String PTSDB_NAME = "PTSDB";
public static final String PTSDB2_NAME = "PTSDB2";
public static final String PTSDB3_NAME = "PTSDB3";
public static final String PTSDB_SCHEMA_NAME = "";
public static final String FUNKY_NAME = "FUNKY_NAMES";
public static final String MULTI_CF_NAME = "MULTI_CF";
public static final String MDTEST_NAME = "MDTEST";
public static final String MDTEST_SCHEMA_NAME = "";
public static final String KEYONLY_NAME = "KEYONLY";
public static final String TABLE_WITH_SALTING = "TABLE_WITH_SALTING";
public static final String INDEX_DATA_SCHEMA = "INDEX_TEST";
public static final String INDEX_DATA_TABLE = "INDEX_DATA_TABLE";
public static final String MUTABLE_INDEX_DATA_TABLE = "MUTABLE_INDEX_DATA_TABLE";
public static final String TRANSACTIONAL_DATA_TABLE = "TRANSACTIONAL_DATA_TABLE";
public static final String JOIN_SCHEMA = "Join";
public static final String JOIN_ORDER_TABLE = "OrderTable";
public static final String JOIN_CUSTOMER_TABLE = "CustomerTable";
public static final String JOIN_ITEM_TABLE = "ItemTable";
public static final String JOIN_SUPPLIER_TABLE = "SupplierTable";
public static final String JOIN_COITEM_TABLE = "CoitemTable";
public static final String JOIN_ORDER_TABLE_FULL_NAME = '"' + JOIN_SCHEMA + "\".\"" + JOIN_ORDER_TABLE + '"';
public static final String JOIN_CUSTOMER_TABLE_FULL_NAME = '"' + JOIN_SCHEMA + "\".\"" + JOIN_CUSTOMER_TABLE + '"';
public static final String JOIN_ITEM_TABLE_FULL_NAME = '"' + JOIN_SCHEMA + "\".\"" + JOIN_ITEM_TABLE + '"';
public static final String JOIN_SUPPLIER_TABLE_FULL_NAME = '"' + JOIN_SCHEMA + "\".\"" + JOIN_SUPPLIER_TABLE + '"';
public static final String JOIN_COITEM_TABLE_FULL_NAME = '"' + JOIN_SCHEMA + "\".\"" + JOIN_COITEM_TABLE + '"';
public static final String JOIN_ORDER_TABLE_DISPLAY_NAME = JOIN_SCHEMA + "." + JOIN_ORDER_TABLE;
public static final String JOIN_CUSTOMER_TABLE_DISPLAY_NAME = JOIN_SCHEMA + "." + JOIN_CUSTOMER_TABLE;
public static final String JOIN_ITEM_TABLE_DISPLAY_NAME = JOIN_SCHEMA + "." + JOIN_ITEM_TABLE;
public static final String JOIN_SUPPLIER_TABLE_DISPLAY_NAME = JOIN_SCHEMA + "." + JOIN_SUPPLIER_TABLE;
public static final String JOIN_COITEM_TABLE_DISPLAY_NAME = JOIN_SCHEMA + "." + JOIN_COITEM_TABLE;
public static final String BINARY_NAME = "BinaryTable";
/**
* Read-only properties used by all tests
*/
public static final Properties TEST_PROPERTIES = new Properties() {
@Override
public String put(Object key, Object value) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public Object remove(Object key) {
throw new UnsupportedOperationException();
}
};
public static byte[][] getSplits(String tenantId) {
return new byte[][] {
HConstants.EMPTY_BYTE_ARRAY,
Bytes.toBytes(tenantId + "00A"),
Bytes.toBytes(tenantId + "00B"),
Bytes.toBytes(tenantId + "00C"),
};
}
public static void assertRoundEquals(BigDecimal bd1, BigDecimal bd2) {
bd1 = bd1.round(PDataType.DEFAULT_MATH_CONTEXT);
bd2 = bd2.round(PDataType.DEFAULT_MATH_CONTEXT);
if (bd1.compareTo(bd2) != 0) {
fail("expected:<" + bd1 + "> but was:<" + bd2 + ">");
}
}
public static BigDecimal computeAverage(double sum, long count) {
return BigDecimal.valueOf(sum).divide(BigDecimal.valueOf(count), PDataType.DEFAULT_MATH_CONTEXT);
}
public static BigDecimal computeAverage(long sum, long count) {
return BigDecimal.valueOf(sum).divide(BigDecimal.valueOf(count), PDataType.DEFAULT_MATH_CONTEXT);
}
public static Expression constantComparison(CompareOp op, PColumn c, Object o) {
return new ComparisonExpression(Arrays.<Expression>asList(new KeyValueColumnExpression(c), LiteralExpression.newConstant(o)), op);
}
public static Expression kvColumn(PColumn c) {
return new KeyValueColumnExpression(c);
}
public static Expression pkColumn(PColumn c, List<PColumn> columns) {
return new RowKeyColumnExpression(c, new RowKeyValueAccessor(columns, columns.indexOf(c)));
}
public static Expression constantComparison(CompareOp op, Expression e, Object o) {
return new ComparisonExpression(Arrays.asList(e, LiteralExpression.newConstant(o)), op);
}
private static boolean useByteBasedRegex(StatementContext context) {
return context
.getConnection()
.getQueryServices()
.getProps()
.getBoolean(QueryServices.USE_BYTE_BASED_REGEX_ATTRIB,
QueryServicesOptions.DEFAULT_USE_BYTE_BASED_REGEX);
}
public static Expression like(Expression e, Object o, StatementContext context) {
return useByteBasedRegex(context)?
ByteBasedLikeExpression.create(Arrays.asList(e, LiteralExpression.newConstant(o)), LikeType.CASE_SENSITIVE):
StringBasedLikeExpression.create(Arrays.asList(e, LiteralExpression.newConstant(o)), LikeType.CASE_SENSITIVE);
}
public static Expression ilike(Expression e, Object o, StatementContext context) {
return useByteBasedRegex(context)?
ByteBasedLikeExpression.create(Arrays.asList(e, LiteralExpression.newConstant(o)), LikeType.CASE_INSENSITIVE):
StringBasedLikeExpression.create(Arrays.asList(e, LiteralExpression.newConstant(o)), LikeType.CASE_INSENSITIVE);
}
public static Expression substr(Expression e, Object offset, Object length) {
return new SubstrFunction(Arrays.asList(e, LiteralExpression.newConstant(offset), LiteralExpression.newConstant(length)));
}
public static Expression columnComparison(CompareOp op, Expression c1, Expression c2) {
return new ComparisonExpression(Arrays.<Expression>asList(c1, c2), op);
}
public static SingleKeyValueComparisonFilter singleKVFilter(Expression e) {
return new SingleCQKeyValueComparisonFilter(e);
}
public static RowKeyComparisonFilter rowKeyFilter(Expression e) {
return new RowKeyComparisonFilter(e, QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES);
}
public static MultiKeyValueComparisonFilter multiKVFilter(Expression e) {
return new MultiCQKeyValueComparisonFilter(e, false, ByteUtil.EMPTY_BYTE_ARRAY);
}
public static MultiEncodedCQKeyValueComparisonFilter multiEncodedKVFilter(Expression e, QualifierEncodingScheme encodingScheme) {
return new MultiEncodedCQKeyValueComparisonFilter(e, encodingScheme, false, null);
}
public static Expression and(Expression... expressions) {
return new AndExpression(Arrays.asList(expressions));
}
public static Expression not(Expression expression) {
return new NotExpression(expression);
}
public static Expression or(Expression... expressions) {
return new OrExpression(Arrays.asList(expressions));
}
public static Expression in(Expression... expressions) throws SQLException {
return InListExpression.create(Arrays.asList(expressions), false, new ImmutableBytesWritable(), true);
}
public static Expression in(Expression e, Object... literals) throws SQLException {
PDataType childType = e.getDataType();
List<Expression> expressions = new ArrayList<Expression>(literals.length + 1);
expressions.add(e);
for (Object o : literals) {
expressions.add(LiteralExpression.newConstant(o, childType));
}
return InListExpression.create(expressions, false, new ImmutableBytesWritable(), true);
}
public static void assertDegenerate(StatementContext context) {
Scan scan = context.getScan();
assertDegenerate(scan);
}
public static void assertDegenerate(Scan scan) {
assertNull(scan.getFilter());
assertArrayEquals(KeyRange.EMPTY_RANGE.getLowerRange(), scan.getStartRow());
assertArrayEquals(KeyRange.EMPTY_RANGE.getLowerRange(), scan.getStopRow());
assertEquals(null,scan.getFilter());
}
public static void assertNotDegenerate(Scan scan) {
assertFalse(
Bytes.compareTo(KeyRange.EMPTY_RANGE.getLowerRange(), scan.getStartRow()) == 0 &&
Bytes.compareTo(KeyRange.EMPTY_RANGE.getLowerRange(), scan.getStopRow()) == 0);
}
public static void assertEmptyScanKey(Scan scan) {
assertNull(scan.getFilter());
assertArrayEquals(ByteUtil.EMPTY_BYTE_ARRAY, scan.getStartRow());
assertArrayEquals(ByteUtil.EMPTY_BYTE_ARRAY, scan.getStopRow());
assertEquals(null,scan.getFilter());
}
/**
* Does a deep comparison of two Results, down to the byte arrays.
* @param res1 first result to compare
* @param res2 second result to compare
* @throws Exception Every difference is throwing an exception
*/
public static void compareTuples(Tuple res1, Tuple res2)
throws Exception {
if (res2 == null) {
throw new Exception("There wasn't enough rows, we stopped at "
+ res1);
}
if (res1.size() != res2.size()) {
throw new Exception("This row doesn't have the same number of KVs: "
+ res1.toString() + " compared to " + res2.toString());
}
for (int i = 0; i < res1.size(); i++) {
Cell ourKV = res1.getValue(i);
Cell replicatedKV = res2.getValue(i);
if (!ourKV.equals(replicatedKV)) {
throw new Exception("This result was different: "
+ res1.toString() + " compared to " + res2.toString());
}
}
}
public static void clearMetaDataCache(Connection conn) throws Throwable {
PhoenixConnection pconn = conn.unwrap(PhoenixConnection.class);
HTableInterface htable = pconn.getQueryServices().getTable(PhoenixDatabaseMetaData.SYSTEM_CATALOG_NAME_BYTES);
htable.coprocessorService(MetaDataService.class, HConstants.EMPTY_START_ROW,
HConstants.EMPTY_END_ROW, new Batch.Call<MetaDataService, ClearCacheResponse>() {
@Override
public ClearCacheResponse call(MetaDataService instance) throws IOException {
ServerRpcController controller = new ServerRpcController();
BlockingRpcCallback<ClearCacheResponse> rpcCallback =
new BlockingRpcCallback<ClearCacheResponse>();
ClearCacheRequest.Builder builder = ClearCacheRequest.newBuilder();
instance.clearCache(controller, builder.build(), rpcCallback);
if(controller.getFailedOn() != null) {
throw controller.getFailedOn();
}
return rpcCallback.get();
}
});
}
public static void closeStatement(Statement stmt) {
try {
stmt.close();
} catch (Throwable ignore) {}
}
public static void closeConnection(Connection conn) {
try {
conn.close();
} catch (Throwable ignore) {}
}
public static void closeStmtAndConn(Statement stmt, Connection conn) {
closeStatement(stmt);
closeConnection(conn);
}
public static void bindParams(PhoenixPreparedStatement stmt, List<Object> binds) throws SQLException {
for (int i = 0; i < binds.size(); i++) {
stmt.setObject(i+1, binds.get(i));
}
}
/**
* @param conn
* connection to be used
* @param sortOrder
* sort order of column contain input values
* @param id
* id of the row being inserted
* @param input
* input to be inserted
*/
public static void upsertRow(Connection conn, String tableName, String sortOrder, int id, Object input) throws SQLException {
String dml = String.format("UPSERT INTO " + tableName + "_%s VALUES(?,?)", sortOrder);
PreparedStatement stmt = conn.prepareStatement(dml);
stmt.setInt(1, id);
if (input instanceof String)
stmt.setString(2, (String) input);
else if (input instanceof Integer)
stmt.setInt(2, (Integer) input);
else if (input instanceof Double)
stmt.setDouble(2, (Double) input);
else if (input instanceof Float)
stmt.setFloat(2, (Float) input);
else if (input instanceof Boolean)
stmt.setBoolean(2, (Boolean) input);
else if (input instanceof Long)
stmt.setLong(2, (Long) input);
else
throw new UnsupportedOperationException("" + input.getClass() + " is not supported by upsertRow");
stmt.execute();
conn.commit();
}
public static void createGroupByTestTable(Connection conn, String tableName) throws SQLException {
conn.createStatement().execute("create table " + tableName +
" (id varchar not null primary key,\n" +
" uri varchar, appcpu integer)");
}
private static void createTable(Connection conn, String inputSqlType, String tableName, String sortOrder) throws SQLException {
String dmlFormat =
"CREATE TABLE " + tableName + "_%s (id INTEGER NOT NULL, pk %s NOT NULL, " + "kv %s "
+ "CONSTRAINT PK_CONSTRAINT PRIMARY KEY (id, pk %s))";
String ddl = String.format(dmlFormat,sortOrder, inputSqlType, inputSqlType, sortOrder);
conn.createStatement().execute(ddl);
conn.commit();
}
/**
* Creates a table to be used for testing. It contains one id column, one varchar column to be used as input, and
* one column which will contain null values
*
* @param conn
* connection to be used
* @param inputSqlType
* sql type of input
* @param inputList
* list of values to be inserted into the pk column
*/
public static String initTables(Connection conn, String inputSqlType, List<Object> inputList) throws Exception {
String tableName = generateUniqueName();
createTable(conn, inputSqlType, tableName, "ASC");
createTable(conn, inputSqlType, tableName, "DESC");
for (int i = 0; i < inputList.size(); ++i) {
upsertRow(conn, tableName, "ASC", i, inputList.get(i));
upsertRow(conn, tableName, "DESC", i, inputList.get(i));
}
return tableName;
}
public static List<KeyRange> getAllSplits(Connection conn, String tableName) throws SQLException {
return getSplits(conn, tableName, null, null, null, null, null);
}
public static List<KeyRange> getAllSplits(Connection conn, String tableName, String where, String selectClause) throws SQLException {
return getSplits(conn, tableName, null, null, null, where, selectClause);
}
public static List<KeyRange> getSplits(Connection conn, String tableName, String pkCol, byte[] lowerRange, byte[] upperRange, String whereClauseSuffix, String selectClause) throws SQLException {
String whereClauseStart =
(lowerRange == null && upperRange == null ? "" :
" WHERE " + ((lowerRange != null ? (pkCol + " >= ? " + (upperRange != null ? " AND " : "")) : "")
+ (upperRange != null ? (pkCol + " < ?") : "" )));
String whereClause = whereClauseSuffix == null ? whereClauseStart : whereClauseStart.length() == 0 ? (" WHERE " + whereClauseSuffix) : (" AND " + whereClauseSuffix);
String query = "SELECT /*+ NO_INDEX */ "+selectClause+" FROM " + tableName + whereClause;
PhoenixPreparedStatement pstmt = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class);
if (lowerRange != null) {
pstmt.setBytes(1, lowerRange);
}
if (upperRange != null) {
pstmt.setBytes(lowerRange != null ? 2 : 1, upperRange);
}
pstmt.execute();
List<KeyRange> keyRanges = pstmt.getQueryPlan().getSplits();
return keyRanges;
}
public static Collection<GuidePostsInfo> getGuidePostsList(Connection conn, String tableName) throws SQLException {
return getGuidePostsList(conn, tableName, null, null, null, null);
}
public static Collection<GuidePostsInfo> getGuidePostsList(Connection conn, String tableName, String where)
throws SQLException {
return getGuidePostsList(conn, tableName, null, null, null, where);
}
public static Collection<GuidePostsInfo> getGuidePostsList(Connection conn, String tableName, String pkCol,
byte[] lowerRange, byte[] upperRange, String whereClauseSuffix) throws SQLException {
String whereClauseStart = (lowerRange == null && upperRange == null ? ""
: " WHERE "
+ ((lowerRange != null ? (pkCol + " >= ? " + (upperRange != null ? " AND " : "")) : "") + (upperRange != null ? (pkCol + " < ?")
: "")));
String whereClause = whereClauseSuffix == null ? whereClauseStart
: whereClauseStart.length() == 0 ? (" WHERE " + whereClauseSuffix) : (" AND " + whereClauseSuffix);
String query = "SELECT /*+ NO_INDEX */ COUNT(*) FROM " + tableName + whereClause;
PhoenixPreparedStatement pstmt = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class);
if (lowerRange != null) {
pstmt.setBytes(1, lowerRange);
}
if (upperRange != null) {
pstmt.setBytes(lowerRange != null ? 2 : 1, upperRange);
}
pstmt.execute();
TableRef tableRef = pstmt.getQueryPlan().getTableRef();
PhoenixConnection pconn = conn.unwrap(PhoenixConnection.class);
PTable table = tableRef.getTable();
GuidePostsInfo info = pconn.getQueryServices().getTableStats(new GuidePostsKey(table.getName().getBytes(), SchemaUtil.getEmptyColumnFamily(table)));
return Collections.singletonList(info);
}
public static void analyzeTable(Connection conn, String tableName) throws IOException, SQLException {
analyzeTable(conn, tableName, false);
}
public static void analyzeTable(Connection conn, String tableName, boolean transactional) throws IOException, SQLException {
String query = "UPDATE STATISTICS " + tableName;
conn.createStatement().execute(query);
// if the table is transactional burn a txn in order to make sure the next txn read pointer is close to wall clock time
conn.commit();
}
public static void analyzeTableIndex(Connection conn, String tableName) throws IOException, SQLException {
String query = "UPDATE STATISTICS " + tableName+ " INDEX";
conn.createStatement().execute(query);
}
public static void analyzeTableColumns(Connection conn, String tableName) throws IOException, SQLException {
String query = "UPDATE STATISTICS " + tableName + " COLUMNS";
conn.createStatement().execute(query);
}
public static void analyzeTable(String url, long ts, String tableName) throws IOException, SQLException {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts));
analyzeTable(url, props, tableName);
}
public static void analyzeTable(String url, Properties props, String tableName) throws IOException, SQLException {
Connection conn = DriverManager.getConnection(url, props);
analyzeTable(conn, tableName);
conn.close();
}
public static void setRowKeyColumns(PreparedStatement stmt, int i) throws SQLException {
// insert row
stmt.setString(1, "varchar" + String.valueOf(i));
stmt.setString(2, "char" + String.valueOf(i));
stmt.setInt(3, i);
stmt.setLong(4, i);
stmt.setBigDecimal(5, new BigDecimal(i*0.5d));
Date date = new Date(DateUtil.parseDate("2015-01-01 00:00:00").getTime() + (i - 1) * MILLIS_IN_DAY);
stmt.setDate(6, date);
}
public static void validateRowKeyColumns(ResultSet rs, int i) throws SQLException {
assertTrue(rs.next());
assertEquals(rs.getString(1), "varchar" + String.valueOf(i));
assertEquals(rs.getString(2), "char" + String.valueOf(i));
assertEquals(rs.getInt(3), i);
assertEquals(rs.getInt(4), i);
assertEquals(rs.getBigDecimal(5), new BigDecimal(i*0.5d));
Date date = new Date(DateUtil.parseDate("2015-01-01 00:00:00").getTime() + (i - 1) * MILLIS_IN_DAY);
assertEquals(rs.getDate(6), date);
}
public static String getTableName(Boolean mutable, Boolean transactional) {
StringBuilder tableNameBuilder = new StringBuilder(DEFAULT_DATA_TABLE_NAME);
if (mutable!=null)
tableNameBuilder.append(mutable ? "_MUTABLE" : "_IMMUTABLE");
if (transactional!=null)
tableNameBuilder.append(transactional ? "_TXN" : "_NON_TXN");
return tableNameBuilder.toString();
}
public static ClientAggregators getSingleSumAggregator(String url, Properties props) throws SQLException {
try (PhoenixConnection pconn = DriverManager.getConnection(url, props).unwrap(PhoenixConnection.class)) {
PhoenixStatement statement = new PhoenixStatement(pconn);
StatementContext context = new StatementContext(statement, null, new Scan(), new SequenceManager(statement));
AggregationManager aggregationManager = context.getAggregationManager();
SumAggregateFunction func = new SumAggregateFunction(Arrays.<Expression>asList(new KeyValueColumnExpression(new PLongColumn() {
@Override
public PName getName() {
return SINGLE_COLUMN_NAME;
}
@Override
public PName getFamilyName() {
return SINGLE_COLUMN_FAMILY_NAME;
}
@Override
public int getPosition() {
return 0;
}
@Override
public SortOrder getSortOrder() {
return SortOrder.getDefault();
}
@Override
public Integer getArraySize() {
return 0;
}
@Override
public byte[] getViewConstant() {
return null;
}
@Override
public boolean isViewReferenced() {
return false;
}
@Override
public String getExpressionStr() {
return null;
}
@Override
public boolean isRowTimestamp() {
return false;
}
@Override
public boolean isDynamic() {
return false;
}
@Override
public byte[] getColumnQualifierBytes() {
return SINGLE_COLUMN_NAME.getBytes();
}
})), null);
aggregationManager.setAggregators(new ClientAggregators(Collections.<SingleAggregateFunction>singletonList(func), 1));
ClientAggregators aggregators = aggregationManager.getAggregators();
return aggregators;
}
}
public static void createMultiCFTestTable(Connection conn, String tableName, String options) throws SQLException {
String ddl = "create table if not exists " + tableName + "(" +
" varchar_pk VARCHAR NOT NULL, " +
" char_pk CHAR(5) NOT NULL, " +
" int_pk INTEGER NOT NULL, "+
" long_pk BIGINT NOT NULL, " +
" decimal_pk DECIMAL(31, 10) NOT NULL, " +
" a.varchar_col1 VARCHAR, " +
" a.char_col1 CHAR(5), " +
" a.int_col1 INTEGER, " +
" a.long_col1 BIGINT, " +
" a.decimal_col1 DECIMAL(31, 10), " +
" b.varchar_col2 VARCHAR, " +
" b.char_col2 CHAR(5), " +
" b.int_col2 INTEGER, " +
" b.long_col2 BIGINT, " +
" b.decimal_col2 DECIMAL, " +
" b.date_col DATE " +
" CONSTRAINT pk PRIMARY KEY (varchar_pk, char_pk, int_pk, long_pk DESC, decimal_pk)) "
+ (options!=null? options : "");
conn.createStatement().execute(ddl);
}
/**
* Runs a major compaction, and then waits until the compaction is complete before returning.
*
* @param tableName name of the table to be compacted
*/
public static void doMajorCompaction(Connection conn, String tableName) throws Exception {
tableName = SchemaUtil.normalizeIdentifier(tableName);
// We simply write a marker row, request a major compaction, and then wait until the marker
// row is gone
PhoenixConnection pconn = conn.unwrap(PhoenixConnection.class);
PTable table = pconn.getTable(new PTableKey(pconn.getTenantId(), tableName));
ConnectionQueryServices services = conn.unwrap(PhoenixConnection.class).getQueryServices();
MutationState mutationState = pconn.getMutationState();
if (table.isTransactional()) {
mutationState.startTransaction();
}
try (HTableInterface htable = mutationState.getHTable(table)) {
byte[] markerRowKey = Bytes.toBytes("TO_DELETE");
Put put = new Put(markerRowKey);
put.add(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES, QueryConstants.EMPTY_COLUMN_VALUE_BYTES, QueryConstants.EMPTY_COLUMN_VALUE_BYTES);
htable.put(put);
Delete delete = new Delete(markerRowKey);
delete.deleteColumn(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES, QueryConstants.EMPTY_COLUMN_VALUE_BYTES);
htable.delete(delete);
htable.close();
if (table.isTransactional()) {
mutationState.commit();
}
HBaseAdmin hbaseAdmin = services.getAdmin();
hbaseAdmin.flush(tableName);
hbaseAdmin.majorCompact(tableName);
hbaseAdmin.close();
boolean compactionDone = false;
while (!compactionDone) {
Thread.sleep(6000L);
Scan scan = new Scan();
scan.setStartRow(markerRowKey);
scan.setStopRow(Bytes.add(markerRowKey, new byte[] { 0 }));
scan.setRaw(true);
try (HTableInterface htableForRawScan = services.getTable(Bytes.toBytes(tableName))) {
ResultScanner scanner = htableForRawScan.getScanner(scan);
List<Result> results = Lists.newArrayList(scanner);
LOG.info("Results: " + results);
compactionDone = results.isEmpty();
scanner.close();
}
LOG.info("Compaction done: " + compactionDone);
// need to run compaction after the next txn snapshot has been written so that compaction can remove deleted rows
if (!compactionDone && table.isTransactional()) {
hbaseAdmin = services.getAdmin();
hbaseAdmin.flush(tableName);
hbaseAdmin.majorCompact(tableName);
hbaseAdmin.close();
}
}
}
}
public static void createTransactionalTable(Connection conn, String tableName) throws SQLException {
conn.createStatement().execute("create table " + tableName + TestUtil.TEST_TABLE_SCHEMA + "TRANSACTIONAL=true");
}
public static void dumpTable(HTableInterface table) throws IOException {
System.out.println("************ dumping " + table + " **************");
Scan s = new Scan();
s.setRaw(true);;
s.setMaxVersions();
try (ResultScanner scanner = table.getScanner(s)) {
Result result = null;
while ((result = scanner.next()) != null) {
CellScanner cellScanner = result.cellScanner();
Cell current = null;
while (cellScanner.advance()) {
current = cellScanner.current();
System.out.println(current);
}
}
}
System.out.println("-----------------------------------------------");
}
public static void waitForIndexRebuild(Connection conn, String fullIndexName, PIndexState expectedIndexState) throws InterruptedException, SQLException {
boolean isActive = false;
String schema = SchemaUtil.getSchemaNameFromFullName(fullIndexName);
String index = SchemaUtil.getTableNameFromFullName(fullIndexName);
int maxTries = 12, nTries = 0;
do {
Thread.sleep(5 * 1000); // sleep 5 secs
String query = "SELECT CAST(" + PhoenixDatabaseMetaData.INDEX_DISABLE_TIMESTAMP + " AS BIGINT) FROM " +
PhoenixDatabaseMetaData.SYSTEM_CATALOG_NAME + " WHERE (" + PhoenixDatabaseMetaData.TABLE_SCHEM + "," + PhoenixDatabaseMetaData.TABLE_NAME
+ ") = (" + "'" + schema + "','" + index + "') "
+ "AND " + PhoenixDatabaseMetaData.COLUMN_FAMILY + " IS NULL AND " + PhoenixDatabaseMetaData.COLUMN_NAME + " IS NULL"
+ " AND " + PhoenixDatabaseMetaData.INDEX_STATE + " = '" + expectedIndexState.getSerializedValue() + "'";
ResultSet rs = conn.createStatement().executeQuery(query);
if (rs.next() && expectedIndexState == PIndexState.ACTIVE) {
if (rs.getLong(1) == 0 && !rs.wasNull()) {
isActive = true;
break;
}
}
} while (++nTries < maxTries);
if (expectedIndexState == PIndexState.ACTIVE) {
assertTrue(isActive);
}
}
public static long scrutinizeIndex(Connection conn, String fullTableName, String fullIndexName) throws SQLException {
PhoenixConnection pconn = conn.unwrap(PhoenixConnection.class);
PTable ptable = pconn.getTable(new PTableKey(pconn.getTenantId(), fullTableName));
PTable pindex = pconn.getTable(new PTableKey(pconn.getTenantId(), fullIndexName));
StringBuilder indexQueryBuf = new StringBuilder("SELECT ");
for (PColumn dcol : ptable.getPKColumns()) {
indexQueryBuf.append("CAST(\"" + IndexUtil.getIndexColumnName(dcol) + "\" AS " + dcol.getDataType().getSqlTypeName() + ")");
indexQueryBuf.append(",");
}
for (PColumn icol : pindex.getColumns()) {
PColumn dcol = IndexUtil.getDataColumn(ptable, icol.getName().getString());
if (SchemaUtil.isPKColumn(icol) && !SchemaUtil.isPKColumn(dcol)) {
indexQueryBuf.append("CAST (\"" + icol.getName().getString() + "\" AS " + dcol.getDataType().getSqlTypeName() + ")");
indexQueryBuf.append(",");
}
}
for (PColumn icol : pindex.getColumns()) {
if (!SchemaUtil.isPKColumn(icol)) {
PColumn dcol = IndexUtil.getDataColumn(ptable, icol.getName().getString());
indexQueryBuf.append("CAST (\"" + icol.getName().getString() + "\" AS " + dcol.getDataType().getSqlTypeName() + ")");
indexQueryBuf.append(",");
}
}
indexQueryBuf.setLength(indexQueryBuf.length()-1);
indexQueryBuf.append("\nFROM " + fullIndexName);
StringBuilder tableQueryBuf = new StringBuilder("SELECT ");
for (PColumn dcol : ptable.getPKColumns()) {
tableQueryBuf.append("\"" + dcol.getName().getString() + "\"");
tableQueryBuf.append(",");
}
for (PColumn icol : pindex.getColumns()) {
PColumn dcol = IndexUtil.getDataColumn(ptable, icol.getName().getString());
if (SchemaUtil.isPKColumn(icol) && !SchemaUtil.isPKColumn(dcol)) {
if (dcol.getFamilyName() != null) {
tableQueryBuf.append("\"" + dcol.getFamilyName().getString() + "\"");
tableQueryBuf.append(".");
}
tableQueryBuf.append("\"" + dcol.getName().getString() + "\"");
tableQueryBuf.append(",");
}
}
for (PColumn icol : pindex.getColumns()) {
if (!SchemaUtil.isPKColumn(icol)) {
PColumn dcol = IndexUtil.getDataColumn(ptable, icol.getName().getString());
if (dcol.getFamilyName() != null) {
tableQueryBuf.append("\"" + dcol.getFamilyName().getString() + "\"");
tableQueryBuf.append(".");
}
tableQueryBuf.append("\"" + dcol.getName().getString() + "\"");
tableQueryBuf.append(",");
}
}
tableQueryBuf.setLength(tableQueryBuf.length()-1);
tableQueryBuf.append("\nFROM " + fullTableName + "\nWHERE (");
for (PColumn dcol : ptable.getPKColumns()) {
tableQueryBuf.append("\"" + dcol.getName().getString() + "\"");
tableQueryBuf.append(",");
}
tableQueryBuf.setLength(tableQueryBuf.length()-1);
tableQueryBuf.append(") = ((");
for (int i = 0; i < ptable.getPKColumns().size(); i++) {
tableQueryBuf.append("?");
tableQueryBuf.append(",");
}
tableQueryBuf.setLength(tableQueryBuf.length()-1);
tableQueryBuf.append("))");
String tableQuery = tableQueryBuf.toString();
PreparedStatement istmt = conn.prepareStatement(tableQuery);
String indexQuery = indexQueryBuf.toString();
ResultSet irs = conn.createStatement().executeQuery(indexQuery);
ResultSetMetaData irsmd = irs.getMetaData();
long icount = 0;
while (irs.next()) {
icount++;
StringBuilder pkBuf = new StringBuilder("(");
for (int i = 0; i < ptable.getPKColumns().size(); i++) {
PColumn dcol = ptable.getPKColumns().get(i);
Object pkVal = irs.getObject(i+1);
PDataType pkType = PDataType.fromTypeId(irsmd.getColumnType(i + 1));
istmt.setObject(i+1, pkVal, dcol.getDataType().getSqlType());
pkBuf.append(pkType.toStringLiteral(pkVal));
pkBuf.append(",");
}
pkBuf.setLength(pkBuf.length()-1);
pkBuf.append(")");
ResultSet drs = istmt.executeQuery();
ResultSetMetaData drsmd = drs.getMetaData();
assertTrue("Expected to find PK in data table: " + pkBuf, drs.next());
for (int i = 0; i < irsmd.getColumnCount(); i++) {
Object iVal = irs.getObject(i + 1);
PDataType iType = PDataType.fromTypeId(irsmd.getColumnType(i + 1));
Object dVal = drs.getObject(i + 1);
PDataType dType = PDataType.fromTypeId(drsmd.getColumnType(i + 1));
assertTrue("Expected equality for " + drsmd.getColumnName(i + 1) + ", but " + iType.toStringLiteral(iVal) + "!=" + dType.toStringLiteral(dVal), Objects.equal(iVal, dVal));
}
}
long dcount = getRowCount(conn, fullTableName);
assertEquals("Expected data table row count to match", icount, dcount);
return icount;
}
private static long getRowCount(Connection conn, String tableName) throws SQLException {
ResultSet rs = conn.createStatement().executeQuery("SELECT /*+ NO_INDEX */ count(*) FROM " + tableName);
assertTrue(rs.next());
return rs.getLong(1);
}
}