src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
HConfiguration extends HBaseConfiguration { public static SConfiguration getConfiguration() { return new HConfiguration().init(); } private HConfiguration(); static SConfiguration getConfiguration(); static SConfiguration reloadConfiguration(Configuration resetConfiguration); static Configuration unwrapDelegate(); @Override void setDefaults(ConfigurationBuilder builder, ConfigurationSource configurationSource); static final Boolean DEFAULT_IN_MEMORY; static final Boolean DEFAULT_BLOCKCACHE; static final int DEFAULT_TTL; static final String DEFAULT_BLOOMFILTER; }
@Test public void testPrefixMatch() throws Exception { SConfiguration config = HConfiguration.getConfiguration(); Map<String, String> auths = config.prefixMatch("splice.authentication.*"); String key = "splice.authentication"; String value = auths.get(key); assertNotNull(value); assertEquals("NON-NATIVE", value); key = "splice.authentication.native.algorithm"; value = auths.get(key); assertNotNull(value); assertEquals("SHA-512", value); key = "splice.authentication.native.create.credentials.database"; value = auths.get(key); assertNotNull(value); assertEquals("false", value); }
SICompactionStateMutate { public long mutate(List<Cell> rawList, List<TxnView> txns, List<Cell> results) throws IOException { handleSanityChecks(results, rawList, txns); long totalSize = 0; try { Iterator<TxnView> it = txns.iterator(); for (Cell cell : rawList) { totalSize += KeyValueUtil.length(cell); TxnView txn = it.next(); mutate(cell, txn); } Stream<Cell> stream = dataToReturn.stream(); if (shouldPurgeDeletes()) stream = stream.filter(not(this::purgeableDeletedRow)); if (shouldPurgeUpdates()) stream = stream.filter(not(this::purgeableOldUpdate)); stream.forEachOrdered(results::add); final boolean debugSortCheck = !LOG.isDebugEnabled() || isSorted(results); if (!debugSortCheck) setBypassPurgeWithWarning("CompactionStateMutate: results not sorted."); assert debugSortCheck : "CompactionStateMutate: results not sorted"; return totalSize; } catch (AssertionError e) { LOG.error(e); LOG.error(rawList.toString()); LOG.error(txns.toString()); throw e; } } SICompactionStateMutate(PurgeConfig purgeConfig); long mutate(List<Cell> rawList, List<TxnView> txns, List<Cell> results); static Predicate<R> not(Predicate<R> predicate); }
@Test public void mutateEmpty() throws IOException { cutNoPurge.mutate(inputCells, transactions, outputCells); assertThat(outputCells, is(empty())); } @Test public void mutateSimpleOneActiveTransaction() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockValueCell(200), SITestUtils.getMockValueCell(100))); transactions.addAll(Arrays.asList( TxnTestUtils.getMockActiveTxn(200), TxnTestUtils.getMockActiveTxn(100) )); cutNoPurge.mutate(inputCells, transactions, outputCells); assertThat(outputCells, equalTo(inputCells)); } @Test public void mutateSimpleOneCommittedTransaction() throws IOException { inputCells.addAll(Collections.singletonList( SITestUtils.getMockValueCell(100))); transactions.addAll(Collections.singletonList( TxnTestUtils.getMockCommittedTxn(100, 200))); cutNoPurge.mutate(inputCells, transactions, outputCells); assertThat(outputCells, hasSize(inputCells.size() + 1)); List<Cell> newCells = getNewlyAddedCells(inputCells, outputCells); assertThat(newCells, hasSize(1)); Cell commit = newCells.get(0); assertThat(CellUtils.getKeyValueType(commit), equalTo(CellType.COMMIT_TIMESTAMP)); assertThat(commit.getTimestamp(), equalTo(100L)); assertThat(Bytes.toLong(commit.getValueArray(), commit.getValueOffset(), commit.getValueLength()), equalTo(200L)); } @Test public void mutateRolledBackTransaction() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockValueCell(300), SITestUtils.getMockValueCell(200), SITestUtils.getMockValueCell(100) )); transactions.addAll(Arrays.asList( TxnTestUtils.getMockRolledBackTxn(300), TxnTestUtils.getMockRolledBackTxn(200), TxnTestUtils.getMockRolledBackTxn(100) )); cutNoPurge.mutate(inputCells, transactions, outputCells); assertThat(outputCells, is(empty())); } @Test public void mutateMixOfTransactions() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockValueCell(300), SITestUtils.getMockValueCell(200), SITestUtils.getMockValueCell(100) )); transactions.addAll(Arrays.asList( TxnTestUtils.getMockCommittedTxn(300, 310), TxnTestUtils.getMockActiveTxn(200), TxnTestUtils.getMockRolledBackTxn(100) )); cutNoPurge.mutate(inputCells, transactions, outputCells); assertThat(outputCells, hasSize(inputCells.size())); List<Cell> newCells = getNewlyAddedCells(inputCells, outputCells); List<Cell> removedCells = getRemovedCells(inputCells, outputCells); assertThat(newCells, hasSize(1)); assertThat(removedCells, hasSize(1)); assertThat(removedCells.get(0).getTimestamp(), equalTo(100L)); assertThat(newCells.get(0).getTimestamp(), equalTo(300L)); } @Test public void mutateNullTransaction() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockValueCell(100), SITestUtils.getMockValueCell(100) )); transactions.addAll(Arrays.asList( null, null )); cutNoPurge.mutate(inputCells, transactions, outputCells); assertThat(outputCells, equalTo(outputCells)); } @Test public void mutateTombstones() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockTombstoneCell(200), SITestUtils.getMockValueCell(100) )); transactions.addAll(Arrays.asList( TxnTestUtils.getMockCommittedTxn(100, 250), TxnTestUtils.getMockCommittedTxn(100, 250) )); cutNoPurge.mutate(inputCells, transactions, outputCells); assertThat(getRemovedCells(inputCells, outputCells), is(empty())); } @Test public void mutatePurgeTombstones() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(200, 210), SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockTombstoneCell(200), SITestUtils.getMockValueCell(100) )); transactions.addAll(Arrays.asList( null, null, TxnTestUtils.getMockCommittedTxn(200, 210), TxnTestUtils.getMockCommittedTxn(100, 110) )); cutForcePurge.mutate(inputCells, transactions, outputCells); assertThat(outputCells, is(empty())); } @Test public void mutateDoNotPurgeBecauseTombstoneNotCommitted() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockTombstoneCell(200), SITestUtils.getMockValueCell(100) )); transactions.addAll(Arrays.asList( null, TxnTestUtils.getMockActiveTxn(200), TxnTestUtils.getMockCommittedTxn(100, 110) )); cutForcePurge.mutate(inputCells, transactions, outputCells); assertThat(outputCells, equalTo(inputCells)); } @Test public void mutateDoNotPurgeBecauseTombstoneRolledBack() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockTombstoneCell(200), SITestUtils.getMockValueCell(100) )); transactions.addAll(Arrays.asList( null, TxnTestUtils.getMockRolledBackTxn(200), TxnTestUtils.getMockCommittedTxn(100, 110) )); cutForcePurge.mutate(inputCells, transactions, outputCells); assertThat(outputCells, hasSize(2)); assertThat(outputCells, contains( SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockValueCell(100))); } @Test public void mutatePartialPurge() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(300, 310), SITestUtils.getMockCommitCell(200, 210), SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockAntiTombstoneCell(300), SITestUtils.getMockTombstoneCell(200), SITestUtils.getMockValueCell(300), SITestUtils.getMockValueCell(100) )); TxnView transaction1 = TxnTestUtils.getMockCommittedTxn(100, 110); TxnView transaction2 = TxnTestUtils.getMockCommittedTxn(200, 210); TxnView transaction3 = TxnTestUtils.getMockCommittedTxn(300, 310); transactions.addAll(Arrays.asList( null, null, null, transaction3, transaction2, transaction3, transaction1 )); cutForcePurge.mutate(inputCells, transactions, outputCells); assertThat(outputCells, hasSize(3)); assertThat(outputCells, contains( SITestUtils.getMockCommitCell(300, 310), SITestUtils.getMockAntiTombstoneCell(300), SITestUtils.getMockValueCell(300))); } @Test public void mutatePurgeKeepTombstones() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(200, 210), SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockTombstoneCell(200), SITestUtils.getMockValueCell(100) )); transactions.addAll(Arrays.asList( null, null, TxnTestUtils.getMockCommittedTxn(200, 210), TxnTestUtils.getMockCommittedTxn(100, 110) )); cutPurgeDuringFlush.mutate(inputCells, transactions, outputCells); assertThat(outputCells, hasSize(2)); assertThat(getRemovedCells(inputCells, outputCells), containsInAnyOrder( SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockValueCell(100) )); } @Test public void mutateNonForcePurge() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(200, 210), SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockTombstoneCell(200), SITestUtils.getMockValueCell(100) )); transactions.addAll(Arrays.asList( null, null, TxnTestUtils.getMockCommittedTxn(200, 210), TxnTestUtils.getMockCommittedTxn(100, 110) )); cutPurgeDuringMajorCompaction.mutate(inputCells, transactions, outputCells); assertThat(outputCells, is(empty())); } @Test public void mutatePurgeConsideringWatermark() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(1100, 1110), SITestUtils.getMockCommitCell(300, 310), SITestUtils.getMockCommitCell(200, 210), SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockTombstoneCell(1100), SITestUtils.getMockAntiTombstoneCell(300), SITestUtils.getMockTombstoneCell(200), SITestUtils.getMockValueCell(300), SITestUtils.getMockValueCell(100) )); TxnView transaction1 = TxnTestUtils.getMockCommittedTxn(100, 110); TxnView transaction2 = TxnTestUtils.getMockCommittedTxn(200, 210); TxnView transaction3 = TxnTestUtils.getMockCommittedTxn(300, 310); TxnView transaction4 = TxnTestUtils.getMockCommittedTxn(1100, 1110); transactions.addAll(Arrays.asList( null, null, null, null, transaction4, transaction3, transaction2, transaction3, transaction1 )); cutPurgeDuringMajorCompaction.mutate(inputCells, transactions, outputCells); assertThat(outputCells, hasSize(5)); assertThat(getRemovedCells(inputCells, outputCells), containsInAnyOrder( SITestUtils.getMockValueCell(100), SITestUtils.getMockTombstoneCell(200), SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockCommitCell(200, 210) )); } @Test public void mutatePurgeConsideringWatermarkKeepTombstone() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(1100, 1110), SITestUtils.getMockCommitCell(300, 310), SITestUtils.getMockCommitCell(200, 210), SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockTombstoneCell(1100), SITestUtils.getMockAntiTombstoneCell(300), SITestUtils.getMockTombstoneCell(200), SITestUtils.getMockValueCell(300), SITestUtils.getMockValueCell(100) )); TxnView transaction1 = TxnTestUtils.getMockCommittedTxn(100, 110); TxnView transaction2 = TxnTestUtils.getMockCommittedTxn(200, 210); TxnView transaction3 = TxnTestUtils.getMockCommittedTxn(300, 310); TxnView transaction4 = TxnTestUtils.getMockCommittedTxn(1100, 1110); transactions.addAll(Arrays.asList( null, null, null, null, transaction4, transaction3, transaction2, transaction3, transaction1 )); cutPurgeDuringFlush.mutate(inputCells, transactions, outputCells); assertThat(outputCells, hasSize(7)); assertThat(getRemovedCells(inputCells, outputCells), containsInAnyOrder( SITestUtils.getMockValueCell(100), SITestUtils.getMockCommitCell(100, 110) )); } @Test public void mutateDoNotPurgeBecauseDeleteStartedBeforeWatermarkButCommittedAfter() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(900, 1100), SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockTombstoneCell(900), SITestUtils.getMockValueCell(100) )); transactions.addAll(Arrays.asList( null, null, TxnTestUtils.getMockCommittedTxn(900, 1100), TxnTestUtils.getMockCommittedTxn(100, 110) )); cutPurgeDuringMajorCompaction.mutate(inputCells, transactions, outputCells); assertThat(outputCells, equalTo(inputCells)); } @Test public void mutatePurgeKeepTombstonesOverriddenByFirstOccurrenceToken() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(200, 210), SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockTombstoneCell(200), SITestUtils.getMockValueCell(100), SITestUtils.getMockFirstWriteCell(100) )); transactions.addAll(Arrays.asList( null, null, TxnTestUtils.getMockCommittedTxn(200, 210), TxnTestUtils.getMockCommittedTxn(100, 110), TxnTestUtils.getMockCommittedTxn(100, 110) )); cutPurgeDuringFlush.mutate(inputCells, transactions, outputCells); assertThat(outputCells, is(empty())); } @Test public void mutatePurgeLatestTombstoneInMinorCompaction() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(200, 210), SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockTombstoneCell(200), SITestUtils.getMockValueCell(100), SITestUtils.getMockDeleteRightAfterFirstWriteCell(200), SITestUtils.getMockFirstWriteCell(100) )); TxnView transaction1 = TxnTestUtils.getMockCommittedTxn(100, 110); TxnView transaction2 = TxnTestUtils.getMockCommittedTxn(200, 210); transactions.addAll(Arrays.asList( null, null, transaction2, transaction1, transaction2, transaction1 )); cutPurgeDuringMinorCompaction.mutate(inputCells, transactions, outputCells); assertThat(outputCells, is(empty())); } @Test public void mutateDoNotPurgeLatestTombstoneInMinorCompactionDespiteTwoTokens() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(400, 410), SITestUtils.getMockCommitCell(300, 310), SITestUtils.getMockCommitCell(200, 210), SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockTombstoneCell(400), SITestUtils.getMockAntiTombstoneCell(300), SITestUtils.getMockTombstoneCell(200), SITestUtils.getMockValueCell(300), SITestUtils.getMockValueCell(100), SITestUtils.getMockDeleteRightAfterFirstWriteCell(200), SITestUtils.getMockFirstWriteCell(100) )); TxnView transaction1 = TxnTestUtils.getMockCommittedTxn(100, 110); TxnView transaction2 = TxnTestUtils.getMockCommittedTxn(200, 210); TxnView transaction3 = TxnTestUtils.getMockCommittedTxn(300, 310); TxnView transaction4 = TxnTestUtils.getMockCommittedTxn(400, 410); transactions.addAll(Arrays.asList( null, null, null, null, transaction4, transaction3, transaction2, transaction3, transaction1, transaction2, transaction1 )); cutPurgeDuringMinorCompaction.mutate(inputCells, transactions, outputCells); assertThat(outputCells, contains( SITestUtils.getMockCommitCell(400, 410), SITestUtils.getMockTombstoneCell(400) )); } @Test public void mutateDoNotPurgeLatestTombstoneDuringMinorCompactionMissingFirstWriteToken() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(200, 210), SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockTombstoneCell(200), SITestUtils.getMockValueCell(100), SITestUtils.getMockDeleteRightAfterFirstWriteCell(200) )); TxnView transaction1 = TxnTestUtils.getMockCommittedTxn(100, 110); TxnView transaction2 = TxnTestUtils.getMockCommittedTxn(200, 210); transactions.addAll(Arrays.asList( null, null, transaction2, transaction1, transaction2 )); cutPurgeDuringMinorCompaction.mutate(inputCells, transactions, outputCells); assertThat(outputCells, hasSize(3)); } @Test public void mutateDoNotPurgeLatestTombstoneDuringMinorCompactionMissingDeleteToken() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(200, 210), SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockTombstoneCell(200), SITestUtils.getMockValueCell(100), SITestUtils.getMockFirstWriteCell(100) )); TxnView transaction1 = TxnTestUtils.getMockCommittedTxn(100, 110); TxnView transaction2 = TxnTestUtils.getMockCommittedTxn(200, 210); transactions.addAll(Arrays.asList( null, null, transaction2, transaction1, transaction1 )); cutPurgeDuringMinorCompaction.mutate(inputCells, transactions, outputCells); assertThat(outputCells, hasSize(2)); } @Test public void mutatePurgeDuringMinorCompactionAntiTombstoneGhostsTombstone() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(200, 210), SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockAntiTombstoneCell(200), SITestUtils.getMockValueCell(200, new boolean[]{true, false, false}), SITestUtils.getMockValueCell(100, new boolean[]{false, true, false}), SITestUtils.getMockDeleteRightAfterFirstWriteCell(200), SITestUtils.getMockFirstWriteCell(100) )); TxnView transaction1 = TxnTestUtils.getMockCommittedTxn(100, 110); TxnView transaction2 = TxnTestUtils.getMockCommittedTxn(200, 210); transactions.addAll(Arrays.asList( null, null, transaction2, transaction2, transaction1, transaction2, transaction1 )); cutPurgeDuringMinorCompaction.mutate(inputCells, transactions, outputCells); assertThat(outputCells, equalTo(inputCells)); } @Test public void mutateCannotPurgeNonGhostingUpdates() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(300, 310), SITestUtils.getMockCommitCell(200, 210), SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockValueCell(300, new boolean[]{false, true, false}), SITestUtils.getMockValueCell(200, new boolean[]{true, false, false}), SITestUtils.getMockValueCell(100, new boolean[]{true, true, true}) )); transactions.addAll(Arrays.asList( null, null, null, TxnTestUtils.getMockCommittedTxn(300, 310), TxnTestUtils.getMockCommittedTxn(200, 210), TxnTestUtils.getMockCommittedTxn(100, 110) )); cutForcePurge.mutate(inputCells, transactions, outputCells); assertThat(outputCells, equalTo(inputCells)); } @Test public void mutatePurgeOneColumnUpdatedOverAndOver() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(300, 310), SITestUtils.getMockCommitCell(200, 210), SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockValueCell(300, new boolean[]{true}), SITestUtils.getMockValueCell(200, new boolean[]{true}), SITestUtils.getMockValueCell(100, new boolean[]{true}) )); transactions.addAll(Arrays.asList( null, null, null, TxnTestUtils.getMockCommittedTxn(300, 310), TxnTestUtils.getMockCommittedTxn(200, 210), TxnTestUtils.getMockCommittedTxn(100, 110) )); cutForcePurge.mutate(inputCells, transactions, outputCells); assertThat(outputCells, hasSize(2)); assertThat(outputCells, contains( SITestUtils.getMockCommitCell(300, 310), SITestUtils.getMockValueCell(300, new boolean[]{true}) )); } @Test public void mutatePurgePartialUpdateButNotBaselineInsert() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(300, 310), SITestUtils.getMockCommitCell(200, 210), SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockValueCell(300, new boolean[]{true, false}), SITestUtils.getMockValueCell(200, new boolean[]{true, false}), SITestUtils.getMockValueCell(100, new boolean[]{true, true}) )); transactions.addAll(Arrays.asList( null, null, null, TxnTestUtils.getMockCommittedTxn(300, 310), TxnTestUtils.getMockCommittedTxn(200, 210), TxnTestUtils.getMockCommittedTxn(100, 110) )); cutForcePurge.mutate(inputCells, transactions, outputCells); assertThat(outputCells, hasSize(4)); assertThat(getRemovedCells(inputCells, outputCells), containsInAnyOrder( SITestUtils.getMockValueCell(200, new boolean[]{true, false}), SITestUtils.getMockCommitCell(200, 210) )); } @Test public void mutatePurgeBaselineUpdateBecausePartialUpdatesCoverItAll() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(300, 310), SITestUtils.getMockCommitCell(200, 210), SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockValueCell(300, new boolean[]{false, true}), SITestUtils.getMockValueCell(200, new boolean[]{true, false}), SITestUtils.getMockValueCell(100, new boolean[]{true, true}) )); transactions.addAll(Arrays.asList( null, null, null, TxnTestUtils.getMockCommittedTxn(300, 310), TxnTestUtils.getMockCommittedTxn(200, 210), TxnTestUtils.getMockCommittedTxn(100, 110) )); cutForcePurge.mutate(inputCells, transactions, outputCells); assertThat(outputCells, hasSize(4)); assertThat(getRemovedCells(inputCells, outputCells), containsInAnyOrder( SITestUtils.getMockValueCell(100, new boolean[]{true, true}), SITestUtils.getMockCommitCell(100, 110) )); } @Test public void mutateDoNotPurgeUpdateBecauseOverrideIsAboveWatermark() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(1200, 1210), SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockValueCell(1200, new boolean[]{true}), SITestUtils.getMockValueCell(100, new boolean[]{true}) )); transactions.addAll(Arrays.asList( null, null, TxnTestUtils.getMockCommittedTxn(1200, 1210), TxnTestUtils.getMockCommittedTxn(100, 110) )); cutForcePurge.mutate(inputCells, transactions, outputCells); assertThat(outputCells, equalTo(inputCells)); } @Test public void mutateDoNotPurgeOldUpdateBecauseOverrideStartedBeforeWatermarkButCommittedAfter() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(900, 1100), SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockValueCell(900), SITestUtils.getMockValueCell(100) )); transactions.addAll(Arrays.asList( null, null, TxnTestUtils.getMockCommittedTxn(900, 1100), TxnTestUtils.getMockCommittedTxn(100, 110) )); cutForcePurge.mutate(inputCells, transactions, outputCells); assertThat(outputCells, equalTo(inputCells)); } @Test public void mutatePurgeUpdatesPrimaryKeys() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(200, 210), SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockValueCell(200, new boolean[]{}), SITestUtils.getMockValueCell(100, new boolean[]{}) )); transactions.addAll(Arrays.asList( null, null, TxnTestUtils.getMockCommittedTxn(200, 210), TxnTestUtils.getMockCommittedTxn(100, 110) )); cutForcePurge.mutate(inputCells, transactions, outputCells); assertThat(outputCells, hasSize(2)); assertThat(getRemovedCells(inputCells, outputCells), containsInAnyOrder( SITestUtils.getMockValueCell(100, new boolean[]{}), SITestUtils.getMockCommitCell(100, 110) )); } @Test public void mutateCalculatesSizeCorrectly() throws IOException { inputCells.addAll(Arrays.asList( SITestUtils.getMockCommitCell(200, 210), SITestUtils.getMockCommitCell(100, 110), SITestUtils.getMockTombstoneCell(200), SITestUtils.getMockValueCell(100) )); transactions.addAll(Arrays.asList( null, null, TxnTestUtils.getMockCommittedTxn(200, 210), TxnTestUtils.getMockCommittedTxn(100, 110) )); long actualSize = cutForcePurge.mutate(inputCells, transactions, outputCells); assertThat(actualSize, equalTo(SITestUtils.getSize(inputCells))); }
FormatableBitSet implements Formatable, Cloneable { public void shrink(int n) { if (SanityManager.DEBUG) { SanityManager.ASSERT(invariantHolds(), "broken invariant"); } if (n < 0 || n > lengthAsBits) { throw new IllegalArgumentException("Bit set cannot shrink from "+ lengthAsBits+" to "+n+" bits"); } final int firstUnusedByte = numBytesFromBits(n); bitsInLastByte = numBitsInLastByte(n); lengthAsBits = n; for (int i = firstUnusedByte; i < value.length; ++i) { value[i] = 0; } if (firstUnusedByte > 0) { value[firstUnusedByte-1] &= 0xff00 >> bitsInLastByte; } } FormatableBitSet(); FormatableBitSet(int numBits); FormatableBitSet(byte[] newValue); FormatableBitSet(FormatableBitSet original); Object clone(); boolean invariantHolds(); int getLengthInBytes(); int getLength(); int size(); byte[] getByteArray(); void grow(int n); void shrink(int n); boolean equals(Object other); int compare(FormatableBitSet other); int hashCode(); final boolean isSet(int position); final boolean get(int position); void set(int position); void clear(int position); void clear(); String toString(); static int maxBitsForSpace(int numBytes); int anySetBit(); int anySetBit(int beyondBit); void or(FormatableBitSet otherBit); void and(FormatableBitSet otherBit); void xor(FormatableBitSet otherBit); int getNumBitsSet(); void writeExternal(ObjectOutput out); void readExternal(ObjectInput in); int getTypeFormatId(); }
@Test public void testShrink() { bitset18.shrink(9); assertEquals(9, bitset18.getLength()); assertEquals(2, bitset18.getLengthInBytes()); assertEquals(5, bitset18.getNumBitsSet()); assertTrue(bitset18.invariantHolds()); assertEquals(2, bitset18.getByteArray().length); } @Test public void testShrinkLarger() { try { bitset18.shrink(25); fail(); } catch (IllegalArgumentException ignored) { } } @Test public void testShrinkNeg() { try { bitset18.shrink(-9); fail(); } catch (IllegalArgumentException ignored) { } }
RingBuffer { public boolean isFull() { return size() == buffer.length; } RingBuffer(int bufferSize); T next(); void add(T element); int size(); int bufferSize(); @SuppressWarnings("unchecked") T peek(); boolean isFull(); boolean isEmpty(); void expand(); void readReset(); void readAdvance(); void clear(); void mark(); }
@Test public void isFull() { RingBuffer<Integer> buffer = new RingBuffer<Integer>(4); buffer.add(10); assertFalse(buffer.isFull()); buffer.add(10); assertFalse(buffer.isFull()); buffer.add(10); assertFalse(buffer.isFull()); buffer.add(10); assertTrue(buffer.isFull()); }
RingBuffer { public int size() { return writePosition - readPosition; } RingBuffer(int bufferSize); T next(); void add(T element); int size(); int bufferSize(); @SuppressWarnings("unchecked") T peek(); boolean isFull(); boolean isEmpty(); void expand(); void readReset(); void readAdvance(); void clear(); void mark(); }
@Test public void size() { RingBuffer<Integer> buffer = new RingBuffer<Integer>(16); assertEquals(0, buffer.size()); buffer.add(42); assertEquals(1, buffer.size()); buffer.add(42); assertEquals(2, buffer.size()); buffer.clear(); assertEquals(0, buffer.size()); }
RingBuffer { public void clear() { readPosition = writePosition; offsetReadPosition = readPosition; } RingBuffer(int bufferSize); T next(); void add(T element); int size(); int bufferSize(); @SuppressWarnings("unchecked") T peek(); boolean isFull(); boolean isEmpty(); void expand(); void readReset(); void readAdvance(); void clear(); void mark(); }
@Test public void clear() throws Exception { int bufferSize = 10; RingBuffer<Integer> buffer = new RingBuffer<Integer>(bufferSize); for (int i = 0; i < bufferSize; i++) { buffer.add(i); } buffer.clear(); assertEquals(0, buffer.size()); assertFalse(buffer.isFull()); assertTrue(buffer.isEmpty()); assertNull("Should not see another value", buffer.next()); }
RingBuffer { public void expand() { buffer = Arrays.copyOf(buffer, 2 * buffer.length); mask = buffer.length - 1; } RingBuffer(int bufferSize); T next(); void add(T element); int size(); int bufferSize(); @SuppressWarnings("unchecked") T peek(); boolean isFull(); boolean isEmpty(); void expand(); void readReset(); void readAdvance(); void clear(); void mark(); }
@Test public void expand() { RingBuffer<Integer> buffer = new RingBuffer<Integer>(2); buffer.add(10); buffer.add(20); assertTrue(buffer.isFull()); buffer.expand(); assertFalse(buffer.isFull()); buffer.add(30); buffer.add(40); assertTrue(buffer.isFull()); assertEquals(4, buffer.size()); assertEquals(4, buffer.bufferSize()); assertEquals(10, buffer.next().intValue()); assertEquals(20, buffer.next().intValue()); assertEquals(30, buffer.next().intValue()); assertEquals(40, buffer.next().intValue()); }
Partition { public static <T> Iterable<List<T>> partition(Collection<T> coll, final int size, final int steps, final boolean pad){ final List<T> c = new ArrayList<T>(coll); final int collSize = c.size(); int padding = Math.max(needsPadding(collSize, size, steps), 0); if (pad && padding > 0) { for (int i = 0; i < padding; i++){ c.add(null); } } return new Iterable<List<T>>() { @Override public Iterator<List<T>> iterator() { return new Iterator<List<T>>() { private int cursor = 0; @Override public boolean hasNext() { return cursor < collSize; } @Override public List<T> next() { if (!hasNext()){ throw new NoSuchElementException(); } List<T> partition = c.subList(cursor, cursor + size < c.size() ? cursor + size : c.size()); cursor = cursor + steps; return Collections.unmodifiableList(partition); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } static Iterable<List<T>> partition(Collection<T> coll, final int size, final int steps, final boolean pad); static Iterable<List<T>> partition(List<T> coll, int size, int steps); static Iterable<List<T>> partition(List<T> coll, int size); static Iterable<List<T>> partition(List<T> coll, int size, boolean pad); }
@Test public void testPartitions() throws Exception { Assert.assertEquals(l(Iterables.toArray(Partition.partition(testColl, 2), Object.class)), l(l(10, 20), l(30, 40), l(50, 60))); Assert.assertEquals(l(Iterables.toArray(Partition.partition(testColl, 2, 1), Object.class)), l(l(10, 20), l(20, 30), l(30, 40), l(40, 50), l(50, 60), l(60))); Assert.assertEquals(l(Iterables.toArray(Partition.partition(testColl, 2, 1, true), Object.class)), l(l(10, 20), l(20, 30), l(30, 40), l(40, 50), l(50, 60), l(60, null))); Assert.assertEquals(l(Iterables.toArray(Partition.partition(testColl, 2, 3, true), Object.class)), l(l(10, 20), l(40, 50))); Assert.assertEquals(l(Iterables.toArray(Partition.partition(testColl, 3, 4, true), Object.class)), l(l(10, 20, 30), l(50, 60, null))); Assert.assertEquals(l(Iterables.toArray(Partition.partition(testColl, 3, 4), Object.class)), l(l(10, 20, 30), l(50, 60))); Assert.assertEquals(l(Iterables.toArray(Partition.partition(testColl, 3, 10, true), Object.class)), l(l(10, 20, 30))); }
Streams { @SafeVarargs public static <T> Stream<T> of(T...elements){ return new ArrayStream<>(elements); } @SafeVarargs static Stream<T> of(T...elements); static Stream<T> wrap(Iterator<T> iterator); static Stream<T> wrap(Iterable<T> iterable); static PeekableStream<T> peekingStream(Stream<T> stream); @SuppressWarnings("unchecked") static Stream<T> empty(); @SuppressWarnings("unchecked") static MeasuredStream<T,V> measuredEmpty(); }
@Test public void of() throws StreamException { Stream<String> stream = Streams.of("111", "222", "333"); assertEquals("111", stream.next()); assertEquals("222", stream.next()); assertEquals("333", stream.next()); }
Streams { public static <T> Stream<T> wrap(Iterator<T> iterator){ return new IteratorStream<>(iterator); } @SafeVarargs static Stream<T> of(T...elements); static Stream<T> wrap(Iterator<T> iterator); static Stream<T> wrap(Iterable<T> iterable); static PeekableStream<T> peekingStream(Stream<T> stream); @SuppressWarnings("unchecked") static Stream<T> empty(); @SuppressWarnings("unchecked") static MeasuredStream<T,V> measuredEmpty(); }
@Test public void wrap() throws StreamException { List<String> list = Lists.newArrayList("111", "222", "333"); Stream<String> stream1 = Streams.wrap(list); Stream<String> stream2 = Streams.wrap(list.iterator()); assertEquals("111", stream1.next()); assertEquals("111", stream2.next()); assertEquals("222", stream1.next()); assertEquals("222", stream2.next()); assertEquals("333", stream1.next()); assertEquals("333", stream2.next()); }
Streams { public static <T> PeekableStream<T> peekingStream(Stream<T> stream){ return new PeekingStream<>(stream); } @SafeVarargs static Stream<T> of(T...elements); static Stream<T> wrap(Iterator<T> iterator); static Stream<T> wrap(Iterable<T> iterable); static PeekableStream<T> peekingStream(Stream<T> stream); @SuppressWarnings("unchecked") static Stream<T> empty(); @SuppressWarnings("unchecked") static MeasuredStream<T,V> measuredEmpty(); }
@Test public void peekingStream() throws StreamException { Stream<String> stream = Streams.of("111", "222", "333"); PeekableStream<String> stream1 = Streams.peekingStream(stream); assertEquals("111", stream1.peek()); assertEquals("111", stream1.next()); assertEquals("222", stream1.peek()); assertEquals("222", stream1.next()); assertEquals("333", stream1.peek()); assertEquals("333", stream1.next()); assertEquals(null, stream1.peek()); }
FormatableBitSet implements Formatable, Cloneable { public int compare(FormatableBitSet other) { int otherCount, thisCount; int otherLen, thisLen; byte[] otherb; otherb = other.value; otherLen = other.getLengthInBytes(); thisLen = getLengthInBytes(); for (otherCount = 0, thisCount = 0; otherCount < otherLen && thisCount < thisLen; otherCount++, thisCount++) { if (otherb[otherCount] != this.value[thisCount]) break; } if ((otherCount == otherLen) && (thisCount == thisLen)) { if (this.getLength() == other.getLength()) { return 0; } return (other.getLength() < this.getLength()) ? 1 : -1; } if (otherCount == otherLen) { return 1; } else if (thisCount == thisLen) { return -1; } else { int otherInt, thisInt; otherInt = (int)otherb[otherCount]; otherInt &= (0x100 - 1); thisInt = (int)this.value[thisCount]; thisInt &= (0x100 - 1); return (thisInt > otherInt) ? 1 : -1; } } FormatableBitSet(); FormatableBitSet(int numBits); FormatableBitSet(byte[] newValue); FormatableBitSet(FormatableBitSet original); Object clone(); boolean invariantHolds(); int getLengthInBytes(); int getLength(); int size(); byte[] getByteArray(); void grow(int n); void shrink(int n); boolean equals(Object other); int compare(FormatableBitSet other); int hashCode(); final boolean isSet(int position); final boolean get(int position); void set(int position); void clear(int position); void clear(); String toString(); static int maxBitsForSpace(int numBytes); int anySetBit(); int anySetBit(int beyondBit); void or(FormatableBitSet otherBit); void and(FormatableBitSet otherBit); void xor(FormatableBitSet otherBit); int getNumBitsSet(); void writeExternal(ObjectOutput out); void readExternal(ObjectInput in); int getTypeFormatId(); }
@Test public void testCompareSameEmpty() { assertEquals(0, empty.compare(empty)); } @Test public void testCompareAnotherEmpty() { assertEquals(0, empty.compare(new FormatableBitSet())); } @Test public void testCompare18Empty() { assertEquals(1, bitset18.compare(new FormatableBitSet())); } @Test public void testCompareEmpty18() { assertEquals(-1, empty.compare(bitset18)); } @Test public void testCompareToComplement() { assertEquals(1, bitset18.compare(bitset18C)); }
AbstractStream implements Stream<T> { @Override public void forEach(Accumulator<T> accumulator) throws StreamException { T n; while((n = next())!=null){ accumulator.accumulate(n); } } @Override Stream<V> transform(Transformer<T, V> transformer); @Override void forEach(Accumulator<T> accumulator); @Override Stream<T> filter(Predicate<T> predicate); @Override Iterator<T> asIterator(); @Override Stream<T> limit(long maxSize); }
@Test public void forEach() throws StreamException { SumAccumulator accumulator = new SumAccumulator(); new IntegerStream().forEach(accumulator); assertEquals(45, accumulator.sum); }
AbstractStream implements Stream<T> { @Override public <V> Stream<V> transform(Transformer<T, V> transformer) { return new TransformingStream<>(this,transformer); } @Override Stream<V> transform(Transformer<T, V> transformer); @Override void forEach(Accumulator<T> accumulator); @Override Stream<T> filter(Predicate<T> predicate); @Override Iterator<T> asIterator(); @Override Stream<T> limit(long maxSize); }
@Test public void transform() throws StreamException { SumAccumulator accumulator = new SumAccumulator(); new IntegerStream().transform(new NegateTransformer()).forEach(accumulator); assertEquals(-45, accumulator.sum); }
Threads { public static void sleep(long duration, TimeUnit timeUnit) { try { Thread.sleep(timeUnit.toMillis(duration)); } catch (InterruptedException e) { throw new IllegalStateException(e); } } private Threads(); static void sleep(long duration, TimeUnit timeUnit); }
@Test public void sleep() { long startTime = System.currentTimeMillis(); Threads.sleep(100, TimeUnit.MILLISECONDS); long elapsedTime = System.currentTimeMillis() - startTime; assertTrue(elapsedTime < 1000); assertTrue(elapsedTime > 75); }
CountDownLatches { public static void uncheckedAwait(CountDownLatch countDownLatch) { try { countDownLatch.await(); } catch (InterruptedException e) { throw new IllegalStateException(e); } } static void uncheckedAwait(CountDownLatch countDownLatch); static boolean uncheckedAwait(CountDownLatch countDownLatch, long timeout, TimeUnit timeUnit); }
@Test public void testUncheckedAwait() throws Exception { final CountDownLatch latch = new CountDownLatch(1); new Thread() { @Override public void run() { latch.countDown(); } }.start(); CountDownLatches.uncheckedAwait(latch); } @Test public void testUncheckedAwaitWithTimeout() throws Exception { final CountDownLatch latch = new CountDownLatch(1); new Thread() { @Override public void run() { latch.countDown(); } }.start(); assertTrue(CountDownLatches.uncheckedAwait(latch, 5, TimeUnit.SECONDS)); } @Test public void testUncheckedAwaitWithTimeoutReturnsFalse() throws Exception { final CountDownLatch latch = new CountDownLatch(1); new Thread() { @Override public void run() { Threads.sleep(5, TimeUnit.SECONDS); } }.start(); assertFalse(CountDownLatches.uncheckedAwait(latch, 50, TimeUnit.MILLISECONDS)); }
MoreExecutors { public static ExecutorService namedSingleThreadExecutor(String nameFormat, boolean isDaemon) { ThreadFactory factory = new ThreadFactoryBuilder() .setNameFormat(nameFormat) .setDaemon(isDaemon) .build(); return Executors.newSingleThreadExecutor(factory); } private MoreExecutors(); static ExecutorService namedSingleThreadExecutor(String nameFormat, boolean isDaemon); static ScheduledExecutorService namedSingleThreadScheduledExecutor(String nameFormat); static ThreadPoolExecutor namedThreadPool(int coreWorkers, int maxWorkers, String nameFormat, long keepAliveSeconds, boolean isDaemon); }
@Test public void newSingleThreadExecutor_usesThreadWithExpectedName() throws Exception { ExecutorService executorService = MoreExecutors.namedSingleThreadExecutor("testName-%d", false); Future<String> threadName = executorService.submit(new GetThreadNameCallable()); Future<Boolean> isDaemon = executorService.submit(new IsDaemonCallable()); assertTrue(threadName.get().matches("testName-\\d")); assertEquals(false, isDaemon.get()); executorService.shutdown(); }
MoreExecutors { public static ScheduledExecutorService namedSingleThreadScheduledExecutor(String nameFormat) { ThreadFactory factory = new ThreadFactoryBuilder() .setNameFormat(nameFormat) .setDaemon(true) .build(); return new LoggingScheduledThreadPoolExecutor(1, factory); } private MoreExecutors(); static ExecutorService namedSingleThreadExecutor(String nameFormat, boolean isDaemon); static ScheduledExecutorService namedSingleThreadScheduledExecutor(String nameFormat); static ThreadPoolExecutor namedThreadPool(int coreWorkers, int maxWorkers, String nameFormat, long keepAliveSeconds, boolean isDaemon); }
@Test public void namedSingleThreadScheduledExecutor() throws Exception { ScheduledExecutorService executorService = MoreExecutors.namedSingleThreadScheduledExecutor("testName-%d"); Future<String> threadName = executorService.submit(new GetThreadNameCallable()); Future<Boolean> isDaemon = executorService.submit(new IsDaemonCallable()); assertTrue(threadName.get().matches("testName-\\d")); assertEquals(true, isDaemon.get()); executorService.shutdown(); }
MoreExecutors { public static ThreadPoolExecutor namedThreadPool(int coreWorkers, int maxWorkers, String nameFormat, long keepAliveSeconds, boolean isDaemon) { ThreadFactory factory = new ThreadFactoryBuilder() .setNameFormat(nameFormat) .setDaemon(isDaemon) .build(); return new ThreadPoolExecutor(coreWorkers, maxWorkers, keepAliveSeconds, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), factory); } private MoreExecutors(); static ExecutorService namedSingleThreadExecutor(String nameFormat, boolean isDaemon); static ScheduledExecutorService namedSingleThreadScheduledExecutor(String nameFormat); static ThreadPoolExecutor namedThreadPool(int coreWorkers, int maxWorkers, String nameFormat, long keepAliveSeconds, boolean isDaemon); }
@Test public void namedThreadPool() throws Exception { final int CORE_POOL_SIZE = 1 + new Random().nextInt(9); final int MAX_POOL_SIZE = CORE_POOL_SIZE + new Random().nextInt(9); final int KEEP_ALIVE_SEC = new Random().nextInt(100); final boolean IS_DAEMON = new Random().nextBoolean(); ThreadPoolExecutor executorService = MoreExecutors.namedThreadPool(CORE_POOL_SIZE, MAX_POOL_SIZE, "testName-%d", KEEP_ALIVE_SEC, IS_DAEMON); Future<String> threadName = executorService.submit(new GetThreadNameCallable()); Future<Boolean> isDaemon = executorService.submit(new IsDaemonCallable()); assertEquals(CORE_POOL_SIZE, executorService.getCorePoolSize()); assertEquals(MAX_POOL_SIZE, executorService.getMaximumPoolSize()); assertEquals(KEEP_ALIVE_SEC, executorService.getKeepAliveTime(TimeUnit.SECONDS)); assertEquals(IS_DAEMON, isDaemon.get()); assertTrue(threadName.get().matches("testName-\\d")); executorService.shutdown(); }
LongStripedSynchronizer { public static LongStripedSynchronizer<ReadWriteLock> stripedReadWriteLock(int stripes, final boolean fair){ int s = getNearestPowerOf2(stripes); return new LongStripedSynchronizer<ReadWriteLock>(s,new Supplier<ReadWriteLock>() { @Override public ReadWriteLock get() { return new ReentrantReadWriteLock(fair); } }); } private LongStripedSynchronizer(int size,Supplier<T> supplier); static LongStripedSynchronizer<Lock> stripedLock(int stripes); static LongStripedSynchronizer<ReadWriteLock> stripedReadWriteLock(int stripes, final boolean fair); static LongStripedSynchronizer<Semaphore> stripedSemaphor(int stripes, final int permitSize); @SuppressWarnings("unchecked") T get(long key); }
@Test public void stripedReadWriteLock() { LongStripedSynchronizer<ReadWriteLock> striped = LongStripedSynchronizer.stripedReadWriteLock(128, false); Set<ReadWriteLock> locks = Sets.newIdentityHashSet(); for (long i = 0; i < 2000; i++) { ReadWriteLock e = striped.get(i); locks.add(e); } assertEquals(128, locks.size()); }
Snowflake { public long nextUUID(){ long timestamp; short count; synchronized (this){ timestamp = System.currentTimeMillis(); if(timestamp<lastTimestamp) throw new IllegalStateException("Unable to obtain timestamp, clock moved backwards"); if(timestamp==lastTimestamp){ if(counter==0) while(timestamp ==lastTimestamp) timestamp = System.currentTimeMillis(); } count = counter; counter++; counter = (short)(counter & COUNTER_MASK); lastTimestamp = timestamp; } return buildUUID(timestamp, count); } Snowflake(short machineId); static long timestampFromUUID(long uuid); byte[] nextUUIDBytes(); void nextUUIDBlock(long[] uuids); long nextUUID(); Generator newGenerator(int blockSize); @Override String toString(); static final long TIMESTAMP_MASK; static final int TIMESTAMP_SHIFT; static final int UUID_BYTE_SIZE; }
@Test public void testcanCreateAUUID() throws Exception { Snowflake snowflake = new Snowflake((short)(1<<6)); long uuid = snowflake.nextUUID(); Assert.assertTrue(uuid != 0); } @Test public void testNoDuplicateUUIDsInASingleThread() throws Exception { Set<Long> uuidSet = new TreeSet<Long>(); Snowflake snowflake = new Snowflake((short)(1<<7)); for(int i=0;i<100000;i++){ long uuid = snowflake.nextUUID(); Assert.assertFalse("duplicate uuid found!",uuidSet.contains(uuid)); uuidSet.add(uuid); } } @Test public void testNoDuplicatesManyThreadsSameSnowflake() throws Exception { int numThreads=3; final int numIterations = 50000; ExecutorService executor = Executors.newFixedThreadPool(numThreads); final ConcurrentMap<Long,Boolean> existing = new ConcurrentHashMap<Long, Boolean>(); List<Future<Boolean>> futures = new ArrayList<Future<Boolean>>(numThreads); final CyclicBarrier startBarrier = new CyclicBarrier(numThreads+1); final Snowflake snowflake = new Snowflake((short)((1<<11)+1)); for(int i=0;i<numThreads;i++){ futures.add(executor.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { startBarrier.await(); for(int i=0;i<numIterations;i++){ long time = System.currentTimeMillis(); long uuid = snowflake.nextUUID(); if(existing.putIfAbsent(uuid,true)!=null){ System.out.println(" already present!i= "+i+", value="+Long.toBinaryString(uuid)+", time="+Long.toBinaryString(time)); return false; } } return true; } })); } startBarrier.await(); for(Future<Boolean> future:futures){ Assert.assertTrue("Duplicate entry found!",future.get()); } assertEquals("Incorrect number of uuids generated!", numThreads * numIterations, existing.size()); } @Test public void testNoDuplicatesManyThreads() throws Exception { int numThreads=5; final int numIterations = 100000; ExecutorService executor = Executors.newFixedThreadPool(numThreads); final ConcurrentMap<Long,Boolean> existing = new ConcurrentHashMap<Long, Boolean>(); List<Future<Boolean>> futures = new ArrayList<Future<Boolean>>(numThreads); final CyclicBarrier startBarrier = new CyclicBarrier(numThreads+1); final AtomicInteger counter = new AtomicInteger(0); for(int i=0;i<numThreads;i++){ futures.add(executor.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { short nextMachineId = (short)(counter.incrementAndGet()); Snowflake snowflake = new Snowflake(nextMachineId); startBarrier.await(); for(int i=0;i<numIterations;i++){ long uuid = snowflake.nextUUID(); if(existing.putIfAbsent(uuid,true)!=null){ System.out.println(" already present!i= "+i+", value="+Long.toBinaryString(uuid)+", time="+Long.toBinaryString(System.currentTimeMillis())); return false; } } return true; } })); } startBarrier.await(); for(Future<Boolean> future:futures){ Assert.assertTrue("Duplicate entry found!",future.get()); } assertEquals("Incorrect number of uuids generated!", numThreads * numIterations, existing.size()); }
Snowflake { public static long timestampFromUUID(long uuid) { return (uuid & TIMESTAMP_LOCATION) >> TIMESTAMP_SHIFT; } Snowflake(short machineId); static long timestampFromUUID(long uuid); byte[] nextUUIDBytes(); void nextUUIDBlock(long[] uuids); long nextUUID(); Generator newGenerator(int blockSize); @Override String toString(); static final long TIMESTAMP_MASK; static final int TIMESTAMP_SHIFT; static final int UUID_BYTE_SIZE; }
@Test public void timestampFromUUID() { assertEquals(1402425368772L, Snowflake.timestampFromUUID(-2074918693534679039l)); assertEquals(1402425369637L, Snowflake.timestampFromUUID(-7920591009858039807l)); assertEquals(1402425368822L, Snowflake.timestampFromUUID(-903982790418145279l)); assertEquals(1402425369571L, Snowflake.timestampFromUUID(-9091526912974639103l)); assertEquals(1402425371394L, Snowflake.timestampFromUUID(2320594542789664769l)); assertEquals(1402425364788L, Snowflake.timestampFromUUID(-6857741497818464255l)); assertEquals(1402425364777L, Snowflake.timestampFromUUID(-6875755896327991295l)); assertEquals(1402425368039L, Snowflake.timestampFromUUID(-4533884090081972223l)); }
Snowflake { @Override public String toString() { return "Snowflake{" + "lastTimestamp=" + lastTimestamp + ", counter=" + counter + ", machineId=" + machineId + '}'; } Snowflake(short machineId); static long timestampFromUUID(long uuid); byte[] nextUUIDBytes(); void nextUUIDBlock(long[] uuids); long nextUUID(); Generator newGenerator(int blockSize); @Override String toString(); static final long TIMESTAMP_MASK; static final int TIMESTAMP_SHIFT; static final int UUID_BYTE_SIZE; }
@Test public void toString_includesExpectedMachineId() { assertEquals("Snowflake{lastTimestamp=0, counter=0, machineId=2}", new Snowflake((short) (1 << 1)).toString()); assertEquals("Snowflake{lastTimestamp=0, counter=0, machineId=4}", new Snowflake((short) (1 << 2)).toString()); assertEquals("Snowflake{lastTimestamp=0, counter=0, machineId=8}", new Snowflake((short) (1 << 3)).toString()); assertEquals("Snowflake{lastTimestamp=0, counter=0, machineId=16}", new Snowflake((short) (1 << 4)).toString()); assertEquals("Snowflake{lastTimestamp=0, counter=0, machineId=32}", new Snowflake((short) (1 << 5)).toString()); assertEquals("Snowflake{lastTimestamp=0, counter=0, machineId=64}", new Snowflake((short) (1 << 6)).toString()); assertEquals("Snowflake{lastTimestamp=0, counter=0, machineId=2048}", new Snowflake((short) (1 << 11)).toString()); }
Murmur64 implements Hash64 { @Override public long hash(String elem) { assert elem!=null: "Cannot hash a null element"; int length = elem.length(); long h = initialize(seed,length); int pos =0; char[] chars = elem.toCharArray(); while(length-pos>=8){ h = hash(h, LittleEndianBits.toLong(chars, pos)); pos+=8; } h = updatePartial(chars,length-pos,h,pos); return finalize(h); } Murmur64(int seed); @Override long hash(String elem); @Override long hash(byte[] data, int offset, int length); @Override long hash(ByteBuffer byteBuffer); @Override long hash(long element); @Override long hash(int element); @Override long hash(float element); @Override long hash(double element); }
@Test public void testByteBufferSameAsByteArray() throws Exception { long correct = hasher.hash(sampleData,0,sampleData.length); ByteBuffer bb = ByteBuffer.wrap(sampleData); long actual = hasher.hash(bb); Assert.assertEquals(correct,actual); } @Test public void testIntSameAsByteArray() throws Exception { byte[] bytes = Bytes.toBytes(sampleValue); long correct = hasher.hash(bytes,0,bytes.length); long actual = hasher.hash(sampleValue); Assert.assertEquals("Incorrect int hash!",correct,actual); } @Test public void testLongSameAsByteArray() throws Exception { byte[] bytes = Bytes.toBytes(sampleLong); long correct = hasher.hash(bytes,0,bytes.length); long actual = hasher.hash(sampleLong); Assert.assertEquals("Incorrect long hash!",correct,actual); }
Murmur32 implements Hash32 { @Override public int hash(String elem) { assert elem!=null: "Cannot hash a null element!"; int h = seed; int length = elem.length(); int pos = 0; int visited =0; char[] chars = elem.toCharArray(); while(length-visited>=4){ int k1 = LittleEndianBits.toInt(chars, pos); h = mutate(h,k1); pos+=2; visited+=4; } h = updatePartial(chars,length,pos,h,visited); return finalize(h); } Murmur32(int seed); @Override int hash(String elem); @Override int hash(byte[] bytes, int offset, int length); @Override int hash(long item); @Override int hash(int element); @Override int hash(short element); @Override int hash(ByteBuffer bytes); static void main(String...args); }
@Test public void testMatchesGoogleVersionMurmur332() throws Exception { HashCode hashCode = Hashing.murmur3_32(0).hashBytes(sampleData, 0, sampleData.length); int actual =hashCode.asInt(); int hash = murmur32.hash(sampleData, 0, sampleData.length); Assert.assertEquals(actual,hash); } @Test public void testMatchesGoogleVersionMurmur332SubBuffers() throws Exception { HashCode hashCode = Hashing.murmur3_32(0).hashBytes(sampleData, sampleOffset, sampleLength); int actual =hashCode.asInt(); int hash = murmur32.hash(sampleData, sampleOffset, sampleLength); Assert.assertEquals(actual,hash); } @Test public void testByteBufferSameAsByteArray() throws Exception { int correct = murmur32.hash(sampleData,0,sampleData.length); ByteBuffer bb = ByteBuffer.wrap(sampleData); int actual = murmur32.hash(bb); Assert.assertEquals(correct,actual); } @Test public void testIntSameAsByteArray() throws Exception { byte[] bytes = Bytes.toBytes(sampleValue); int correct = murmur32.hash(bytes,0,bytes.length); int actual = murmur32.hash(sampleValue); Assert.assertEquals("Incorrect int hash!",correct,actual); } @Test public void testLongSameAsByteArray() throws Exception { byte[] bytes = Bytes.toBytes(sampleLong); int correct = murmur32.hash(bytes,0,bytes.length); int actual = murmur32.hash(sampleLong); Assert.assertEquals("Incorrect int hash!",correct,actual); }
QuoteTrackingTokenizer extends AbstractTokenizer { @Override public boolean readColumns(final List<String> columns) throws IOException { return readColumns(columns, null); } QuoteTrackingTokenizer(final Reader reader, final CsvPreference preferences, final boolean oneLineRecord, boolean quotedEmptyIsNull); QuoteTrackingTokenizer(final Reader reader, final CsvPreference preferences, final boolean oneLineRecord, boolean quotedEmptyIsNull, final long scanThresold, final List<Integer> valueSizeHints); @Override boolean readColumns(final List<String> columns); boolean readColumns(final List<String> columns, final BooleanList quotedColumns); void clearRow(); String getUntokenizedRow(); }
@Test public void quotedMultiRowRecordWithOneLineRecordSetThrowsProperly() throws Exception { String invalidRow = "\"hello\",\"wrong\ncell\",goodbye\n"; try { QuoteTrackingTokenizer qtt = new QuoteTrackingTokenizer(new StringReader(invalidRow), CsvPreference.STANDARD_PREFERENCE, true, true); List<String> columns = new ArrayList<>(); qtt.readColumns(columns); Assert.fail("expected exception to be thrown, but no exception was thrown"); } catch(Exception e) { Assert.assertTrue(e instanceof SuperCsvException); Assert.assertEquals("one-line record CSV has a record that spans over multiple lines at line 1", e.getMessage()); return; } Assert.fail("expected exception to be thrown, but no exception was thrown"); }
BareKeyHash { public static DataHash encoder(int[] keyColumns,boolean[] keySortOrder,DescriptorSerializer[] serializers){ return encoder(keyColumns,keySortOrder,SpliceKryoRegistry.getInstance(),serializers); } protected BareKeyHash(int[] keyColumns, boolean[] keySortOrder, boolean sparse, KryoPool kryoPool, DescriptorSerializer[] serializers); static DataHash encoder(int[] keyColumns,boolean[] keySortOrder,DescriptorSerializer[] serializers); static DataHash encoder(int[] keyColumns,boolean[] keySortOrder,KryoPool kryoPool,DescriptorSerializer[] serializers); static KeyHashDecoder decoder(int[] keyColumns,boolean[] keySortOrder,DescriptorSerializer[] serializers); static KeyHashDecoder decoder(int[] keyColumns,boolean[] keySortOrder,KryoPool kryoPool,DescriptorSerializer[] serializers); void close(); }
@Test public void testProperlyEncodesValues() throws Exception { ExecRow execRow = new ValueRow(dataTypes.length); for(int i=0;i<dataTypes.length;i++){ execRow.setColumn(i + 1, row[i].cloneValue(true)); } int[] keyColumns= new int[dataTypes.length]; for(int i=0;i<keyColumns.length;i++){ keyColumns[i] = i; } DescriptorSerializer[] serializers = VersionedSerializers.latestVersion(true).getSerializers(execRow); DataHash bareKeyHash = BareKeyHash.encoder(keyColumns,null,serializers); bareKeyHash.setRow(execRow); byte[] data = bareKeyHash.encode(); MultiFieldDecoder decoder = MultiFieldDecoder.wrap(data); for(int i=0;i<dataTypes.length;i++){ TestingDataType dt = dataTypes[i]; DataValueDescriptor field = execRow.getColumn(i+1); if(row[i].isNull()){ String errorMsg = "Incorrectly encoded a null value!"; if(dt==TestingDataType.REAL) Assert.assertTrue(errorMsg,decoder.nextIsNullFloat()); else if(dt==TestingDataType.DOUBLE) Assert.assertTrue(errorMsg,decoder.nextIsNullDouble()); else Assert.assertTrue(errorMsg,decoder.nextIsNull()); continue; } String errorMsg = "Incorrectly encoded a non-null field as null!"; if(dt==TestingDataType.REAL) Assert.assertFalse(errorMsg,decoder.nextIsNullFloat()); else if(dt==TestingDataType.DOUBLE) Assert.assertFalse(errorMsg,decoder.nextIsNullDouble()); else Assert.assertFalse(errorMsg,decoder.nextIsNull()); dt.decodeNext(field,decoder); Assert.assertEquals("Row<"+ Arrays.toString(row)+">Incorrect serialization of field "+ row[i],row[i],field); } } @Test public void testCanEncodeAndDecodeProperly() throws Exception { ExecRow execRow = new ValueRow(dataTypes.length); for(int i=0;i<dataTypes.length;i++){ execRow.setColumn(i + 1, row[i].cloneValue(true)); } int[] keyColumns= new int[dataTypes.length]; for(int i=0;i<keyColumns.length;i++){ keyColumns[i] = i; } DescriptorSerializer[] serializers = VersionedSerializers.latestVersion(true).getSerializers(execRow); DataHash bareKeyHash = BareKeyHash.encoder(keyColumns,null,serializers); bareKeyHash.setRow(execRow); byte[] data = bareKeyHash.encode(); KeyHashDecoder decoder = bareKeyHash.getDecoder(); ExecRow clone = execRow.getNewNullRow(); decoder.set(data,0,data.length); decoder.decode(clone); ImportTestUtils.assertRowsEquals(execRow,clone); } @Test public void testCanEncodeAndDecodeProperlyOutOfOrderKeyCols() throws Exception { ExecRow execRow = new ValueRow(dataTypes.length); for(int i=0;i<dataTypes.length;i++){ execRow.setColumn(i + 1, row[i].cloneValue(true)); } int[] keyColumns= new int[dataTypes.length]; Set<Integer> columns = Sets.newHashSet(); for(int i=0;i<10;i++) columns.add(i); Iterator<Integer> colIt = columns.iterator(); for(int i=0;i<keyColumns.length;i++){ keyColumns[i] = colIt.next(); colIt.remove(); } DescriptorSerializer[] serializers = VersionedSerializers.latestVersion(true).getSerializers(execRow); DataHash bareKeyHash = BareKeyHash.encoder(keyColumns,null,serializers); bareKeyHash.setRow(execRow); byte[] data = bareKeyHash.encode(); KeyHashDecoder decoder = bareKeyHash.getDecoder(); ExecRow clone = execRow.getNewNullRow(); decoder.set(data,0,data.length); decoder.decode(clone); ImportTestUtils.assertRowsEquals(execRow,clone); }
TimestampV2DescriptorSerializer extends TimestampV1DescriptorSerializer { public static long formatLong(Timestamp timestamp) throws StandardException { long millis = SQLTimestamp.checkV2Bounds(timestamp); long micros = timestamp.getNanos() / NANOS_TO_MICROS; return millis * MICROS_TO_SECOND + micros; } static long formatLong(Timestamp timestamp); static final Factory INSTANCE_FACTORY; }
@Test public void shouldFailOnSmallDate() { String errorCode = "N/A"; try { TimestampV2DescriptorSerializer.formatLong(getTimestamp(1677)); } catch (StandardException e) { errorCode = e.getSqlState(); } assertEquals(SQLState.LANG_DATE_TIME_ARITHMETIC_OVERFLOW, errorCode); } @Test public void shouldFailOnLargeDate() { String errorCode = "N/A"; try { TimestampV2DescriptorSerializer.formatLong(getTimestamp(2263)); } catch (StandardException e) { errorCode = e.getSqlState(); } assertEquals(SQLState.LANG_DATE_TIME_ARITHMETIC_OVERFLOW, errorCode); }
SpliceDateFunctions { public static Date ADD_MONTHS(Date source, Integer numOfMonths) { if (source == null || numOfMonths == null) return null; DateTime dt = new DateTime(source); return new Date(dt.plusMonths(numOfMonths).getMillis()); } static Date ADD_MONTHS(Date source, Integer numOfMonths); static Date ADD_DAYS(Date source, Integer numOfDays); static Date ADD_YEARS(Date source, Integer numOfYears); static Timestamp TO_TIMESTAMP(String source); static Timestamp TO_TIMESTAMP(String source, String format, SpliceDateTimeFormatter formatter); static Timestamp TO_TIMESTAMP(String source, String format); static Timestamp TO_TIMESTAMP(String source, String format, ZoneId zoneId); static Time TO_TIME(String source); static Time TO_TIME(String source, String format); static Time TO_TIME(String source, String format, ZoneId zoneId); static Time TO_TIME(String source, String format, SpliceDateTimeFormatter formatter); static Date TO_DATE(String source); static Date TO_DATE(String source, String format); static Date TO_DATE(String source, String format, ZoneId zoneId); static Date TO_DATE(String source, String format, SpliceDateTimeFormatter formatter); static Date stringWithFormatToDate(String source, SpliceDateTimeFormatter formatter); static Date LAST_DAY(Date source); static Date NEXT_DAY(Date source, String weekday); static double MONTH_BETWEEN(Date source1, Date source2); static String TO_CHAR(Date source, String format); static String TIMESTAMP_TO_CHAR(Timestamp stamp, String output); static Timestamp TRUNC_DATE(Timestamp source, String field); }
@Test public void testAddMonth() { Calendar c = Calendar.getInstance(); Date t = new Date(c.getTime().getTime()); c.add(Calendar.MONTH, 2); Date s = new Date(c.getTime().getTime()); assertEquals(SpliceDateFunctions.ADD_MONTHS(t, 2), s); }
SpliceDateFunctions { public static Date ADD_DAYS(Date source, Integer numOfDays) { if (source == null || numOfDays == null) return null; DateTime dt = new DateTime(source); return new Date(dt.plusDays(numOfDays).getMillis()); } static Date ADD_MONTHS(Date source, Integer numOfMonths); static Date ADD_DAYS(Date source, Integer numOfDays); static Date ADD_YEARS(Date source, Integer numOfYears); static Timestamp TO_TIMESTAMP(String source); static Timestamp TO_TIMESTAMP(String source, String format, SpliceDateTimeFormatter formatter); static Timestamp TO_TIMESTAMP(String source, String format); static Timestamp TO_TIMESTAMP(String source, String format, ZoneId zoneId); static Time TO_TIME(String source); static Time TO_TIME(String source, String format); static Time TO_TIME(String source, String format, ZoneId zoneId); static Time TO_TIME(String source, String format, SpliceDateTimeFormatter formatter); static Date TO_DATE(String source); static Date TO_DATE(String source, String format); static Date TO_DATE(String source, String format, ZoneId zoneId); static Date TO_DATE(String source, String format, SpliceDateTimeFormatter formatter); static Date stringWithFormatToDate(String source, SpliceDateTimeFormatter formatter); static Date LAST_DAY(Date source); static Date NEXT_DAY(Date source, String weekday); static double MONTH_BETWEEN(Date source1, Date source2); static String TO_CHAR(Date source, String format); static String TIMESTAMP_TO_CHAR(Timestamp stamp, String output); static Timestamp TRUNC_DATE(Timestamp source, String field); }
@Test public void testAddDays() { Calendar c = Calendar.getInstance(); Date t = new Date(c.getTime().getTime()); c.add(Calendar.DAY_OF_MONTH, 2); Date s = new Date(c.getTime().getTime()); assertEquals(SpliceDateFunctions.ADD_DAYS(t, 2), s); }
SpliceDateFunctions { public static Date ADD_YEARS(Date source, Integer numOfYears) { if (source == null || numOfYears == null) return null; DateTime dt = new DateTime(source); return new Date(dt.plusYears(numOfYears).getMillis()); } static Date ADD_MONTHS(Date source, Integer numOfMonths); static Date ADD_DAYS(Date source, Integer numOfDays); static Date ADD_YEARS(Date source, Integer numOfYears); static Timestamp TO_TIMESTAMP(String source); static Timestamp TO_TIMESTAMP(String source, String format, SpliceDateTimeFormatter formatter); static Timestamp TO_TIMESTAMP(String source, String format); static Timestamp TO_TIMESTAMP(String source, String format, ZoneId zoneId); static Time TO_TIME(String source); static Time TO_TIME(String source, String format); static Time TO_TIME(String source, String format, ZoneId zoneId); static Time TO_TIME(String source, String format, SpliceDateTimeFormatter formatter); static Date TO_DATE(String source); static Date TO_DATE(String source, String format); static Date TO_DATE(String source, String format, ZoneId zoneId); static Date TO_DATE(String source, String format, SpliceDateTimeFormatter formatter); static Date stringWithFormatToDate(String source, SpliceDateTimeFormatter formatter); static Date LAST_DAY(Date source); static Date NEXT_DAY(Date source, String weekday); static double MONTH_BETWEEN(Date source1, Date source2); static String TO_CHAR(Date source, String format); static String TIMESTAMP_TO_CHAR(Timestamp stamp, String output); static Timestamp TRUNC_DATE(Timestamp source, String field); }
@Test public void testAddYears() { Calendar c = Calendar.getInstance(); Date t = new Date(c.getTime().getTime()); c.add(Calendar.YEAR, 2); Date s = new Date(c.getTime().getTime()); assertEquals(SpliceDateFunctions.ADD_YEARS(t, 2), s); }
SpliceDateFunctions { public static Date LAST_DAY(Date source) { if (source == null) { return null; } DateTime dt = new DateTime(source).dayOfMonth().withMaximumValue(); return new Date(dt.getMillis()); } static Date ADD_MONTHS(Date source, Integer numOfMonths); static Date ADD_DAYS(Date source, Integer numOfDays); static Date ADD_YEARS(Date source, Integer numOfYears); static Timestamp TO_TIMESTAMP(String source); static Timestamp TO_TIMESTAMP(String source, String format, SpliceDateTimeFormatter formatter); static Timestamp TO_TIMESTAMP(String source, String format); static Timestamp TO_TIMESTAMP(String source, String format, ZoneId zoneId); static Time TO_TIME(String source); static Time TO_TIME(String source, String format); static Time TO_TIME(String source, String format, ZoneId zoneId); static Time TO_TIME(String source, String format, SpliceDateTimeFormatter formatter); static Date TO_DATE(String source); static Date TO_DATE(String source, String format); static Date TO_DATE(String source, String format, ZoneId zoneId); static Date TO_DATE(String source, String format, SpliceDateTimeFormatter formatter); static Date stringWithFormatToDate(String source, SpliceDateTimeFormatter formatter); static Date LAST_DAY(Date source); static Date NEXT_DAY(Date source, String weekday); static double MONTH_BETWEEN(Date source1, Date source2); static String TO_CHAR(Date source, String format); static String TIMESTAMP_TO_CHAR(Timestamp stamp, String output); static Timestamp TRUNC_DATE(Timestamp source, String field); }
@Test public void testLastDay() { Calendar c = Calendar.getInstance(); Date t = new Date(c.getTime().getTime()); c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH)); Date s = new Date(c.getTime().getTime()); assertEquals(SpliceDateFunctions.LAST_DAY(t), s); }
SpliceDateFunctions { public static Date NEXT_DAY(Date source, String weekday) throws SQLException { if (source == null || weekday == null) return source; String lowerWeekday = weekday.toLowerCase(); if (!WEEK_DAY_MAP.containsKey(lowerWeekday)) { throw PublicAPI.wrapStandardException(ErrorState.LANG_INVALID_DAY.newException(weekday)); } DateTime dt = new DateTime(source); int increment = WEEK_DAY_MAP.get(lowerWeekday) - dt.getDayOfWeek() - 1; if (increment > 0) { return new Date(dt.plusDays(increment).getMillis()); } else { return new Date(dt.plusDays(7 + increment).getMillis()); } } static Date ADD_MONTHS(Date source, Integer numOfMonths); static Date ADD_DAYS(Date source, Integer numOfDays); static Date ADD_YEARS(Date source, Integer numOfYears); static Timestamp TO_TIMESTAMP(String source); static Timestamp TO_TIMESTAMP(String source, String format, SpliceDateTimeFormatter formatter); static Timestamp TO_TIMESTAMP(String source, String format); static Timestamp TO_TIMESTAMP(String source, String format, ZoneId zoneId); static Time TO_TIME(String source); static Time TO_TIME(String source, String format); static Time TO_TIME(String source, String format, ZoneId zoneId); static Time TO_TIME(String source, String format, SpliceDateTimeFormatter formatter); static Date TO_DATE(String source); static Date TO_DATE(String source, String format); static Date TO_DATE(String source, String format, ZoneId zoneId); static Date TO_DATE(String source, String format, SpliceDateTimeFormatter formatter); static Date stringWithFormatToDate(String source, SpliceDateTimeFormatter formatter); static Date LAST_DAY(Date source); static Date NEXT_DAY(Date source, String weekday); static double MONTH_BETWEEN(Date source1, Date source2); static String TO_CHAR(Date source, String format); static String TIMESTAMP_TO_CHAR(Timestamp stamp, String output); static Timestamp TRUNC_DATE(Timestamp source, String field); }
@Test public void nextDay() throws ParseException, SQLException { Date date1 = new Date(DF.parse("2014/06/24").getTime()); Date date2 = new Date(DF.parse("2014/06/29").getTime()); Date date3 = new Date(DF.parse("2014/06/25").getTime()); Date date4 = new Date(DF.parse("2014/06/27").getTime()); Date date5 = new Date(DF.parse("2014/05/12").getTime()); Date date6 = new Date(DF.parse("2014/05/17").getTime()); assertEquals(date3, SpliceDateFunctions.NEXT_DAY(date1, "wednesday")); assertEquals(date2, SpliceDateFunctions.NEXT_DAY(date1, "sunday")); assertEquals(date4, SpliceDateFunctions.NEXT_DAY(date1, "friday")); assertEquals(date6, SpliceDateFunctions.NEXT_DAY(date5, "saturday")); } @Test public void nextDayIsNotCaseSensitive() throws ParseException, SQLException { Date startDate = new Date(DF.parse("2014/06/24").getTime()); Date resultDate = new Date(DF.parse("2014/06/30").getTime()); assertEquals(resultDate, SpliceDateFunctions.NEXT_DAY(startDate, "MoNdAy")); } @Test public void nextDayThrowsWhenPassedInvalidDay() throws SQLException { try{ SpliceDateFunctions.NEXT_DAY(new Date(1L),"not-a-week-day"); }catch(SQLException se){ Assert.assertEquals("Invalid sql state!",ErrorState.LANG_INVALID_DAY.getSqlState(),se.getSQLState()); Assert.assertTrue("Did not contain the proper week day message!",se.getMessage().contains("not-a-week-day")); } } @Test public void nextDayReturnsPassedDateWhenGivenNullDay() throws SQLException { Date source = new Date(1L); assertSame(source, SpliceDateFunctions.NEXT_DAY(source, null)); }
SpliceDateFunctions { public static double MONTH_BETWEEN(Date source1, Date source2) { if (source1 == null || source2 == null) return -1; DateTime dt1 = new DateTime(source1); DateTime dt2 = new DateTime(source2); return Months.monthsBetween(dt1, dt2).getMonths(); } static Date ADD_MONTHS(Date source, Integer numOfMonths); static Date ADD_DAYS(Date source, Integer numOfDays); static Date ADD_YEARS(Date source, Integer numOfYears); static Timestamp TO_TIMESTAMP(String source); static Timestamp TO_TIMESTAMP(String source, String format, SpliceDateTimeFormatter formatter); static Timestamp TO_TIMESTAMP(String source, String format); static Timestamp TO_TIMESTAMP(String source, String format, ZoneId zoneId); static Time TO_TIME(String source); static Time TO_TIME(String source, String format); static Time TO_TIME(String source, String format, ZoneId zoneId); static Time TO_TIME(String source, String format, SpliceDateTimeFormatter formatter); static Date TO_DATE(String source); static Date TO_DATE(String source, String format); static Date TO_DATE(String source, String format, ZoneId zoneId); static Date TO_DATE(String source, String format, SpliceDateTimeFormatter formatter); static Date stringWithFormatToDate(String source, SpliceDateTimeFormatter formatter); static Date LAST_DAY(Date source); static Date NEXT_DAY(Date source, String weekday); static double MONTH_BETWEEN(Date source1, Date source2); static String TO_CHAR(Date source, String format); static String TIMESTAMP_TO_CHAR(Timestamp stamp, String output); static Timestamp TRUNC_DATE(Timestamp source, String field); }
@Test public void monthBetween() { Calendar c = Calendar.getInstance(); Date t = new Date(c.getTime().getTime()); c.add(Calendar.MONTH, 3); Date s = new Date(c.getTime().getTime()); assertEquals(3.0, SpliceDateFunctions.MONTH_BETWEEN(t, s), 0.001); }
SpliceDateFunctions { public static Date TO_DATE(String source) throws SQLException { return TO_DATE(source,null); } static Date ADD_MONTHS(Date source, Integer numOfMonths); static Date ADD_DAYS(Date source, Integer numOfDays); static Date ADD_YEARS(Date source, Integer numOfYears); static Timestamp TO_TIMESTAMP(String source); static Timestamp TO_TIMESTAMP(String source, String format, SpliceDateTimeFormatter formatter); static Timestamp TO_TIMESTAMP(String source, String format); static Timestamp TO_TIMESTAMP(String source, String format, ZoneId zoneId); static Time TO_TIME(String source); static Time TO_TIME(String source, String format); static Time TO_TIME(String source, String format, ZoneId zoneId); static Time TO_TIME(String source, String format, SpliceDateTimeFormatter formatter); static Date TO_DATE(String source); static Date TO_DATE(String source, String format); static Date TO_DATE(String source, String format, ZoneId zoneId); static Date TO_DATE(String source, String format, SpliceDateTimeFormatter formatter); static Date stringWithFormatToDate(String source, SpliceDateTimeFormatter formatter); static Date LAST_DAY(Date source); static Date NEXT_DAY(Date source, String weekday); static double MONTH_BETWEEN(Date source1, Date source2); static String TO_CHAR(Date source, String format); static String TIMESTAMP_TO_CHAR(Timestamp stamp, String output); static Timestamp TRUNC_DATE(Timestamp source, String field); }
@Test public void toDate() throws SQLException, ParseException { String format = "yyyy/MM/dd"; String source = "2014/06/24"; DateFormat formatter = new SimpleDateFormat(format); Date date = new Date(formatter.parse(source).getTime()); assertEquals(date, SpliceDateFunctions.TO_DATE(source, format)); } @Test public void toDate_throwsOnInvalidDateFormat() throws SQLException, ParseException { expectedException.expect(SQLException.class); SpliceDateFunctions.TO_DATE("bad-format", "yyyy/MM/dd"); } @Test public void toDateDefaultPattern() throws Exception { String source = "2014-06-24"; DateFormat formatter = new SimpleDateFormat("MM/dd/yy"); Date date = new Date(formatter.parse("06/24/2014").getTime()); assertEquals(date, SpliceDateFunctions.TO_DATE(source)); } @Test public void toDateWithTimezoneTransitionAtMidnight() throws Exception { String source = "1908-04-01"; DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(formatter.parse("1908-04-01").getTime()); try { assertEquals(date, SpliceDateFunctions.TO_DATE(source, "yyyy-MM-dd", ZoneId.of("Asia/Seoul"))); } catch (SQLException e) { fail("Failed to parse date with timezone transition at midnight."); } } @Test public void toDateDefaultWrongPattern() throws Exception { String source = "2014/06/24"; DateFormat formatter = new SimpleDateFormat("MM/dd/yy"); Date date = new Date(formatter.parse("06/24/2014").getTime()); try { assertEquals(date, SpliceDateFunctions.TO_DATE(source)); fail("Expected to get an exception for parsing the wrong date pattern."); } catch (SQLException e) { assertEquals("Error parsing datetime 2014/06/24 with pattern: yyyy-MM-dd. Try using an ISO8601 pattern such as, yyyy-MM-dd'T'HH:mm:ss.SSSZZ, yyyy-MM-dd'T'HH:mm:ssZ or yyyy-MM-dd", e.getLocalizedMessage()); } }
SpliceDateFunctions { public static Timestamp TO_TIMESTAMP(String source) throws SQLException { return TO_TIMESTAMP(source,null); } static Date ADD_MONTHS(Date source, Integer numOfMonths); static Date ADD_DAYS(Date source, Integer numOfDays); static Date ADD_YEARS(Date source, Integer numOfYears); static Timestamp TO_TIMESTAMP(String source); static Timestamp TO_TIMESTAMP(String source, String format, SpliceDateTimeFormatter formatter); static Timestamp TO_TIMESTAMP(String source, String format); static Timestamp TO_TIMESTAMP(String source, String format, ZoneId zoneId); static Time TO_TIME(String source); static Time TO_TIME(String source, String format); static Time TO_TIME(String source, String format, ZoneId zoneId); static Time TO_TIME(String source, String format, SpliceDateTimeFormatter formatter); static Date TO_DATE(String source); static Date TO_DATE(String source, String format); static Date TO_DATE(String source, String format, ZoneId zoneId); static Date TO_DATE(String source, String format, SpliceDateTimeFormatter formatter); static Date stringWithFormatToDate(String source, SpliceDateTimeFormatter formatter); static Date LAST_DAY(Date source); static Date NEXT_DAY(Date source, String weekday); static double MONTH_BETWEEN(Date source1, Date source2); static String TO_CHAR(Date source, String format); static String TIMESTAMP_TO_CHAR(Timestamp stamp, String output); static Timestamp TRUNC_DATE(Timestamp source, String field); }
@Test public void toTimestamp() throws SQLException, ParseException { String format = "yyyy/MM/dd HH:mm:ss.SSS"; String source = "2014/06/24 12:13:14.123"; DateFormat formatter = new SimpleDateFormat("MM/dd/yy HH:mm:ss.SSS"); Timestamp date = new Timestamp(formatter.parse("06/24/2014 12:13:14.123").getTime()); assertEquals(date, SpliceDateFunctions.TO_TIMESTAMP(source, format)); } @Test public void toTimestamp_throwsOnInvalidDateFormat() throws SQLException, ParseException { expectedException.expect(SQLException.class); SpliceDateFunctions.TO_TIMESTAMP("bad-format", "yyyy/MM/dd HH:mm:ss.SSS"); } @Test public void toTimestampDefaultPattern() throws Exception { String source = "2014-06-24T12:13:14.123"; DateFormat formatter = new SimpleDateFormat("MM/dd/yy HH:mm:ss.SSS"); Timestamp date = new Timestamp(formatter.parse("06/24/2014 12:13:14.123").getTime()); assertEquals(date, SpliceDateFunctions.TO_TIMESTAMP(source)); } @Test public void toTimestampISO8601Pattern() throws Exception { String format = "yyyy-MM-dd'T'HH:mm:ssz"; String source = "2011-09-17T23:40:53EDT"; DateFormat formatter = new SimpleDateFormat(format); Timestamp date = new Timestamp(formatter.parse(source).getTime()); assertEquals(date, SpliceDateFunctions.TO_TIMESTAMP(source, format)); } @Test public void toTimestampISO8601Pattern2() throws Exception { String format = "yyyy-MM-dd'T'HH:mm:ssz"; String source = "2011-09-17T23:40:53GMT"; DateFormat formatter = new SimpleDateFormat(format); Timestamp date = new Timestamp(formatter.parse(source).getTime()); assertEquals(date, SpliceDateFunctions.TO_TIMESTAMP(source, format)); } @Test public void toTimestampDefaultWrongPattern() throws Exception { String source = "2014-06-24 12:13:14.123"; DateFormat formatter = new SimpleDateFormat("MM/dd/yy HH:mm:ss.SSS"); Timestamp date = new Timestamp(formatter.parse("06/24/2014 12:13:14.123").getTime()); try { assertEquals(date, SpliceDateFunctions.TO_TIMESTAMP(source)); } catch (SQLException e) { fail("No exception expected. Date is using the default timestamp format pattern."); } } @Test public void testLargeTimestamps() throws Exception { assertEquals("2013-11-26 23:28:55.22", SpliceDateFunctions.TO_TIMESTAMP("2013-11-26 23:28:55.22","yyyy-MM-dd HH:mm:ss.SSSSSS").toString()); assertEquals("2014-03-08 20:33:27.135", SpliceDateFunctions.TO_TIMESTAMP("2014-03-08 20:33:27.135","yyyy-MM-dd HH:mm:ss.SSSSSS").toString()); assertEquals("2013-11-26 23:28:55.386", SpliceDateFunctions.TO_TIMESTAMP("2013-11-26 23:28:55.386","yyyy-MM-dd HH:mm:ss.SSSSSS").toString()); assertEquals("2014-03-08 20:33:27.135", SpliceDateFunctions.TO_TIMESTAMP("2014-03-08 20:33:27.135","yyyy-MM-dd HH:mm:ss.SSSSSS").toString()); assertEquals("2014-03-08 20:33:40.287469", SpliceDateFunctions.TO_TIMESTAMP("2014-03-08 20:33:40.287469","yyyy-MM-dd HH:mm:ss.SSSSSS").toString()); assertEquals("2015-12-12 11:11:12.123456", SpliceDateFunctions.TO_TIMESTAMP("2015-12-12 11:11:12.123456","yyyy-MM-dd HH:mm:ss.SSSSSS").toString()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ"); sdf.setTimeZone(TimeZone.getTimeZone("PST")); assertEquals("2013-03-23 19:45:00.987-0700", sdf.format(SpliceDateFunctions.TO_TIMESTAMP("2013-03-23 19:45:00.987-07", "yyyy-MM-dd HH:mm:ss.SSSZ"))); } @Test public void testSupportMultipleTimestampFormats() throws Exception { Timestamp ts = SpliceDateFunctions.TO_TIMESTAMP("2013-03-23 19:45:00.987654-05","yyyy-MM-dd HH:mm:ss.SSSSSSZ"); ZonedDateTime zdt = java.time.ZonedDateTime.parse("2013-03-24T00:45:00.987654Z"); Timestamp expectedTS = getTimestamp(zdt); assertTrue(String.format("Unexpected timestamp value. Expected: %s, Actual: %s", expectedTS, ts), expectedTS.equals(ts)); ts = SpliceDateFunctions.TO_TIMESTAMP("2013-03-23 19:45:00.987654-02","yyyy-MM-dd HH:mm:ss.SSSSSSZ"); zdt = java.time.ZonedDateTime.parse("2013-03-23T21:45:00.987654Z"); expectedTS = getTimestamp(zdt); assertTrue(String.format("Unexpected timestamp value. Expected: %s, Actual: %s", expectedTS, ts), expectedTS.equals(ts)); } @Test @Ignore("DB-5033") public void test_IBM_SAP_timestampFormats() throws Exception { assertEquals("2013-03-23 19:45:00.987654", SpliceDateFunctions.TO_TIMESTAMP("2013-03-23-19:45:00.987654","YYYY-MM-DD-HH.MM.SS.NNNNNN").toString()); assertEquals("2013-03-23 19:45:00.987654", SpliceDateFunctions.TO_TIMESTAMP("20130323194500987654","YYYYMMDDHHMMSSNNNNNN").toString()); assertEquals("2013-03-23 19:45:00.987654", SpliceDateFunctions.TO_TIMESTAMP("130323194500987654","YYMMDDHHMMSSNNNNNN").toString()); }
FormatableBitSet implements Formatable, Cloneable { public final boolean isSet(int position) { checkPosition(position); final int byteIndex = udiv8(position); final byte bitIndex = umod8(position); return ((value[byteIndex] & (0x80>>bitIndex)) != 0); } FormatableBitSet(); FormatableBitSet(int numBits); FormatableBitSet(byte[] newValue); FormatableBitSet(FormatableBitSet original); Object clone(); boolean invariantHolds(); int getLengthInBytes(); int getLength(); int size(); byte[] getByteArray(); void grow(int n); void shrink(int n); boolean equals(Object other); int compare(FormatableBitSet other); int hashCode(); final boolean isSet(int position); final boolean get(int position); void set(int position); void clear(int position); void clear(); String toString(); static int maxBitsForSpace(int numBytes); int anySetBit(); int anySetBit(int beyondBit); void or(FormatableBitSet otherBit); void and(FormatableBitSet otherBit); void xor(FormatableBitSet otherBit); int getNumBitsSet(); void writeExternal(ObjectOutput out); void readExternal(ObjectInput in); int getTypeFormatId(); }
@Test public void testIsSetEmpty() { try { empty.isSet(-8); fail(); } catch (IllegalArgumentException ignored) { } try { empty.isSet(-1); fail(); } catch (IllegalArgumentException ignored) { } try { empty.isSet(0); fail(); } catch (IllegalArgumentException ignored) { } } @Test public void testIsSet() { try { bitset18C.isSet(-8); fail(); } catch (IllegalArgumentException ignored) { } try { bitset18C.isSet(-1); fail(); } catch (IllegalArgumentException ignored) { } assertFalse(bitset18C.isSet(0)); assertFalse(bitset18C.isSet(1)); assertTrue(bitset18C.isSet(2)); assertTrue(bitset18C.isSet(3)); assertFalse(bitset18C.isSet(4)); assertFalse(bitset18C.isSet(5)); assertFalse(bitset18C.isSet(6)); assertTrue(bitset18C.isSet(7)); assertTrue(bitset18C.isSet(8)); assertTrue(bitset18C.isSet(9)); assertFalse(bitset18C.isSet(10)); assertFalse(bitset18C.isSet(11)); assertFalse(bitset18C.isSet(12)); assertFalse(bitset18C.isSet(13)); assertTrue(bitset18C.isSet(14)); assertTrue(bitset18C.isSet(15)); assertTrue(bitset18C.isSet(16)); assertTrue(bitset18C.isSet(17)); try { bitset18C.isSet(18); fail(); } catch (IllegalArgumentException ignored) { } }
SpliceDateFunctions { public static Timestamp TRUNC_DATE(Timestamp source, String field) throws SQLException { if (source == null || field == null) return null; DateTime dt = new DateTime(source); field = field.toLowerCase(); String lowerCaseField = field.toLowerCase(); if ("microseconds".equals(lowerCaseField)) { int nanos = source.getNanos(); nanos = nanos - nanos % 1000; source.setNanos(nanos); return source; } else if ("milliseconds".equals(lowerCaseField)) { int nanos = source.getNanos(); nanos = nanos - nanos % 1000000; source.setNanos(nanos); return source; } else if ("second".equals(lowerCaseField)) { source.setNanos(0); return source; } else if ("minute".equals(lowerCaseField)) { DateTime modified = dt.minusSeconds(dt.getSecondOfMinute()); Timestamp ret = new Timestamp(modified.getMillis()); ret.setNanos(0); return ret; } else if ("hour".equals(lowerCaseField)) { DateTime modified = dt.minusMinutes(dt.getMinuteOfHour()) .minusSeconds(dt.getSecondOfMinute()); Timestamp ret = new Timestamp(modified.getMillis()); ret.setNanos(0); return ret; } else if ("day".equals(lowerCaseField)) { DateTime modified = dt.minusHours(dt.getHourOfDay()) .minusMinutes(dt.getMinuteOfHour()) .minusSeconds(dt.getSecondOfMinute()); Timestamp ret = new Timestamp(modified.getMillis()); ret.setNanos(0); return ret; } else if ("week".equals(lowerCaseField)) { DateTime modified = dt.minusDays(dt.getDayOfWeek()) .minusHours(dt.getHourOfDay()) .minusMinutes(dt.getMinuteOfHour()) .minusSeconds(dt.getSecondOfMinute()); Timestamp ret = new Timestamp(modified.getMillis()); ret.setNanos(0); return ret; } else if ("month".equals(lowerCaseField)) { DateTime modified = dt.minusDays(dt.get(DateTimeFieldType.dayOfMonth()) - 1) .minusHours(dt.getHourOfDay()) .minusMinutes(dt.getMinuteOfHour()) .minusSeconds(dt.getSecondOfMinute()); Timestamp ret = new Timestamp(modified.getMillis()); ret.setNanos(0); return ret; } else if ("quarter".equals(lowerCaseField)) { int month = dt.getMonthOfYear(); DateTime modified = dt; if ((month + 1) % 3 == 1) { modified = dt.minusMonths(2); } else if ((month + 1) % 3 == 0) { modified = dt.minusMonths(1); } DateTime fin = modified.minusDays(dt.get(DateTimeFieldType.dayOfMonth()) - 1) .minusHours(dt.getHourOfDay()) .minusMinutes(dt.getMinuteOfHour()) .minusSeconds(dt.getSecondOfMinute()); Timestamp ret = new Timestamp(fin.getMillis()); ret.setNanos(0); return ret; } else if ("year".equals(lowerCaseField)) { DateTime modified = dt.minusDays(dt.get(DateTimeFieldType.dayOfMonth()) - 1) .minusHours(dt.getHourOfDay()) .minusMonths(dt.getMonthOfYear() - 1) .minusMinutes(dt.getMinuteOfHour()) .minusSeconds(dt.getSecondOfMinute()); Timestamp ret = new Timestamp(modified.getMillis()); ret.setNanos(0); return ret; } else if ("decade".equals(lowerCaseField)) { DateTime modified = dt.minusDays(dt.get(DateTimeFieldType.dayOfMonth()) - 1) .minusYears(dt.getYear() % 10) .minusHours(dt.getHourOfDay()) .minusMonths(dt.getMonthOfYear() - 1) .minusMinutes(dt.getMinuteOfHour()) .minusSeconds(dt.getSecondOfMinute()); Timestamp ret = new Timestamp(modified.getMillis()); ret.setNanos(0); return ret; } else if ("century".equals(lowerCaseField)) { DateTime modified = dt.minusDays(dt.get(DateTimeFieldType.dayOfMonth()) - 1) .minusHours(dt.getHourOfDay()) .minusYears(dt.getYear() % 100) .minusMonths(dt.getMonthOfYear() - 1) .minusMinutes(dt.getMinuteOfHour()) .minusSeconds(dt.getSecondOfMinute()); Timestamp ret = new Timestamp(modified.getMillis()); ret.setNanos(0); return ret; } else if ("millennium".equals(lowerCaseField)) { int newYear = dt.getYear() - dt.getYear() % 1000; return new Timestamp(newYear - 1900, Calendar.JANUARY, 1, 0, 0, 0, 0); } else { throw new SQLException(String.format("invalid time unit '%s'", field)); } } static Date ADD_MONTHS(Date source, Integer numOfMonths); static Date ADD_DAYS(Date source, Integer numOfDays); static Date ADD_YEARS(Date source, Integer numOfYears); static Timestamp TO_TIMESTAMP(String source); static Timestamp TO_TIMESTAMP(String source, String format, SpliceDateTimeFormatter formatter); static Timestamp TO_TIMESTAMP(String source, String format); static Timestamp TO_TIMESTAMP(String source, String format, ZoneId zoneId); static Time TO_TIME(String source); static Time TO_TIME(String source, String format); static Time TO_TIME(String source, String format, ZoneId zoneId); static Time TO_TIME(String source, String format, SpliceDateTimeFormatter formatter); static Date TO_DATE(String source); static Date TO_DATE(String source, String format); static Date TO_DATE(String source, String format, ZoneId zoneId); static Date TO_DATE(String source, String format, SpliceDateTimeFormatter formatter); static Date stringWithFormatToDate(String source, SpliceDateTimeFormatter formatter); static Date LAST_DAY(Date source); static Date NEXT_DAY(Date source, String weekday); static double MONTH_BETWEEN(Date source1, Date source2); static String TO_CHAR(Date source, String format); static String TIMESTAMP_TO_CHAR(Timestamp stamp, String output); static Timestamp TRUNC_DATE(Timestamp source, String field); }
@Test public void truncDate() throws ParseException, SQLException { assertEquals(timeStampT("2014/07/15 12:12:12.234"), TRUNC_DATE(timeStampT("2014/07/15 12:12:12.234"), "microseconds")); assertEquals(timeStampT("2014/07/15 12:12:12.234"), TRUNC_DATE(timeStampT("2014/07/15 12:12:12.234"), "milliseconds")); assertEquals(timeStampT("2014/07/15 12:12:12.0"), TRUNC_DATE(timeStampT("2014/07/15 12:12:12.234"), "second")); assertEquals(timeStampT("2014/07/15 12:12:00.0"), TRUNC_DATE(timeStampT("2014/07/15 12:12:12.234"), "minute")); assertEquals(timeStampT("2014/07/15 12:00:00.0"), TRUNC_DATE(timeStampT("2014/07/15 12:12:12.234"), "hour")); assertEquals(timeStampT("2014/06/01 00:00:00.000"), TRUNC_DATE(timeStampT("2014/06/24 12:13:14.123"), "month")); assertEquals(timeStampT("2014/06/22 00:00:00.000"), TRUNC_DATE(timeStampT("2014/06/24 12:13:14.123"), "week")); assertEquals(timeStampT("2014/04/01 00:00:00.000"), TRUNC_DATE(timeStampT("2014/06/24 12:13:14.123"), "quarter")); assertEquals(timeStampT("2014/01/01 00:00:00.000"), TRUNC_DATE(timeStampT("2014/06/24 12:13:14.123"), "year")); assertEquals(timeStampT("2010/01/01 00:00:00.000"), TRUNC_DATE(timeStampT("2014/06/24 12:13:14.123"), "decade")); assertEquals(timeStampT("2000/01/01 00:00:00.000"), TRUNC_DATE(timeStampT("2014/06/24 12:13:14.123"), "century")); } @Test public void truncDate_Millennium() throws ParseException, SQLException { assertEquals(timeStampT("0000/01/01 00:00:00.000"), TRUNC_DATE(timeStampT("955/12/31 12:13:14.123"), "millennium")); assertEquals(timeStampT("1000/01/01 00:00:00.000"), TRUNC_DATE(timeStampT("1955/12/31 12:13:14.123"), "millennium")); assertEquals(timeStampT("2000/01/01 00:00:00.000"), TRUNC_DATE(timeStampT("2000/01/01 12:13:14.123"), "millennium")); assertEquals(timeStampT("2000/01/01 00:00:00.000"), TRUNC_DATE(timeStampT("2999/12/31 12:13:14.123"), "millennium")); assertEquals(timeStampT("3000/01/01 00:00:00.000"), TRUNC_DATE(timeStampT("3501/06/24 12:13:14.123"), "millennium")); assertEquals(timeStampT("3000/01/01 00:00:00.000"), TRUNC_DATE(timeStampT("3301/06/24 12:13:14.123"), "millennium")); } @Test public void truncDate_returnsNullIfSourceOrDateOrBothAreNull() throws ParseException, SQLException { assertNull(TRUNC_DATE(timeStampT("2014/07/15 12:12:12.234"), null)); assertNull(TRUNC_DATE(null, "month")); assertNull(TRUNC_DATE(null, null)); } @Test public void truncDate_throwsOnInvalidTimeFieldArg() throws ParseException, SQLException { expectedException.expect(SQLException.class); assertNull(TRUNC_DATE(timeStampT("2014/07/15 12:12:12.234"), "not-a-time-field")); } @Test public void truncDate_isNotCaseSensitive() throws ParseException, SQLException { assertEquals(timeStampT("2014/07/15 12:00:00.0"), TRUNC_DATE(timeStampT("2014/07/15 12:12:12.234"), "hOuR")); }
DDLWatchRefresher { public boolean refreshDDL(Set<DDLWatcher.DDLListener> callbacks) throws IOException{ Collection<String> ongoingDDLChangeIds=watchChecker.getCurrentChangeIds(); if(ongoingDDLChangeIds==null) return false; Set<Pair<DDLChange,String>> newChanges=new HashSet<>(); boolean currentWasEmpty=currentDDLChanges.isEmpty(); try{ clearFinishedChanges(ongoingDDLChangeIds,callbacks); }catch(StandardException se){ throw exceptionFactory.asIOException(se); } for(String changeId : ongoingDDLChangeIds){ if(!seenDDLChanges.contains(changeId)){ DDLChange change=watchChecker.getChange(changeId); if(change==null)continue; String cId=change.getChangeId(); changeTimeouts.add(cId); SpliceLogUtils.info(LOG,"New change with id=%s, and change=%s",changeId,change); try { processPreCommitChange(change, callbacks); seenDDLChanges.add(changeId); newChanges.add(new Pair<DDLChange, String>(change,null)); } catch (Exception e) { LOG.error("Encountered an exception processing DDL change",e); newChanges.add(new Pair<>(change,e.getLocalizedMessage())); } } } watchChecker.notifyProcessed(newChanges); int killed = killTimeouts(callbacks); if(currentWasEmpty!=currentDDLChanges.isEmpty()){ boolean case1=!currentDDLChanges.isEmpty(); for(DDLWatcher.DDLListener listener : callbacks){ if(case1){ listener.startGlobalChange(); }else listener.finishGlobalChange(); } }else if(killed>0){ for(DDLWatcher.DDLListener listener : callbacks){ listener.finishGlobalChange(); } } return true; } DDLWatchRefresher(DDLWatchChecker watchChecker, TransactionReadController txnController, SqlExceptionFactory exceptionFactory, TxnSupplier txnSupplier); Collection<DDLChange> tentativeDDLChanges(); int numCurrentDDLChanges(); boolean refreshDDL(Set<DDLWatcher.DDLListener> callbacks); boolean canUseSPSCache(TransactionManager txnMgr); boolean canWriteCache(TransactionManager xact_mgr); boolean canReadCache(TransactionManager xact_mgr); boolean cacheIsValid(); }
@Test public void picksUpNonTentativeChange() throws Exception{ TestChecker checker=getTestChecker(); Clock clock = new IncrementingClock(0); TxnStore supplier = new TestingTxnStore(clock,new TestingTimestampSource(),null,100l); supplier.recordNewTransaction(txn); TestDDLWatchRefresher refresher = new TestDDLWatchRefresher(checker,null,ef,supplier); refresher.setTimeout(false); final DDLChange testChange = ProtoUtil.createNoOpDDLChange(txn.getTxnId(),"change",DDLMessage.DDLChangeType.CHANGE_PK); checker.addChange(testChange); CountingListener assertionListener = new CountingListener(); boolean shouldCont=refresher.refreshDDL(Collections.<DDLWatcher.DDLListener>singleton(assertionListener)); Assert.assertTrue("Returned an error State!",shouldCont); Assert.assertEquals("Incorrect initiated count!",1,assertionListener.getCount(testChange)); } @Test public void allPostCommitAreTreatedAsSuch() throws Exception{ TestChecker checker=getTestChecker(); Clock clock = new IncrementingClock(0); TxnStore supplier = new TestingTxnStore(clock,new TestingTimestampSource(),null,100l); supplier.recordNewTransaction(txn); SITransactionReadController txnController=new SITransactionReadController(supplier); TestDDLWatchRefresher refresher = new TestDDLWatchRefresher(checker,txnController,ef,supplier); refresher.setTimeout(false); CountingListener assertionListener = new CountingListener(); for(DDLChangeType type:DDLChangeType.values()){ if(type.isPreCommit()) continue; final DDLChange testChange = ProtoUtil.createNoOpDDLChange(txn.getTxnId(),type.toString(),DDLMessage.DDLChangeType.CREATE_SCHEMA); checker.addChange(testChange); boolean shouldCont=refresher.refreshDDL(Collections.<DDLWatcher.DDLListener>singleton(assertionListener)); Assert.assertTrue("Returned an error State!",shouldCont); Assert.assertEquals("Incorrect initiated count for changeType "+type+"!",1,assertionListener.getCount(testChange)); Assert.assertEquals("Incorrect global start count!",0,assertionListener.getStartGlobalCount()); Assert.assertEquals("Incorrect global stop count!",0,assertionListener.getEndGlobalCount()); } } @Test public void removesFinishedChange() throws Exception{ TestChecker checker=getTestChecker(); Clock clock = new IncrementingClock(0); TxnStore supplier = new TestingTxnStore(clock,new TestingTimestampSource(),null,100l); supplier.recordNewTransaction(txn); SITransactionReadController txnController=new SITransactionReadController(supplier); TestDDLWatchRefresher refresher = new TestDDLWatchRefresher(checker,txnController,ef,supplier); refresher.setTimeout(true); DDLChange testChange = ProtoUtil.createNoOpDDLChange(txn.getTxnId(),"change",DDLMessage.DDLChangeType.CHANGE_PK ); checker.addChange(testChange); CountingListener assertionListener = new CountingListener(); boolean shouldCont=refresher.refreshDDL(Collections.<DDLWatcher.DDLListener>singleton(assertionListener)); Assert.assertTrue("Returned an error State!",shouldCont); Assert.assertEquals("Incorrect initiated count!",1,assertionListener.getCount(testChange)); shouldCont = refresher.refreshDDL(Collections.<DDLWatcher.DDLListener>singleton(assertionListener)); Assert.assertTrue("Returned an error State!",shouldCont); Assert.assertEquals("Incorrect initiated count!",0,assertionListener.getCount(testChange)); } @Test public void testDDLTimesOut() throws Exception{ TestChecker checker=getTestChecker(); TickingClock clock = new IncrementingClock(0); TxnStore supplier = new TestingTxnStore(clock,new TestingTimestampSource(),null,100l); supplier.recordNewTransaction(txn); long timeoutMs=10l; TestDDLWatchRefresher refresher = new TestDDLWatchRefresher(checker,null,ef,supplier); refresher.setTimeout(false); final DDLChange testChange = ProtoUtil.createNoOpDDLChange(txn.getTxnId(),"change",DDLMessage.DDLChangeType.ADD_PRIMARY_KEY ); CountingListener assertionListener = new CountingListener(); checker.addChange(testChange); boolean shouldCont=refresher.refreshDDL(Collections.<DDLWatcher.DDLListener>singleton(assertionListener)); Assert.assertTrue("Returned an error State!",shouldCont); Assert.assertEquals("Incorrect initiated count!",1,assertionListener.getCount(testChange)); clock.tickMillis(5l); checker.addChange(testChange); shouldCont=refresher.refreshDDL(Collections.<DDLWatcher.DDLListener>singleton(assertionListener)); Assert.assertTrue("Returned an error State!",shouldCont); Assert.assertEquals("Incorrect initiated count!",1,assertionListener.getCount(testChange)); clock.tickMillis(10); refresher.setTimeout(true); shouldCont=refresher.refreshDDL(Collections.<DDLWatcher.DDLListener>singleton(assertionListener)); Assert.assertTrue("Returned an error State!",shouldCont); Assert.assertEquals("Incorrect initiated count!",1,assertionListener.getCount(testChange)); Assert.assertTrue("Incorrect failed count!",assertionListener.isFailed(testChange)); }
AsynchronousDDLController implements DDLController, CommunicationListener { @Override public String notifyMetadataChange(DDLChange change) throws StandardException { String changeId = communicator.createChangeNode(change); long availableTime =maximumWaitTime; long elapsedTime = 0; Collection<String> finishedServers =Collections.emptyList(); Collection<String> activeServers = Collections.emptyList(); while (availableTime>0) { activeServers = this.activeServers.getActiveServers(); finishedServers = communicator.completedListeners(changeId,this); if (finishedServers.containsAll(activeServers)) { return changeId; } for (String finishedServer: finishedServers) { if (finishedServer.startsWith(DDLConfiguration.ERROR_TAG)) { String errorMessage = communicator.getErrorMessage(changeId,finishedServer); throw StandardException.plainWrapException(new IOException(errorMessage)); } } long startTimestamp = clock.currentTimeMillis(); notificationLock.lock(); try { notificationSignal.await(refreshInterval,TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw Exceptions.parseException(e); }finally{ notificationLock.unlock(); } long stopTimestamp = clock.currentTimeMillis(); availableTime-= (stopTimestamp -startTimestamp); elapsedTime+=(stopTimestamp-startTimestamp); } logMissingServers(activeServers,finishedServers); communicator.deleteChangeNode(changeId); throw ErrorState.DDL_TIMEOUT.newException(elapsedTime,maximumWaitTime); } AsynchronousDDLController(DDLCommunicator communicator, LockFactory lockFactory, Clock clock, long refreshInterval, long maximumWaitTime); AsynchronousDDLController(DDLCommunicator communicator, LockFactory lockFactory, Clock clock, SConfiguration configuration); @Override String notifyMetadataChange(DDLChange change); @Override void finishMetadataChange(String changeId); @Override void onCommunicationEvent(String node); }
@Test(expected=StandardException.class) public void timesOutIfServerRespondsAfterTimeout() throws Exception{ final List<String> servers = Arrays.asList("server1","server2"); final String changeId = "change"; final TickingClock clock = new IncrementingClock(0); final long timeout = 10l; final TestDDLCommunicator ddlCommunicator = new TestDDLCommunicator(servers){ @Override public String createChangeNode(DDLChange change) throws StandardException{ return changeId; } }; final TestCondition condition = new TestCondition(clock){ @Override protected void waitUninterruptibly(){ clock.tickMillis(timeout); for(String server:servers){ ddlCommunicator.serverCompleted(changeId,server); } } }; final TestLock lock = new TestLock(clock){ @Override protected void blockUninterruptibly(){ } @Override public boolean tryLock(){ return true; } @Override public Condition newCondition(){ return condition; } }; LockFactory lf = new SingleInstanceLockFactory(lock); AsynchronousDDLController controller=new AsynchronousDDLController(ddlCommunicator,lf,clock,config); TxnView txn = new WritableTxn(1l,1l,null,Txn.IsolationLevel.SNAPSHOT_ISOLATION,Txn.ROOT_TRANSACTION,null,false,null); DDLChange change = ProtoUtil.createNoOpDDLChange(txn.getTxnId(),"testChange",DDLMessage.DDLChangeType.CREATE_INDEX); try{ controller.notifyMetadataChange(change); Assert.fail("The coordination did not time out!"); }catch(StandardException se){ Assert.assertEquals("Incorrect error code!","SE017",se.getSQLState()); throw se; } } @Test(expected=StandardException.class) public void timesOutIfNoServerEverResponds() throws Exception{ final List<String> servers = Arrays.asList("server1","server2"); final String changeId = "change"; final TickingClock clock = new IncrementingClock(0); final long timeout = 10l; final TestDDLCommunicator ddlCommunicator = new TestDDLCommunicator(servers){ @Override public String createChangeNode(DDLChange change) throws StandardException{ return changeId; } }; final TestCondition condition = new TestCondition(clock){ @Override protected void waitUninterruptibly(){ clock.tickMillis(timeout); } }; final TestLock lock = new TestLock(clock){ @Override protected void blockUninterruptibly(){ } @Override public boolean tryLock(){ return true; } @Override public Condition newCondition(){ return condition; } }; LockFactory lf = new SingleInstanceLockFactory(lock); AsynchronousDDLController controller=new AsynchronousDDLController(ddlCommunicator,lf,clock,config); TxnView txn = new WritableTxn(1l,1l,null,Txn.IsolationLevel.SNAPSHOT_ISOLATION,Txn.ROOT_TRANSACTION,null,false,null); DDLChange change = ProtoUtil.createNoOpDDLChange(txn.getTxnId(),"testChange",DDLMessage.DDLChangeType.CHANGE_PK ); try{ controller.notifyMetadataChange(change); Assert.fail("The coordination did not time out!"); }catch(StandardException se){ Assert.assertEquals("Incorrect error code!","SE017",se.getSQLState()); throw se; } } @Test public void correctlyIgnoresRemovedServers() throws Exception{ final List<String> servers = Arrays.asList("server1","server2"); final String changeId = "change"; final TickingClock clock = new IncrementingClock(0); final long timeout = 10l; final TestDDLCommunicator ddlCommunicator = new TestDDLCommunicator(servers){ @Override public String createChangeNode(DDLChange change) throws StandardException{ return changeId; } }; final TestCondition condition = new TestCondition(clock){ int state = 0; @Override protected void waitUninterruptibly(){ switch(state){ case 0: ddlCommunicator.serverCompleted(changeId,servers.get(0)); break; case 1: ddlCommunicator.decommissionServer("server2"); break; default: Assert.fail("Unexpected call to wait()"); } clock.tickMillis(timeout/5); state++; } }; final TestLock lock = new TestLock(clock){ @Override protected void blockUninterruptibly(){ } @Override public boolean tryLock(){ return true; } @Override public Condition newCondition(){ return condition; } }; LockFactory lf = new SingleInstanceLockFactory(lock); AsynchronousDDLController controller=new AsynchronousDDLController(ddlCommunicator,lf,clock,10,100); TxnView txn = new WritableTxn(1l,1l,null,Txn.IsolationLevel.SNAPSHOT_ISOLATION,Txn.ROOT_TRANSACTION,null,false,null); DDLChange change = ProtoUtil.createNoOpDDLChange(txn.getTxnId(),"testChange",DDLMessage.DDLChangeType.ADD_COLUMN); String retChangeId=controller.notifyMetadataChange(change); Assert.assertEquals("Change id does not match!",changeId,retChangeId); Assert.assertTrue("Some servers are missing!",ddlCommunicator.completedServers.containsAll(ddlCommunicator.allServers)); } @Test public void correctlyCatchesNewServers() throws Exception{ final List<String> servers = Arrays.asList("server1","server2"); final String changeId = "change"; final TickingClock clock = new IncrementingClock(0); final long timeout = 10l; final TestDDLCommunicator ddlCommunicator = new TestDDLCommunicator(servers){ @Override public String createChangeNode(DDLChange change) throws StandardException{ return changeId; } }; final TestCondition condition = new TestCondition(clock){ int state = 0; @Override protected void waitUninterruptibly(){ switch(state){ case 0: ddlCommunicator.serverCompleted(changeId,servers.get(0)); break; case 1: ddlCommunicator.commissionServer("server3"); break; case 2: ddlCommunicator.serverCompleted(changeId,servers.get(1)); break; case 3: ddlCommunicator.serverCompleted(changeId,"server3"); break; default: Assert.fail("Unexpected call to wait()"); } clock.tickMillis(timeout/5); state++; } }; final TestLock lock = new TestLock(clock){ @Override protected void blockUninterruptibly(){ } @Override public boolean tryLock(){ return true; } @Override public Condition newCondition(){ return condition; } }; LockFactory lf = new SingleInstanceLockFactory(lock); AsynchronousDDLController controller=new AsynchronousDDLController(ddlCommunicator,lf,clock,10,100); TxnView txn = new WritableTxn(1l,1l,null,Txn.IsolationLevel.SNAPSHOT_ISOLATION,Txn.ROOT_TRANSACTION,null,false,null); DDLChange change = ProtoUtil.createNoOpDDLChange(txn.getTxnId(),"testChange",DDLMessage.DDLChangeType.ALTER_STATS); String retChangeId=controller.notifyMetadataChange(change); Assert.assertEquals("Change id does not match!",changeId,retChangeId); Assert.assertTrue("Some servers are missing!",ddlCommunicator.completedServers.containsAll(ddlCommunicator.allServers)); } @Test(expected=StandardException.class) public void timesOutIfOneServerNeverResponds() throws Exception{ final List<String> servers = Arrays.asList("server1","server2"); final String changeId = "change"; final TickingClock clock = new IncrementingClock(0); final long timeout = 10l; final TestDDLCommunicator ddlCommunicator = new TestDDLCommunicator(servers){ @Override public String createChangeNode(DDLChange change) throws StandardException{ return changeId; } }; final TestCondition condition = new TestCondition(clock){ int state = 0; @Override protected void waitUninterruptibly(){ switch(state){ case 0: ddlCommunicator.serverCompleted(changeId,servers.get(0)); break; case 1: clock.tickMillis(timeout); break; default: Assert.fail("wait() called after timing out"); } clock.tickMillis(timeout/3); state++; } }; final TestLock lock = new TestLock(clock){ @Override protected void blockUninterruptibly(){ } @Override public boolean tryLock(){ return true; } @Override public Condition newCondition(){ return condition; } }; LockFactory lf = new SingleInstanceLockFactory(lock); AsynchronousDDLController controller=new AsynchronousDDLController(ddlCommunicator,lf,clock,config); TxnView txn = new WritableTxn(1l,1l,null,Txn.IsolationLevel.SNAPSHOT_ISOLATION,Txn.ROOT_TRANSACTION,null,false,null); DDLChange change = ProtoUtil.createNoOpDDLChange(txn.getTxnId(),"testChange",DDLMessage.DDLChangeType.ADD_UNIQUE_CONSTRAINT ); try{ controller.notifyMetadataChange(change); Assert.fail("The coordination did not time out!"); }catch(StandardException se){ Assert.assertEquals("Incorrect error code!","SE017",se.getSQLState()); throw se; } } @Test public void noErrorWhenOneServerBecomesInactive() throws Exception{ final List<String> servers = Arrays.asList("server1","server2"); final String changeId = "change"; TickingClock clock = new IncrementingClock(0); final TestDDLCommunicator ddlCommunicator = new TestDDLCommunicator(servers){ @Override public String createChangeNode(DDLChange change) throws StandardException{ return changeId; } }; final TestCondition condition = new TestCondition(clock){ @Override protected void waitUninterruptibly(){ ddlCommunicator.serverCompleted(changeId,servers.get(0)); ddlCommunicator.decommissionServer(servers.get(1)); } }; final TestLock lock = new TestLock(clock){ @Override protected void blockUninterruptibly(){ } @Override public boolean tryLock(){ return true; } @Override public Condition newCondition(){ return condition; } }; LockFactory lf = new SingleInstanceLockFactory(lock); AsynchronousDDLController controller=new AsynchronousDDLController(ddlCommunicator,lf,clock,100,10); TxnView txn = new WritableTxn(1l,1l,null,Txn.IsolationLevel.SNAPSHOT_ISOLATION,Txn.ROOT_TRANSACTION,null,false,null); DDLChange change = ProtoUtil.createNoOpDDLChange(txn.getTxnId(),"testChange",DDLMessage.DDLChangeType.CREATE_SCHEMA ); String retChangeId=controller.notifyMetadataChange(change); Assert.assertEquals("Change id does not match!",changeId,retChangeId); Assert.assertTrue("Some servers are missing!",ddlCommunicator.completedServers.containsAll(ddlCommunicator.allServers)); } @Test public void noErrorWhenAllServersRespondBeforeFirstWait() throws Exception{ final List<String> servers = Arrays.asList("server1","server2"); final String changeId = "change"; TickingClock clock = new IncrementingClock(0); final TestDDLCommunicator ddlCommunicator = new TestDDLCommunicator(servers){ @Override public String createChangeNode(DDLChange change) throws StandardException{ return changeId; } }; for(String server:servers){ ddlCommunicator.serverCompleted(changeId,server); } final TestCondition condition = new TestCondition(clock){ @Override protected void waitUninterruptibly(){ Assert.fail("Should not wait on the condition!"); } }; final TestLock lock = new TestLock(clock){ @Override protected void blockUninterruptibly(){ } @Override public boolean tryLock(){ Assert.fail("Should not have tried the lock!"); return false; } @Override public Condition newCondition(){ return condition; } }; LockFactory lf = new SingleInstanceLockFactory(lock); AsynchronousDDLController controller=new AsynchronousDDLController(ddlCommunicator,lf,clock,10,100); TxnView txn = new WritableTxn(1l,1l,null,Txn.IsolationLevel.SNAPSHOT_ISOLATION,Txn.ROOT_TRANSACTION,null,false,null); DDLChange change = ProtoUtil.createNoOpDDLChange(txn.getTxnId(),"testChange",DDLMessage.DDLChangeType.CREATE_SCHEMA); String retChangeId=controller.notifyMetadataChange(change); Assert.assertEquals("Change id does not match!",changeId,retChangeId); Assert.assertTrue("Some servers are missing!",ddlCommunicator.completedServers.containsAll(ddlCommunicator.allServers)); } @Test public void testWorksWhenAllServersRespondAfterFirstCheck() throws Exception{ final List<String> servers = Arrays.asList("server1","server2"); final String changeId = "change"; final TestDDLCommunicator ddlCommunicator = new TestDDLCommunicator(servers){ @Override public String createChangeNode(DDLChange change) throws StandardException{ return changeId; } }; TickingClock clock = new IncrementingClock(0); final TestCondition condition = new TestCondition(clock){ @Override protected void waitUninterruptibly(){ for(String server:servers){ ddlCommunicator.serverCompleted(changeId,server); } } }; final TestLock lock = new TestLock(clock){ @Override protected void blockUninterruptibly(){ } @Override public boolean tryLock(){ return true; } @Override public Condition newCondition(){ return condition; } }; LockFactory lf = new SingleInstanceLockFactory(lock); AsynchronousDDLController controller=new AsynchronousDDLController(ddlCommunicator,lf,clock,100,10); TxnView txn = new WritableTxn(1l,1l,null,Txn.IsolationLevel.SNAPSHOT_ISOLATION,Txn.ROOT_TRANSACTION,null,false,null); DDLChange change = ProtoUtil.createNoOpDDLChange(txn.getTxnId(),"testCHange",DDLMessage.DDLChangeType.ADD_NOT_NULL); String retChangeId=controller.notifyMetadataChange(change); Assert.assertEquals("Change id does not match!",changeId,retChangeId); Assert.assertTrue("Some servers are missing!",ddlCommunicator.completedServers.containsAll(ddlCommunicator.allServers)); }
FormatableBitSet implements Formatable, Cloneable { public void set(int position) { checkPosition(position); final int byteIndex = udiv8(position); final byte bitIndex = umod8(position); value[byteIndex] |= (0x80>>bitIndex); } FormatableBitSet(); FormatableBitSet(int numBits); FormatableBitSet(byte[] newValue); FormatableBitSet(FormatableBitSet original); Object clone(); boolean invariantHolds(); int getLengthInBytes(); int getLength(); int size(); byte[] getByteArray(); void grow(int n); void shrink(int n); boolean equals(Object other); int compare(FormatableBitSet other); int hashCode(); final boolean isSet(int position); final boolean get(int position); void set(int position); void clear(int position); void clear(); String toString(); static int maxBitsForSpace(int numBytes); int anySetBit(); int anySetBit(int beyondBit); void or(FormatableBitSet otherBit); void and(FormatableBitSet otherBit); void xor(FormatableBitSet otherBit); int getNumBitsSet(); void writeExternal(ObjectOutput out); void readExternal(ObjectInput in); int getTypeFormatId(); }
@Test public void testSetEmpty() { try { empty.set(-8); fail(); } catch (IllegalArgumentException ignored) { } try { empty.set(-1); fail(); } catch (IllegalArgumentException ignored) { } try { empty.set(0); fail(); } catch (IllegalArgumentException ignored) { } } @Test public void testSet() { try { bitset18.set(-8); fail(); } catch (IllegalArgumentException ignored) { } try { bitset18.set(-1); fail(); } catch (IllegalArgumentException ignored) { } bitset18.set(0); assertTrue(bitset18.invariantHolds()); bitset18.set(1); assertTrue(bitset18.invariantHolds()); try { bitset18.set(18); fail(); } catch (IllegalArgumentException ignored) { } }
AbstractSequence implements Sequence, Externalizable { public long getNext() throws StandardException{ if(remaining.getAndDecrement()<=0) allocateBlock(false); return currPosition.getAndAdd(incrementSteps); } AbstractSequence(); AbstractSequence(long blockAllocationSize,long incrementSteps,long startingValue); long getNext(); long peekAtCurrentValue(); abstract void close(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); }
@Test public void singleThreaded100BlockSingleIncrementTestWithRollover() throws Exception { Sequence sequence = new SpliceTestSequence(100,1,0); for (long i = 0; i< 1000; i++) { long next = sequence.getNext(); Assert.assertTrue(i==next); } } @Test public void singleThreaded1BlockSingleIncrementTestWithRollover() throws Exception { Sequence sequence = new SpliceTestSequence(1,1,0); for (long i = 0; i< 1000; i++) { long next = sequence.getNext(); Assert.assertTrue(i==next); } } @Test public void singleThreaded1BlockWithStarting20WithRollover() throws Exception { Sequence sequence = new SpliceTestSequence(1,1,20); for (long i = 0; i< 1000; i++) { long next = sequence.getNext(); Assert.assertTrue(i+20==next); } } @Test public void singleThreaded100BlockWithStarting20Increment10WithRollover() throws Exception { Sequence sequence = new SpliceTestSequence(100,10,20); for (long i = 0; i< 1000; i++) { long next = sequence.getNext(); Assert.assertTrue((i*10+20)==next); } }
DMLTriggerEventMapper { public static TriggerEvent getBeforeEvent(Class<? extends DMLWriteOperation> operationClass) { for (Map.Entry<Class<? extends DMLWriteOperation>, TriggerEvent> entry : beforeMap.entrySet()) { if (entry.getKey().isAssignableFrom(operationClass)) { return entry.getValue(); } } throw new IllegalArgumentException("could not find trigger event for operation = " + operationClass); } static TriggerEvent getBeforeEvent(Class<? extends DMLWriteOperation> operationClass); static TriggerEvent getAfterEvent(Class<? extends DMLWriteOperation> operationClass); }
@Test public void testGetBeforeEvent() throws Exception { assertEquals(TriggerEvent.BEFORE_DELETE, DMLTriggerEventMapper.getBeforeEvent(DeleteOperation.class)); assertEquals(TriggerEvent.BEFORE_INSERT, DMLTriggerEventMapper.getBeforeEvent(InsertOperation.class)); assertEquals(TriggerEvent.BEFORE_UPDATE, DMLTriggerEventMapper.getBeforeEvent(UpdateOperation.class)); }
DMLTriggerEventMapper { public static TriggerEvent getAfterEvent(Class<? extends DMLWriteOperation> operationClass) { for (Map.Entry<Class<? extends DMLWriteOperation>, TriggerEvent> entry : afterMap.entrySet()) { if (entry.getKey().isAssignableFrom(operationClass)) { return entry.getValue(); } } throw new IllegalArgumentException("could not find trigger event for operation = " + operationClass); } static TriggerEvent getBeforeEvent(Class<? extends DMLWriteOperation> operationClass); static TriggerEvent getAfterEvent(Class<? extends DMLWriteOperation> operationClass); }
@Test public void testGetAfterEvent() throws Exception { assertEquals(TriggerEvent.AFTER_DELETE, DMLTriggerEventMapper.getAfterEvent(DeleteOperation.class)); assertEquals(TriggerEvent.AFTER_INSERT, DMLTriggerEventMapper.getAfterEvent(InsertOperation.class)); assertEquals(TriggerEvent.AFTER_UPDATE, DMLTriggerEventMapper.getAfterEvent(UpdateOperation.class)); }
IndexRowReader implements Iterator<ExecRow>, Iterable<ExecRow> { public int getMaxConcurrency() {return this.numBlocks;} IndexRowReader(Iterator<ExecRow> sourceIterator, ExecRow outputTemplate, TxnView txn, int lookupBatchSize, int numConcurrentLookups, long mainTableConglomId, byte[] predicateFilterBytes, KeyHashDecoder keyDecoder, KeyHashDecoder rowDecoder, int[] indexCols, TxnOperationFactory operationFactory, PartitionFactory tableFactory); int getMaxConcurrency(); void close(); @Override @SuppressFBWarnings(value = "IT_NO_SUCH_ELEMENT", justification = "DB-9844") ExecRow next(); ExecRow nextScannedRow(); @Override void remove(); @Override boolean hasNext(); @Override Iterator<ExecRow> iterator(); }
@Test public void testReaderConcurrency() throws Exception { IndexRowReader irr = new IndexRowReader( null, null, null, 4000, 0, 0, null, null, null, null, null, null); assertTrue("Expected a max concurrency of 2", irr.getMaxConcurrency() == 2); irr = new IndexRowReader( null, null, null, 4000, -5000, 0, null, null, null, null, null, null); assertTrue("Expected a max concurrency of 2", irr.getMaxConcurrency() == 2); }
ExportFile { public OutputStream getOutputStream() throws IOException { String fullyQualifiedExportFilePath = buildOutputFilePath(); OutputStream rawOutputStream =fileSystem.newOutputStream(fullyQualifiedExportFilePath, new DistributedFileOpenOption(exportParams.getReplicationCount(),StandardOpenOption.CREATE_NEW)); if (exportParams.getCompression()==COMPRESSION.BZ2) { Configuration conf = new Configuration(); CompressionCodecFactory factory = new CompressionCodecFactory(conf); CompressionCodec codec = factory.getCodecByClassName("org.apache.hadoop.io.compress.BZip2Codec"); return codec.createOutputStream(rawOutputStream); } else if (exportParams.getCompression()==COMPRESSION.GZ) { return new GZIPOutputStream(rawOutputStream); } else { return rawOutputStream; } } ExportFile(ExportParams exportParams, byte[] taskId); ExportFile(ExportParams exportParams, byte[] taskId, DistributedFileSystem fileSystem); OutputStream getOutputStream(); boolean createDirectory(); boolean delete(); boolean deleteDirectory(); boolean clearDirectory(); boolean isWritable(); static final String SUCCESS_FILE; }
@Test public void getOutputStream_createsStreamConnectedToExpectedFile() throws IOException { ExportParams exportParams = ExportParams.withDirectory(temporaryFolder.getRoot().getAbsolutePath()); ExportFile exportFile = new ExportFile(exportParams, testTaskId(),dfs); final byte[] EXPECTED_CONTENT = ("splice for the win" + RandomStringUtils.randomAlphanumeric(1000)).getBytes("utf-8"); OutputStream outputStream = exportFile.getOutputStream(); outputStream.write(EXPECTED_CONTENT); outputStream.close(); File expectedFile = new File(temporaryFolder.getRoot(), "export_82010203042A060708.csv"); assertTrue(expectedFile.exists()); Assert.assertArrayEquals(EXPECTED_CONTENT,IOUtils.toByteArray(new FileInputStream(expectedFile))); }
ExportFile { protected String buildFilenameFromTaskId(byte[] taskId) { String postfix = ""; if (exportParams.getCompression() == COMPRESSION.BZ2) { postfix = ".bz2"; } else if (exportParams.getCompression() == COMPRESSION.GZ) { postfix = ".gz"; } return "export_" + Bytes.toHex(taskId) + ".csv" + postfix; } ExportFile(ExportParams exportParams, byte[] taskId); ExportFile(ExportParams exportParams, byte[] taskId, DistributedFileSystem fileSystem); OutputStream getOutputStream(); boolean createDirectory(); boolean delete(); boolean deleteDirectory(); boolean clearDirectory(); boolean isWritable(); static final String SUCCESS_FILE; }
@Test public void buildFilenameFromTaskId() throws IOException { ExportFile streamSetup = new ExportFile(new ExportParams(), testTaskId(),dfs); byte[] taskId = testTaskId(); assertEquals("export_82010203042A060708.csv", streamSetup.buildFilenameFromTaskId(taskId)); }
ExportFile { public boolean delete() throws IOException { if (LOG.isDebugEnabled()) SpliceLogUtils.debug(LOG, "delete()"); try{ fileSystem.delete(exportParams.getDirectory(),buildFilenameFromTaskId(taskId), false); return true; }catch(NoSuchFileException fnfe){ return false; } } ExportFile(ExportParams exportParams, byte[] taskId); ExportFile(ExportParams exportParams, byte[] taskId, DistributedFileSystem fileSystem); OutputStream getOutputStream(); boolean createDirectory(); boolean delete(); boolean deleteDirectory(); boolean clearDirectory(); boolean isWritable(); static final String SUCCESS_FILE; }
@Test public void delete() throws IOException { ExportParams exportParams = ExportParams.withDirectory(temporaryFolder.getRoot().getAbsolutePath()); ExportFile exportFile = new ExportFile(exportParams, testTaskId(),dfs); exportFile.getOutputStream(); assertTrue("export file should exist in temp dir", temporaryFolder.getRoot().list().length > 0); exportFile.delete(); assertTrue("export file should be deleted", temporaryFolder.getRoot().list().length == 0); }
ExportFile { public boolean createDirectory() throws StandardException { if (LOG.isDebugEnabled()) SpliceLogUtils.debug(LOG, "createDirectory(): export directory=%s", exportParams.getDirectory()); try { return fileSystem.createDirectory(exportParams.getDirectory(), false); } catch (Exception ioe) { throw StandardException.newException(SQLState.FILESYSTEM_IO_EXCEPTION, ioe.getMessage()); } } ExportFile(ExportParams exportParams, byte[] taskId); ExportFile(ExportParams exportParams, byte[] taskId, DistributedFileSystem fileSystem); OutputStream getOutputStream(); boolean createDirectory(); boolean delete(); boolean deleteDirectory(); boolean clearDirectory(); boolean isWritable(); static final String SUCCESS_FILE; }
@Test public void createDirectory() throws IOException, StandardException { String testDir = temporaryFolder.getRoot().getAbsolutePath() + "/" + RandomStringUtils.randomAlphabetic(9); ExportParams exportParams = ExportParams.withDirectory(testDir); ExportFile exportFile = new ExportFile(exportParams, testTaskId(),dfs); assertTrue(exportFile.createDirectory()); assertTrue(new File(testDir).exists()); assertTrue(new File(testDir).isDirectory()); } @Ignore @Test public void createDirectory_returnsFalseWhenCannotCreate() throws IOException, StandardException { String testDir = "/noPermissionToCreateFolderInRoot"; ExportParams exportParams = ExportParams.withDirectory(testDir); ExportFile exportFile = new ExportFile(exportParams, testTaskId(),dfs); try { assertFalse(exportFile.createDirectory()); } catch (Exception e) { assertThat(e.getMessage(), stringContainsInOrder("IOException '/noPermissionToCreateFolderInRoot","' when accessing directory")); } assertFalse(new File(testDir).exists()); assertFalse(new File(testDir).isDirectory()); }
ExportPermissionCheck { void verify() throws StandardException { verifyExportDirExistsOrCanBeCreated(); verifyExportDirWritable(); } ExportPermissionCheck(ExportParams exportParams,DistributedFileSystem dfs); ExportPermissionCheck(ExportParams exportParams); void cleanup(); }
@Ignore @Test public void verify_failCase() throws IOException, StandardException { ExportParams exportParams = ExportParams.withDirectory("/ExportPermissionCheckTest"); ExportPermissionCheck permissionCheck = new ExportPermissionCheck(exportParams,dfs); try { permissionCheck.verify(); } catch (Exception e) { assertThat(e.getMessage(), stringContainsInOrder("IOException '/ExportPermissionCheckTest", "' when accessing directory")); } }
ExportCSVWriterBuilder { public CsvListWriter build(OutputStream outputStream, ExportParams exportParams) throws IOException { OutputStreamWriter stream = new OutputStreamWriter(outputStream, exportParams.getCharacterEncoding()); Writer writer = new BufferedWriter(stream, WRITE_BUFFER_SIZE_BYTES); CsvPreference preference = new CsvPreference.Builder( exportParams.getQuoteChar(), exportParams.getFieldDelimiter(), exportParams.getRecordDelimiter()) .useQuoteMode(new ColumnQuoteMode()) .build(); return new CsvListWriter(writer, preference); } CsvListWriter build(OutputStream outputStream, ExportParams exportParams); }
@Test public void buildCVSWriter() throws IOException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); ExportParams exportParams = ExportParams.withDirectory("/tmp"); CsvListWriter csvWriter = csvWriterBuilder.build(byteStream, exportParams); csvWriter.write(new String[]{"a1", "b1", "c1", "d1"}); csvWriter.write(new String[]{"a2", "b 2", "c2", "d2"}); csvWriter.write(new String[]{"a3", "b3", "c3", "d,3"}); csvWriter.write(new String[]{"a\n4", "b4", "c4", "d4"}); csvWriter.write(new String[]{"a5", "b\"5", "c5", "d5"}); csvWriter.write(new String[]{"a5", "b5", "c5\u1272", "d5"}); csvWriter.close(); assertEquals("" + "a1,b1,c1,d1\n" + "a2,b 2,c2,d2\n" + "a3,b3,c3,\"d,3\"\n" + "\"a\n" + "4\",b4,c4,d4\n" + "a5,\"b\"\"5\",c5,d5\n" + "a5,b5,c5ቲ,d5\n", new String(byteStream.toByteArray(), "UTF-8")); }
CostUtils { public static long add(long count1, long count2) { checkArgument(count1 >= 0); checkArgument(count2 >= 0); long sum = count1 + count2; return (sum >= 0L) ? sum : Long.MAX_VALUE; } static long add(long count1, long count2); }
@Test public void add() { long result = CostUtils.add(20L, 20L); assertEquals(40L, result); result = CostUtils.add(Long.MAX_VALUE, 200L); assertEquals(Long.MAX_VALUE, result); }
SpliceClient { static String parseJDBCPassword(String jdbcUrl) throws SqlException { Properties properties = ClientDriver.tokenizeURLProperties(jdbcUrl, null); return properties.getProperty("password"); } static synchronized void setClient(boolean tokenEnabled, Mode mode); static boolean isClient(); @SuppressFBWarnings(value = "DC_PARTIALLY_CONSTRUCTED", justification = "DB-9844") static DataSource getConnectionPool(boolean debugConnections, int maxConnections); @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "DB-9844") static boolean isRegionServer; static volatile String connectionString; static volatile byte[] token; }
@Test public void testParseJDBCPassword() throws SqlException { String password = "Abd98*@80EFg"; String raw = "jdbc:splice: assertEquals(password, SpliceClient.parseJDBCPassword(raw)); raw = "jdbc:splice: assertEquals(password, SpliceClient.parseJDBCPassword(raw)); }
ConstraintContext implements Externalizable { public ConstraintContext withInsertedMessage(int index, String newMessage) { return new ConstraintContext((String[]) ArrayUtils.add(messageArgs,index,newMessage)); } @Deprecated ConstraintContext(); ConstraintContext(String... messageArgs); static ConstraintContext empty(); static ConstraintContext unique(String tableName, String constraintName); static ConstraintContext primaryKey(String tableName, String constraintName); static ConstraintContext foreignKey(FKConstraintInfo fkConstraintInfo); ConstraintContext withInsertedMessage(int index, String newMessage); ConstraintContext withoutMessage(int index); ConstraintContext withMessage(int index, String newMessage); @SuppressFBWarnings(value = "EI_EXPOSE_REP",justification = "Intentional") String[] getMessages(); @Override boolean equals(Object o); @Override int hashCode(); @Override void readExternal(ObjectInput objectInput); @Override void writeExternal(ObjectOutput objectOutput); @Override String toString(); }
@Test public void withInsertedMessage() { ConstraintContext context1 = new ConstraintContext("aa", "bb", "cc"); ConstraintContext context2 = context1.withInsertedMessage(0, "ZZ"); ConstraintContext context3 = context1.withInsertedMessage(1, "ZZ"); ConstraintContext context4 = context1.withInsertedMessage(2, "ZZ"); ConstraintContext context5 = context1.withInsertedMessage(3, "ZZ"); assertArrayEquals(new String[]{"ZZ", "aa", "bb", "cc"}, context2.getMessages()); assertArrayEquals(new String[]{"aa", "ZZ", "bb", "cc"}, context3.getMessages()); assertArrayEquals(new String[]{"aa", "bb", "ZZ", "cc"}, context4.getMessages()); assertArrayEquals(new String[]{"aa", "bb", "cc", "ZZ"}, context5.getMessages()); }
ConstraintContext implements Externalizable { public ConstraintContext withoutMessage(int index) { return new ConstraintContext((String[]) ArrayUtils.remove(messageArgs,index)); } @Deprecated ConstraintContext(); ConstraintContext(String... messageArgs); static ConstraintContext empty(); static ConstraintContext unique(String tableName, String constraintName); static ConstraintContext primaryKey(String tableName, String constraintName); static ConstraintContext foreignKey(FKConstraintInfo fkConstraintInfo); ConstraintContext withInsertedMessage(int index, String newMessage); ConstraintContext withoutMessage(int index); ConstraintContext withMessage(int index, String newMessage); @SuppressFBWarnings(value = "EI_EXPOSE_REP",justification = "Intentional") String[] getMessages(); @Override boolean equals(Object o); @Override int hashCode(); @Override void readExternal(ObjectInput objectInput); @Override void writeExternal(ObjectOutput objectOutput); @Override String toString(); }
@Test public void withOutMessage() { ConstraintContext context1 = new ConstraintContext("aa", "bb", "cc"); ConstraintContext context2 = context1.withoutMessage(0); ConstraintContext context3 = context1.withoutMessage(1); ConstraintContext context4 = context1.withoutMessage(2); assertArrayEquals(new String[]{"bb", "cc"}, context2.getMessages()); assertArrayEquals(new String[]{"aa", "cc"}, context3.getMessages()); assertArrayEquals(new String[]{"aa", "bb"}, context4.getMessages()); }
ConstraintContext implements Externalizable { public ConstraintContext withMessage(int index, String newMessage) { String[] newArgs = Arrays.copyOf(this.messageArgs, this.messageArgs.length); newArgs[index] = newMessage; return new ConstraintContext(newArgs); } @Deprecated ConstraintContext(); ConstraintContext(String... messageArgs); static ConstraintContext empty(); static ConstraintContext unique(String tableName, String constraintName); static ConstraintContext primaryKey(String tableName, String constraintName); static ConstraintContext foreignKey(FKConstraintInfo fkConstraintInfo); ConstraintContext withInsertedMessage(int index, String newMessage); ConstraintContext withoutMessage(int index); ConstraintContext withMessage(int index, String newMessage); @SuppressFBWarnings(value = "EI_EXPOSE_REP",justification = "Intentional") String[] getMessages(); @Override boolean equals(Object o); @Override int hashCode(); @Override void readExternal(ObjectInput objectInput); @Override void writeExternal(ObjectOutput objectOutput); @Override String toString(); }
@Test public void withMessage() { ConstraintContext context1 = new ConstraintContext("aa", "bb", "cc"); ConstraintContext context2 = context1.withMessage(0, "ZZ"); ConstraintContext context3 = context1.withMessage(1, "ZZ"); ConstraintContext context4 = context1.withMessage(2, "ZZ"); assertArrayEquals(new String[]{"ZZ", "bb", "cc"}, context2.getMessages()); assertArrayEquals(new String[]{"aa", "ZZ", "cc"}, context3.getMessages()); assertArrayEquals(new String[]{"aa", "bb", "ZZ"}, context4.getMessages()); }
BulkWriteAction implements Callable<WriteStats> { @Override public WriteStats call() throws Exception{ statusReporter.numExecutingFlushes.incrementAndGet(); reportSize(); long start=System.currentTimeMillis(); try{ Timer totalTimer=metricFactory.newTimer(); totalTimer.startTiming(); if(LOG.isDebugEnabled()) SpliceLogUtils.debug(LOG,"Calling BulkWriteAction: id=%d, initialBulkWritesSize=%d, initialKVPairSize=%d",id,bulkWrites.numEntries(),bulkWrites.numEntries()); execute(bulkWrites); totalTimer.stopTiming(); if(metricFactory.isActive()) return new SimpleWriteStats(writtenCounter.getTotal(), retryCounter.getTotal(), thrownErrorsRows.getTotal(), retriedRows.getTotal(), partialRows.getTotal(), partialThrownErrorRows.getTotal(), partialRetriedRows.getTotal(), partialIgnoredRows.getTotal(), partialWrite.getTotal(), ignoredRows.getTotal(), catchThrownRows.getTotal(), catchRetriedRows.getTotal(), regionTooBusy.getTotal() ); else return WriteStats.NOOP_WRITE_STATS; }finally{ long timeTakenMs=System.currentTimeMillis()-start; long numRecords=bulkWrites.numEntries(); writeConfiguration.writeComplete(timeTakenMs,numRecords); statusReporter.complete(timeTakenMs); bulkWrites=null; } } @SuppressFBWarnings(value = "EI_EXPOSE_REP2",justification = "Intentional") BulkWriteAction(byte[] tableName, BulkWrites writes, WriteConfiguration writeConfiguration, ActionStatusReporter statusReporter, BulkWriterFactory writerFactory, PipelineExceptionFactory pipelineExceptionFactory, PartitionFactory partitionFactory, Clock clock); @Override WriteStats call(); }
@Test public void testDoesNotWriteDataWhenGivenAnEmptyBulkWrite() throws Exception{ byte[] table=Bytes.toBytes("1424"); TxnView txn=new ActiveWriteTxn(1l,1l,Txn.ROOT_TRANSACTION,true,Txn.IsolationLevel.SNAPSHOT_ISOLATION); Collection<BulkWrite> bwList=new ArrayList<>(); BulkWrites bw=new BulkWrites(bwList,txn); ActionStatusReporter asr=new ActionStatusReporter(); final BulkWriter writer = new FailWriter(); BulkWriterFactory bwf=new BulkWriterFactory(){ @Override public BulkWriter newWriter(byte[] tableName){ return writer; } @Override public void invalidateCache(byte[] tableName) throws IOException{ } @Override public void setPipeline(WritePipelineFactory writePipelineFactory){ throw new UnsupportedOperationException(); } @Override public void setWriter(PipelineWriter pipelineWriter){ throw new UnsupportedOperationException(); } }; PartitionServer ts = mock(PartitionServer.class); Partition p = mock(Partition.class); when(p.subPartitions()).thenReturn(Collections.singletonList(p)); when(p.owningServer()).thenReturn(ts); when(p.getName()).thenReturn("region2"); when(p.getStartKey()).thenReturn(new byte[]{}); PartitionFactory pf = mock(PartitionFactory.class); when(pf.getTable(any(String.class))).thenReturn(p); WriteConfiguration config = new DefaultWriteConfiguration(new Monitor(0,0,10,10L,0),pef); IncrementingClock clock = new IncrementingClock(); BulkWriteAction bwa = new BulkWriteAction(table, bw, config, asr, bwf, pef, pf, clock); bwa.call(); Assert.assertEquals("Should not have waited!",0,clock.currentTimeMillis()); } @Test public void testDoesNotWriteDataWhenGivenBulkWriteWithNoRecords() throws Exception{ byte[] table=Bytes.toBytes("1424"); TxnView txn=new ActiveWriteTxn(1l,1l,Txn.ROOT_TRANSACTION,true,Txn.IsolationLevel.SNAPSHOT_ISOLATION); Collection<BulkWrite> bwList=new ArrayList<>(); bwList.add(new BulkWrite(Collections.<KVPair>emptyList(),"region1")); BulkWrites bw=new BulkWrites(bwList,txn); ActionStatusReporter asr=new ActionStatusReporter(); final BulkWriter writer = new FailWriter(); BulkWriterFactory bwf=new BulkWriterFactory(){ @Override public BulkWriter newWriter(byte[] tableName){ return writer; } @Override public void invalidateCache(byte[] tableName) throws IOException{ } @Override public void setPipeline(WritePipelineFactory writePipelineFactory){ throw new UnsupportedOperationException(); } @Override public void setWriter(PipelineWriter pipelineWriter){ throw new UnsupportedOperationException(); } }; PartitionServer ts = mock(PartitionServer.class); Partition p = mock(Partition.class); when(p.subPartitions()).thenReturn(Collections.singletonList(p)); when(p.owningServer()).thenReturn(ts); when(p.getName()).thenReturn("region2"); when(p.getStartKey()).thenReturn(new byte[]{}); PartitionFactory pf = mock(PartitionFactory.class); when(pf.getTable(any(String.class))).thenReturn(p); WriteConfiguration config = new DefaultWriteConfiguration(new Monitor(0,0,10,10L,0),pef); IncrementingClock clock = new IncrementingClock(); BulkWriteAction bwa = new BulkWriteAction(table, bw, config, asr, bwf, pef, pf, clock); bwa.call(); Assert.assertEquals("Should not have waited!",0,clock.currentTimeMillis()); } @Test public void testCorrectlyRetriesWhenOneRegionStops() throws Exception{ byte[] table=Bytes.toBytes("1424"); TxnView txn=new ActiveWriteTxn(1l,1l,Txn.ROOT_TRANSACTION,true,Txn.IsolationLevel.SNAPSHOT_ISOLATION); Collection<BulkWrite> bwList=new ArrayList<>(2); bwList.add(new BulkWrite(addData(0,10),"region1")); bwList.add(new BulkWrite(addData(100,10),"region2")); BulkWrites bw=new BulkWrites(bwList,txn); ActionStatusReporter asr=new ActionStatusReporter(); final TestBulkWriter writer = new TestBulkWriter(); BulkWriterFactory bwf=new BulkWriterFactory(){ @Override public BulkWriter newWriter(byte[] tableName){ return writer; } @Override public void invalidateCache(byte[] tableName) throws IOException{ } @Override public void setPipeline(WritePipelineFactory writePipelineFactory){ throw new UnsupportedOperationException(); } @Override public void setWriter(PipelineWriter pipelineWriter){ throw new UnsupportedOperationException(); } }; PartitionServer ts = mock(PartitionServer.class); Partition p = mock(Partition.class); when(p.subPartitions()).thenReturn(Collections.singletonList(p)); when(p.owningServer()).thenReturn(ts); when(p.getName()).thenReturn("region2"); when(p.getStartKey()).thenReturn(new byte[]{}); PartitionFactory pf = mock(PartitionFactory.class); when(pf.getTable(any(String.class))).thenReturn(p); WriteConfiguration config = new DefaultWriteConfiguration(new Monitor(0,0,10,10L,0),pef); config.setRecordingContext(new TestRecordingContext()); IncrementingClock clock = new IncrementingClock(); BulkWriteAction bwa = new BulkWriteAction(table, bw, config, asr, bwf, pef, pf, clock); WriteStats ws = bwa.call(); Assert.assertEquals("Incorrect number of calls!",2,writer.callCount); Collection<KVPair> allData = writer.data; Set<KVPair> deduped = new HashSet<>(allData); Assert.assertEquals("Duplicate rows were inserted!",allData.size(),deduped.size()); for(BulkWrite write:bwList){ Collection<KVPair> toWrite = write.getMutations(); for(KVPair mutation:toWrite){ Assert.assertTrue("Missing write!",allData.contains(mutation)); } } Assert.assertEquals("Unexpected number of retries.", 1, ws.getRetryCounter()); } @Test public void testCorrectlyRetriesPartialResults() throws Exception{ byte[] table=Bytes.toBytes("1424"); TxnView txn=new ActiveWriteTxn(1l,1l,Txn.ROOT_TRANSACTION,true,Txn.IsolationLevel.SNAPSHOT_ISOLATION); Collection<BulkWrite> bwList=new ArrayList<>(2); bwList.add(new BulkWrite(addData(0,10),"region1")); bwList.add(new BulkWrite(addData(100,10),"region2")); BulkWrites bw=new BulkWrites(bwList,txn); ActionStatusReporter asr=new ActionStatusReporter(); final PartialTestBulkWriter writer = new PartialTestBulkWriter(); BulkWriterFactory bwf=new BulkWriterFactory(){ @Override public BulkWriter newWriter(byte[] tableName){ return writer; } @Override public void invalidateCache(byte[] tableName) throws IOException{ } @Override public void setPipeline(WritePipelineFactory writePipelineFactory){ throw new UnsupportedOperationException(); } @Override public void setWriter(PipelineWriter pipelineWriter){ throw new UnsupportedOperationException(); } }; PartitionServer ts = mock(PartitionServer.class); Partition p = mock(Partition.class); when(p.subPartitions()).thenReturn(Collections.singletonList(p)); when(p.owningServer()).thenReturn(ts); when(p.getName()).thenReturn("region2"); when(p.getStartKey()).thenReturn(new byte[]{}); PartitionFactory pf = mock(PartitionFactory.class); when(pf.getTable(any(String.class))).thenReturn(p); WriteConfiguration config = new DefaultWriteConfiguration(new Monitor(0,0,10,10L,0),pef); config.setRecordingContext(new TestRecordingContext()); IncrementingClock clock = new IncrementingClock(); BulkWriteAction bwa = new BulkWriteAction(table, bw, config, asr, bwf, pef, pf, clock); WriteStats ws = bwa.call(); Assert.assertEquals("Incorrect number of calls!",2,writer.callCount); Collection<KVPair> allData = writer.data; Set<KVPair> deduped = new HashSet<>(allData); Assert.assertEquals("Duplicate rows were inserted!",allData.size(),deduped.size()); for(BulkWrite write:bwList){ Collection<KVPair> toWrite = write.getMutations(); for(KVPair mutation:toWrite){ Assert.assertTrue("Missing write!",allData.contains(mutation)); } } Assert.assertEquals("Unexpected number of retries.", 1, ws.getRetryCounter()); } @Test public void testCorrectlyRetriesWhenOneRegionStopsButReturnsResult() throws Exception{ byte[] table=Bytes.toBytes("1424"); TxnView txn=new ActiveWriteTxn(1l,1l,Txn.ROOT_TRANSACTION,true,Txn.IsolationLevel.SNAPSHOT_ISOLATION); Collection<BulkWrite> bwList=new ArrayList<>(2); bwList.add(new BulkWrite(addData(0,10),"region1")); bwList.add(new BulkWrite(addData(100,10),"region2")); BulkWrites bw=new BulkWrites(bwList,txn); ActionStatusReporter asr=new ActionStatusReporter(); final TestBulkWriter writer = new TestBulkWriter(); BulkWriterFactory bwf=new BulkWriterFactory(){ @Override public BulkWriter newWriter(byte[] tableName){ return writer; } @Override public void invalidateCache(byte[] tableName) throws IOException{ } @Override public void setPipeline(WritePipelineFactory writePipelineFactory){ throw new UnsupportedOperationException(); } @Override public void setWriter(PipelineWriter pipelineWriter){ throw new UnsupportedOperationException(); } }; PartitionServer ts = mock(PartitionServer.class); Partition p = mock(Partition.class); when(p.subPartitions()).thenReturn(Collections.singletonList(p)); when(p.owningServer()).thenReturn(ts); when(p.getName()).thenReturn("region2"); when(p.getStartKey()).thenReturn(new byte[]{}); PartitionFactory pf = mock(PartitionFactory.class); when(pf.getTable(any(String.class))).thenReturn(p); WriteConfiguration config = new DefaultWriteConfiguration(new Monitor(0,0,10,10L,0),pef); config.setRecordingContext(new TestRecordingContext()); IncrementingClock clock = new IncrementingClock(); BulkWriteAction bwa = new BulkWriteAction(table, bw, config, asr, bwf, pef, pf, clock); WriteStats ws = bwa.call(); Assert.assertEquals("Incorrect number of calls!",2,writer.callCount); Collection<KVPair> allData = writer.data; Set<KVPair> deduped = new HashSet<>(allData); Assert.assertEquals("Duplicate rows were inserted!",allData.size(),deduped.size()); for(BulkWrite write:bwList){ Collection<KVPair> toWrite = write.getMutations(); for(KVPair mutation:toWrite){ Assert.assertTrue("Missing write!",allData.contains(mutation)); } } Assert.assertEquals("Unexpected number of retries.", 1, ws.getRetryCounter()); }
FormatableBitSet implements Formatable, Cloneable { public void clear(int position) { checkPosition(position); final int byteIndex = udiv8(position); final byte bitIndex = umod8(position); value[byteIndex] &= ~(0x80>>bitIndex); } FormatableBitSet(); FormatableBitSet(int numBits); FormatableBitSet(byte[] newValue); FormatableBitSet(FormatableBitSet original); Object clone(); boolean invariantHolds(); int getLengthInBytes(); int getLength(); int size(); byte[] getByteArray(); void grow(int n); void shrink(int n); boolean equals(Object other); int compare(FormatableBitSet other); int hashCode(); final boolean isSet(int position); final boolean get(int position); void set(int position); void clear(int position); void clear(); String toString(); static int maxBitsForSpace(int numBytes); int anySetBit(); int anySetBit(int beyondBit); void or(FormatableBitSet otherBit); void and(FormatableBitSet otherBit); void xor(FormatableBitSet otherBit); int getNumBitsSet(); void writeExternal(ObjectOutput out); void readExternal(ObjectInput in); int getTypeFormatId(); }
@Test public void testClearEmpty() { try { empty.clear(-8); fail(); } catch (IllegalArgumentException ignored) { } try { empty.clear(-1); fail(); } catch (IllegalArgumentException ignored) { } try { empty.clear(0); fail(); } catch (IllegalArgumentException ignored) { } } @Test public void testClear() { try { bitset18.clear(-8); fail(); } catch (IllegalArgumentException ignored) { } try { bitset18.clear(-1); fail(); } catch (IllegalArgumentException ignored) { } bitset18.clear(0); assertTrue(bitset18.invariantHolds()); bitset18.clear(1); assertTrue(bitset18.invariantHolds()); try { bitset18.clear(18); fail(); } catch (IllegalArgumentException ignored) { } }
FormatableBitSet implements Formatable, Cloneable { public int anySetBit() { if (SanityManager.DEBUG) { SanityManager.ASSERT(invariantHolds(), "broken invariant"); } final int numbytes = getLengthInBytes(); for (int i = 0; i < numbytes; ++i) { final byte v = value[i]; if (v == 0) continue; return (umul8(i) + firstSet(v)); } return -1; } FormatableBitSet(); FormatableBitSet(int numBits); FormatableBitSet(byte[] newValue); FormatableBitSet(FormatableBitSet original); Object clone(); boolean invariantHolds(); int getLengthInBytes(); int getLength(); int size(); byte[] getByteArray(); void grow(int n); void shrink(int n); boolean equals(Object other); int compare(FormatableBitSet other); int hashCode(); final boolean isSet(int position); final boolean get(int position); void set(int position); void clear(int position); void clear(); String toString(); static int maxBitsForSpace(int numBytes); int anySetBit(); int anySetBit(int beyondBit); void or(FormatableBitSet otherBit); void and(FormatableBitSet otherBit); void xor(FormatableBitSet otherBit); int getNumBitsSet(); void writeExternal(ObjectOutput out); void readExternal(ObjectInput in); int getTypeFormatId(); }
@Test public void testAnySetBitEmpty() { assertEquals(empty.anySetBit(), -1); } @Test public void testAnySetBit() { assertEquals(2, bitset18C.anySetBit()); bitset18C.clear(2); assertEquals(3, bitset18C.anySetBit()); } @Test public void testAnySetBitBeyondBit() { assertEquals(4, bitset18.anySetBit(1)); } @Test public void testAnySetBitBeyondBitNeg() { assertEquals(1, bitset18.anySetBit(0)); assertEquals(0, bitset18.anySetBit(-1)); try { bitset18.anySetBit(-2); fail(); } catch (ArrayIndexOutOfBoundsException ignored) { } try { bitset18.anySetBit(-3); fail(); } catch (ArrayIndexOutOfBoundsException ignored) { } } @Test public void testAnySetBitBeyondBitPastEnd() { assertEquals(-1, bitset18.anySetBit(18)); }
ArrayInputStream extends InputStream implements LimitObjectInput { public long skip(long count) throws IOException { if (count <= 0) { return 0; } long toSkip = Math.min(count, available()); position += toSkip; return toSkip; } ArrayInputStream(); ArrayInputStream(byte[] data); void setData(byte[] data); byte[] getData(); int read(); int read(byte b[], int off, int len); long skip(long count); int getPosition(); final void setPosition(int newPosition); int available(); void setLimit(int offset, int length); final void setLimit(int length); final int clearLimit(); final void readFully(byte b[]); final void readFully(byte b[], int off, int len); final int skipBytes(int n); final boolean readBoolean(); final byte readByte(); final int readUnsignedByte(); final short readShort(); final int readUnsignedShort(); final char readChar(); final int readInt(); final long readLong(); final float readFloat(); final double readDouble(); final String readLine(); final String readUTF(); final int readDerbyUTF(char[][] rawData_array, int utflen); final int readCompressedInt(); final long readCompressedLong(); Object readObject(); String getErrorInfo(); Exception getNestedException(); }
@Test public void testSkipNegative() throws IOException { ArrayInputStream ais = new ArrayInputStream(new byte[1000]); assertEquals(0, ais.skip(-1)); }
ArrayInputStream extends InputStream implements LimitObjectInput { public final int skipBytes(int n) throws IOException { return (int) skip(n); } ArrayInputStream(); ArrayInputStream(byte[] data); void setData(byte[] data); byte[] getData(); int read(); int read(byte b[], int off, int len); long skip(long count); int getPosition(); final void setPosition(int newPosition); int available(); void setLimit(int offset, int length); final void setLimit(int length); final int clearLimit(); final void readFully(byte b[]); final void readFully(byte b[], int off, int len); final int skipBytes(int n); final boolean readBoolean(); final byte readByte(); final int readUnsignedByte(); final short readShort(); final int readUnsignedShort(); final char readChar(); final int readInt(); final long readLong(); final float readFloat(); final double readDouble(); final String readLine(); final String readUTF(); final int readDerbyUTF(char[][] rawData_array, int utflen); final int readCompressedInt(); final long readCompressedLong(); Object readObject(); String getErrorInfo(); Exception getNestedException(); }
@Test public void testSkipBytesNegative() throws IOException { ArrayInputStream ais = new ArrayInputStream(new byte[1000]); assertEquals(0, ais.skipBytes(-1)); }
SQLSmallint extends NumberDataType { public int getInt() { return (int) value; } SQLSmallint(); SQLSmallint(short val); SQLSmallint(int val); private SQLSmallint(short val, boolean isNull); SQLSmallint(Short obj); int getInt(); byte getByte(); short getShort(); long getLong(); float getFloat(); double getDouble(); boolean getBoolean(); String getString(); int getLength(); Object getObject(); String getTypeName(); int getTypeFormatId(); void writeExternal(ObjectOutput out); void readExternalFromArray(ArrayInputStream in); void readExternal(ObjectInput in); void restoreToNull(); DataValueDescriptor cloneValue(boolean forceMaterialization); DataValueDescriptor getNewNull(); void setValueFromResultSet(ResultSet resultSet, int colNumber, boolean isNullable); final void setInto(PreparedStatement ps, int position); final void setInto(ResultSet rs, int position); void setValue(String theValue); void setValue(short theValue); void setValue(byte theValue); void setValue(int theValue); void setValue(long theValue); void setValue(float theValue); void setValue(double theValue); void setValue(boolean theValue); void setValue(Integer theValue); int typePrecedence(); BooleanDataValue equals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue notEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessOrEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterOrEquals(DataValueDescriptor left, DataValueDescriptor right); NumberDataValue times(NumberDataValue left, NumberDataValue right, NumberDataValue result); NumberDataValue mod(NumberDataValue dividend, NumberDataValue divisor, NumberDataValue result); NumberDataValue minus(NumberDataValue result); String toString(); int hashCode(); int estimateMemoryUsage(); Format getFormat(); BigDecimal getBigDecimal(); @Override void read(Row row, int ordinal); @Override StructField getStructField(String columnName); @Override Object getSparkObject(); void updateThetaSketch(UpdateSketch updateSketch); @Override void setSparkObject(Object sparkObject); }
@Test public void addTwo() throws StandardException { SQLSmallint integer1 = new SQLSmallint(100); SQLSmallint integer2 = new SQLSmallint(100); Assert.assertEquals("Integer Add Fails", 200, integer1.plus(integer1, integer2, null).getInt(),0); }
SQLSmallint extends NumberDataType { public NumberDataValue minus(NumberDataValue result) throws StandardException { if (result == null) { result = new SQLSmallint(); } if (this.isNull()) { result.setToNull(); return result; } int operandValue = this.getShort(); result.setValue(-operandValue); return result; } SQLSmallint(); SQLSmallint(short val); SQLSmallint(int val); private SQLSmallint(short val, boolean isNull); SQLSmallint(Short obj); int getInt(); byte getByte(); short getShort(); long getLong(); float getFloat(); double getDouble(); boolean getBoolean(); String getString(); int getLength(); Object getObject(); String getTypeName(); int getTypeFormatId(); void writeExternal(ObjectOutput out); void readExternalFromArray(ArrayInputStream in); void readExternal(ObjectInput in); void restoreToNull(); DataValueDescriptor cloneValue(boolean forceMaterialization); DataValueDescriptor getNewNull(); void setValueFromResultSet(ResultSet resultSet, int colNumber, boolean isNullable); final void setInto(PreparedStatement ps, int position); final void setInto(ResultSet rs, int position); void setValue(String theValue); void setValue(short theValue); void setValue(byte theValue); void setValue(int theValue); void setValue(long theValue); void setValue(float theValue); void setValue(double theValue); void setValue(boolean theValue); void setValue(Integer theValue); int typePrecedence(); BooleanDataValue equals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue notEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessOrEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterOrEquals(DataValueDescriptor left, DataValueDescriptor right); NumberDataValue times(NumberDataValue left, NumberDataValue right, NumberDataValue result); NumberDataValue mod(NumberDataValue dividend, NumberDataValue divisor, NumberDataValue result); NumberDataValue minus(NumberDataValue result); String toString(); int hashCode(); int estimateMemoryUsage(); Format getFormat(); BigDecimal getBigDecimal(); @Override void read(Row row, int ordinal); @Override StructField getStructField(String columnName); @Override Object getSparkObject(); void updateThetaSketch(UpdateSketch updateSketch); @Override void setSparkObject(Object sparkObject); }
@Test(expected = StandardException.class) public void testNegativeOverFlow() throws StandardException { SQLSmallint integer1 = new SQLSmallint(Integer.MIN_VALUE); SQLSmallint integer2 = new SQLSmallint(1); integer1.minus(integer1, integer2, null); }
SQLSmallint extends NumberDataType { public void writeExternal(ObjectOutput out) throws IOException { out.writeBoolean(isNull); out.writeShort(value); } SQLSmallint(); SQLSmallint(short val); SQLSmallint(int val); private SQLSmallint(short val, boolean isNull); SQLSmallint(Short obj); int getInt(); byte getByte(); short getShort(); long getLong(); float getFloat(); double getDouble(); boolean getBoolean(); String getString(); int getLength(); Object getObject(); String getTypeName(); int getTypeFormatId(); void writeExternal(ObjectOutput out); void readExternalFromArray(ArrayInputStream in); void readExternal(ObjectInput in); void restoreToNull(); DataValueDescriptor cloneValue(boolean forceMaterialization); DataValueDescriptor getNewNull(); void setValueFromResultSet(ResultSet resultSet, int colNumber, boolean isNullable); final void setInto(PreparedStatement ps, int position); final void setInto(ResultSet rs, int position); void setValue(String theValue); void setValue(short theValue); void setValue(byte theValue); void setValue(int theValue); void setValue(long theValue); void setValue(float theValue); void setValue(double theValue); void setValue(boolean theValue); void setValue(Integer theValue); int typePrecedence(); BooleanDataValue equals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue notEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessOrEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterOrEquals(DataValueDescriptor left, DataValueDescriptor right); NumberDataValue times(NumberDataValue left, NumberDataValue right, NumberDataValue result); NumberDataValue mod(NumberDataValue dividend, NumberDataValue divisor, NumberDataValue result); NumberDataValue minus(NumberDataValue result); String toString(); int hashCode(); int estimateMemoryUsage(); Format getFormat(); BigDecimal getBigDecimal(); @Override void read(Row row, int ordinal); @Override StructField getStructField(String columnName); @Override Object getSparkObject(); void updateThetaSketch(UpdateSketch updateSketch); @Override void setSparkObject(Object sparkObject); }
@Test public void writeExternal() throws StandardException, IOException { SQLSmallint s = new SQLSmallint(42); MockObjectOutput moo = new MockObjectOutput(); s.writeExternal(moo); Assert.assertFalse("Shouldn't be null", moo.isNull); Assert.assertTrue("Unexpected value", moo.value == 42); } @Test public void writeExternalNull() throws IOException { SQLSmallint s = new SQLSmallint(); MockObjectOutput moo = new MockObjectOutput(); s.writeExternal(moo); Assert.assertTrue("Should be null", moo.isNull); }
SQLSmallint extends NumberDataType { public void readExternal(ObjectInput in) throws IOException { isNull = in.readBoolean(); value = in.readShort(); } SQLSmallint(); SQLSmallint(short val); SQLSmallint(int val); private SQLSmallint(short val, boolean isNull); SQLSmallint(Short obj); int getInt(); byte getByte(); short getShort(); long getLong(); float getFloat(); double getDouble(); boolean getBoolean(); String getString(); int getLength(); Object getObject(); String getTypeName(); int getTypeFormatId(); void writeExternal(ObjectOutput out); void readExternalFromArray(ArrayInputStream in); void readExternal(ObjectInput in); void restoreToNull(); DataValueDescriptor cloneValue(boolean forceMaterialization); DataValueDescriptor getNewNull(); void setValueFromResultSet(ResultSet resultSet, int colNumber, boolean isNullable); final void setInto(PreparedStatement ps, int position); final void setInto(ResultSet rs, int position); void setValue(String theValue); void setValue(short theValue); void setValue(byte theValue); void setValue(int theValue); void setValue(long theValue); void setValue(float theValue); void setValue(double theValue); void setValue(boolean theValue); void setValue(Integer theValue); int typePrecedence(); BooleanDataValue equals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue notEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessOrEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterOrEquals(DataValueDescriptor left, DataValueDescriptor right); NumberDataValue times(NumberDataValue left, NumberDataValue right, NumberDataValue result); NumberDataValue mod(NumberDataValue dividend, NumberDataValue divisor, NumberDataValue result); NumberDataValue minus(NumberDataValue result); String toString(); int hashCode(); int estimateMemoryUsage(); Format getFormat(); BigDecimal getBigDecimal(); @Override void read(Row row, int ordinal); @Override StructField getStructField(String columnName); @Override Object getSparkObject(); void updateThetaSketch(UpdateSketch updateSketch); @Override void setSparkObject(Object sparkObject); }
@Test public void readExternal() throws IOException { SQLSmallint s = new SQLSmallint(); MockObjectInput moi = new MockObjectInput(); moi.isNull = false; moi.value = 42; s.readExternal(moi); Assert.assertFalse("Shouldn't be null", s.isNull()); Assert.assertTrue("Unexpected value", s.getShort() == 42); } @Test public void readExternalNull() throws IOException { SQLSmallint s = new SQLSmallint(); MockObjectInput moi = new MockObjectInput(); moi.isNull = true; moi.value = 0; s.readExternal(moi); Assert.assertTrue("Should be null", s.isNull()); }
SQLChar extends DataType implements StringDataValue, StreamStorable { public String getString() throws StandardException { if (value == null) { int len = rawLength; if (len != -1) { value = new String(rawData, 0, len); if (len > RETURN_SPACE_THRESHOLD) { rawData = null; rawLength = -1; cKey = null; } } else if (_clobValue != null) { try { value = _clobValue.getSubString( 1L, getClobLength() ); _clobValue = null; } catch (SQLException se) { throw StandardException.plainWrapException( se ); } } else if (stream != null) { try { if (stream instanceof FormatIdInputStream) { readExternal((FormatIdInputStream) stream); } else { readExternal(new FormatIdInputStream(stream)); } stream = null; return getString(); } catch (IOException ioe) { throw StandardException.newException( SQLState.LANG_STREAMING_COLUMN_I_O_EXCEPTION, ioe, String.class.getName()); } } isNull = evaluateNull(); } return value; } SQLChar(); SQLChar(String val); SQLChar(Clob val); SQLChar( char[] val ); char[] getRawDataAndZeroIt(); void zeroRawData(); boolean getBoolean(); byte getByte(); @Override byte[] getBytes(); short getShort(); int getInt(); long getLong(); float getFloat(); double getDouble(); Date getDate(Calendar cal); DateTime getDateTime(); static DateTime getDate( String str, LocaleFinder localeFinder); static Date getDate( java.util.Calendar cal, String str, LocaleFinder localeFinder); Time getTime(Calendar cal); static Time getTime( Calendar cal, String str, LocaleFinder localeFinder); Timestamp getTimestamp( Calendar cal); static Timestamp getTimestamp( java.util.Calendar cal, String str, LocaleFinder localeFinder); InputStream returnStream(); void setStream(InputStream newStream); void loadStream(); Object getObject(); InputStream getStream(); CharacterStreamDescriptor getStreamWithDescriptor(); int typeToBigDecimal(); int getLength(); String getTypeName(); String getString(); @SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "DB-9406") char[] getCharArray(); int getTypeFormatId(); void writeExternal(ObjectOutput out); void readExternalFromArray(ArrayInputStream in); void readExternal(ObjectInput in); void restoreToNull(); boolean compare(int op, DataValueDescriptor other, boolean orderedNulls, boolean unknownRV); @SuppressFBWarnings(value="RV_NEGATING_RESULT_OF_COMPARETO", justification="Using compare method from dominant type") int compare(DataValueDescriptor other); DataValueDescriptor cloneHolder(); DataValueDescriptor cloneValue(boolean forceMaterialization); DataValueDescriptor getNewNull(); StringDataValue getValue(RuleBasedCollator collatorForComparison); final void setValueFromResultSet(ResultSet resultSet, int colNumber, boolean isNullable); final void setInto( PreparedStatement ps, int position); void setValue(Clob theValue); void setValue(String theValue); void setValue(boolean theValue); void setValue(int theValue); void setValue(double theValue); void setValue(float theValue); void setValue(short theValue); void setValue(long theValue); void setValue(byte theValue); void setValue(byte[] theValue); void setBigDecimal(Number bigDecimal); void setValue(Date theValue, Calendar cal); void setValue(Time theValue, Calendar cal); void setValue( Timestamp theValue, Calendar cal); final void setValue(InputStream theStream, int valueLength); void setObjectForCast( Object theValue, boolean instanceOfResultType, String resultTypeClassName); void normalize( DataTypeDescriptor desiredType, DataValueDescriptor source); void setWidth(int desiredWidth, int desiredScale, // Ignored boolean errorOnTrunc); BooleanDataValue equals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue notEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessOrEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterOrEquals(DataValueDescriptor left, DataValueDescriptor right); NumberDataValue charLength(NumberDataValue result); StringDataValue concatenate( StringDataValue leftOperand, StringDataValue rightOperand, StringDataValue result); StringDataValue repeat(StringDataValue leftOperand, NumberDataValue rightOperand, StringDataValue result); BooleanDataValue like(DataValueDescriptor pattern); BooleanDataValue like( DataValueDescriptor pattern, DataValueDescriptor escape); NumberDataValue locate( ConcatableDataValue searchFrom, NumberDataValue start, NumberDataValue result); ConcatableDataValue substring( NumberDataValue start, NumberDataValue length, ConcatableDataValue result, int maxLen, boolean isFixedLength); StringDataValue right( NumberDataValue length, StringDataValue result); StringDataValue left(NumberDataValue length, StringDataValue result); ConcatableDataValue replace( StringDataValue fromStr, StringDataValue toStr, ConcatableDataValue result); StringDataValue ansiTrim( int trimType, StringDataValue trimChar, StringDataValue result); StringDataValue upper(StringDataValue result); StringDataValue upperWithLocale(StringDataValue leftOperand, StringDataValue rightOperand, StringDataValue result); StringDataValue lowerWithLocale(StringDataValue leftOperand, StringDataValue rightOperand, StringDataValue result); StringDataValue lower(StringDataValue result); int typePrecedence(); String toString(); int hashCode(); int estimateMemoryUsage(); void copyState(SQLChar other); @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "DB-9406") void copyState( String otherValue, char[] otherRawData, int otherRawLength, CollationKey otherCKey, InputStream otherStream, Clob otherClobValue, LocaleFinder otherLocaleFinder ); String getTraceString(); StreamHeaderGenerator getStreamHeaderGenerator(); void setStreamHeaderFormat(Boolean inSoftUpgradeMode); Format getFormat(); int getSqlCharSize(); void setSqlCharSize(int size); void read(Row row, int ordinal); @Override StructField getStructField(String columnName); void updateThetaSketch(UpdateSketch updateSketch); @Override void setSparkObject(Object sparkObject); static final char PAD; }
@Test public void rowValueToDVDValue() throws Exception { SQLChar char1 = new SQLChar("foobar"); SQLChar char2 = new SQLChar(); ExecRow execRow = new ValueRow(2); execRow.setColumn(1, char1); execRow.setColumn(2, char2); Assert.assertEquals("foobar", ((Row) execRow).getString(0)); Assert.assertTrue(((Row) execRow).isNullAt(1)); Row sparkRow = execRow.getSparkRow(); Assert.assertEquals(sparkRow.getString(0), "foobar"); Assert.assertTrue(sparkRow.isNullAt(1)); }
SQLReal extends NumberDataType { public NumberDataValue plus(NumberDataValue addend1, NumberDataValue addend2, NumberDataValue result) throws StandardException { if (result == null) { result = new SQLReal(); } if (addend1.isNull() || addend2.isNull()) { result.setToNull(); return result; } double dsum = addend1.getDouble() + addend2.getDouble(); result.setValue(dsum); return result; } SQLReal(); SQLReal(float val); SQLReal(Float obj); int getInt(); byte getByte(); short getShort(); long getLong(); float getFloat(); double getDouble(); int typeToBigDecimal(); boolean getBoolean(); String getString(); int getLength(); Object getObject(); String getTypeName(); int getTypeFormatId(); void writeExternal(ObjectOutput out); void readExternal(ObjectInput in); void readExternalFromArray(ArrayInputStream in); void restoreToNull(); DataValueDescriptor cloneValue(boolean forceMaterialization); DataValueDescriptor getNewNull(); void setValueFromResultSet(ResultSet resultSet, int colNumber, boolean isNullable); final void setInto(PreparedStatement ps, int position); final void setInto(ResultSet rs, int position); void setValue(String theValue); void setValue(Number theValue); void setBigDecimal(Number bigDecimal); void setValue(float theValue); void setValue(int theValue); void setValue(long theValue); void setValue(double theValue); void setValue(boolean theValue); void setValue(Double theValue); int typePrecedence(); BooleanDataValue equals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue notEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessOrEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterOrEquals(DataValueDescriptor left, DataValueDescriptor right); NumberDataValue plus(NumberDataValue addend1, NumberDataValue addend2, NumberDataValue result); NumberDataValue minus(NumberDataValue left, NumberDataValue right, NumberDataValue result); NumberDataValue times(NumberDataValue left, NumberDataValue right, NumberDataValue result); NumberDataValue divide(NumberDataValue dividend, NumberDataValue divisor, NumberDataValue result); NumberDataValue minus(NumberDataValue result); String toString(); int hashCode(); int estimateMemoryUsage(); Format getFormat(); BigDecimal getBigDecimal(); @Override void read(Row row, int ordinal); @Override StructField getStructField(String columnName); void updateThetaSketch(UpdateSketch updateSketch); @Override void setSparkObject(Object sparkObject); }
@Test(expected = StandardException.class) public void testPositiveOverFlow() throws StandardException { SQLReal float1 = new SQLReal(Float.MAX_VALUE); SQLReal float2 = new SQLReal(1.0f); float1.plus(float1,float2,null); }
SQLReal extends NumberDataType { public NumberDataValue minus(NumberDataValue left, NumberDataValue right, NumberDataValue result) throws StandardException { if (result == null) { result = new SQLReal(); } if (left.isNull() || right.isNull()) { result.setToNull(); return result; } double ddifference = left.getDouble() - right.getDouble(); result.setValue(ddifference); return result; } SQLReal(); SQLReal(float val); SQLReal(Float obj); int getInt(); byte getByte(); short getShort(); long getLong(); float getFloat(); double getDouble(); int typeToBigDecimal(); boolean getBoolean(); String getString(); int getLength(); Object getObject(); String getTypeName(); int getTypeFormatId(); void writeExternal(ObjectOutput out); void readExternal(ObjectInput in); void readExternalFromArray(ArrayInputStream in); void restoreToNull(); DataValueDescriptor cloneValue(boolean forceMaterialization); DataValueDescriptor getNewNull(); void setValueFromResultSet(ResultSet resultSet, int colNumber, boolean isNullable); final void setInto(PreparedStatement ps, int position); final void setInto(ResultSet rs, int position); void setValue(String theValue); void setValue(Number theValue); void setBigDecimal(Number bigDecimal); void setValue(float theValue); void setValue(int theValue); void setValue(long theValue); void setValue(double theValue); void setValue(boolean theValue); void setValue(Double theValue); int typePrecedence(); BooleanDataValue equals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue notEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessOrEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterOrEquals(DataValueDescriptor left, DataValueDescriptor right); NumberDataValue plus(NumberDataValue addend1, NumberDataValue addend2, NumberDataValue result); NumberDataValue minus(NumberDataValue left, NumberDataValue right, NumberDataValue result); NumberDataValue times(NumberDataValue left, NumberDataValue right, NumberDataValue result); NumberDataValue divide(NumberDataValue dividend, NumberDataValue divisor, NumberDataValue result); NumberDataValue minus(NumberDataValue result); String toString(); int hashCode(); int estimateMemoryUsage(); Format getFormat(); BigDecimal getBigDecimal(); @Override void read(Row row, int ordinal); @Override StructField getStructField(String columnName); void updateThetaSketch(UpdateSketch updateSketch); @Override void setSparkObject(Object sparkObject); }
@Test(expected = StandardException.class) public void testNegativeOverFlow() throws StandardException { SQLReal float1 = new SQLReal(Float.MIN_VALUE); SQLReal float2 = new SQLReal(1.0f); float1.minus(float1, float2, null); }
SQLLongint extends NumberDataType { public NumberDataValue plus(NumberDataValue addend1, NumberDataValue addend2, NumberDataValue result) throws StandardException { if (result == null) { result = new SQLLongint(); } if (addend1.isNull() || addend2.isNull()) { result.setToNull(); return result; } long addend1Long = addend1.getLong(); long addend2Long = addend2.getLong(); long resultValue = addend1Long + addend2Long; if ((addend1Long < 0) == (addend2Long < 0)) { if ((addend1Long < 0) != (resultValue < 0)) { throw StandardException.newException(SQLState.LANG_OUTSIDE_RANGE_FOR_DATATYPE, "BIGINT"); } } result.setValue(resultValue); return result; } SQLLongint(); SQLLongint(long val); private SQLLongint(long val, boolean isNullArg); SQLLongint(Long obj); int getInt(); byte getByte(); short getShort(); long getLong(); float getFloat(); double getDouble(); boolean getBoolean(); String getString(); Object getObject(); int getLength(); String getTypeName(); int getTypeFormatId(); void writeExternal(ObjectOutput out); void readExternal(ObjectInput in); void readExternalFromArray(ArrayInputStream in); void restoreToNull(); DataValueDescriptor cloneValue(boolean forceMaterialization); DataValueDescriptor getNewNull(); void setValueFromResultSet(ResultSet resultSet, int colNumber, boolean isNullable); final void setInto(PreparedStatement ps, int position); final void setInto(ResultSet rs, int position); void setValue(String theValue); final void setValue(Number theValue); void setValue(long theValue); void setValue(int theValue); void setValue(float theValue); void setValue(double theValue); void setValue(boolean theValue); void setValue(BigInteger theValue); int typePrecedence(); BooleanDataValue equals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue notEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessOrEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterOrEquals(DataValueDescriptor left, DataValueDescriptor right); NumberDataValue plus(NumberDataValue addend1, NumberDataValue addend2, NumberDataValue result); NumberDataValue minus(NumberDataValue left, NumberDataValue right, NumberDataValue result); NumberDataValue times(NumberDataValue left, NumberDataValue right, NumberDataValue result); NumberDataValue divide(NumberDataValue dividend, NumberDataValue divisor, NumberDataValue result); NumberDataValue mod(NumberDataValue dividend, NumberDataValue divisor, NumberDataValue result); NumberDataValue minus(NumberDataValue result); String toString(); int hashCode(); int estimateMemoryUsage(); Format getFormat(); BigDecimal getBigDecimal(); @Override void read(Row row, int ordinal); @Override StructField getStructField(String columnName); void updateThetaSketch(UpdateSketch updateSketch); @Override void setSparkObject(Object sparkObject); }
@Test(expected = StandardException.class) public void testPositiveOverFlow() throws StandardException { SQLLongint long1 = new SQLLongint(Long.MAX_VALUE); SQLLongint long2 = new SQLLongint(1); long1.plus(long1,long2,null); }
SQLLongint extends NumberDataType { public NumberDataValue minus(NumberDataValue left, NumberDataValue right, NumberDataValue result) throws StandardException { if (result == null) { result = new SQLLongint(); } if (left.isNull() || right.isNull()) { result.setToNull(); return result; } long diff = left.getLong() - right.getLong(); if ((left.getLong() < 0) != (right.getLong() < 0)) { if ((left.getLong() < 0) != (diff < 0)) { throw StandardException.newException(SQLState.LANG_OUTSIDE_RANGE_FOR_DATATYPE, "BIGINT"); } } result.setValue(diff); return result; } SQLLongint(); SQLLongint(long val); private SQLLongint(long val, boolean isNullArg); SQLLongint(Long obj); int getInt(); byte getByte(); short getShort(); long getLong(); float getFloat(); double getDouble(); boolean getBoolean(); String getString(); Object getObject(); int getLength(); String getTypeName(); int getTypeFormatId(); void writeExternal(ObjectOutput out); void readExternal(ObjectInput in); void readExternalFromArray(ArrayInputStream in); void restoreToNull(); DataValueDescriptor cloneValue(boolean forceMaterialization); DataValueDescriptor getNewNull(); void setValueFromResultSet(ResultSet resultSet, int colNumber, boolean isNullable); final void setInto(PreparedStatement ps, int position); final void setInto(ResultSet rs, int position); void setValue(String theValue); final void setValue(Number theValue); void setValue(long theValue); void setValue(int theValue); void setValue(float theValue); void setValue(double theValue); void setValue(boolean theValue); void setValue(BigInteger theValue); int typePrecedence(); BooleanDataValue equals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue notEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessOrEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterOrEquals(DataValueDescriptor left, DataValueDescriptor right); NumberDataValue plus(NumberDataValue addend1, NumberDataValue addend2, NumberDataValue result); NumberDataValue minus(NumberDataValue left, NumberDataValue right, NumberDataValue result); NumberDataValue times(NumberDataValue left, NumberDataValue right, NumberDataValue result); NumberDataValue divide(NumberDataValue dividend, NumberDataValue divisor, NumberDataValue result); NumberDataValue mod(NumberDataValue dividend, NumberDataValue divisor, NumberDataValue result); NumberDataValue minus(NumberDataValue result); String toString(); int hashCode(); int estimateMemoryUsage(); Format getFormat(); BigDecimal getBigDecimal(); @Override void read(Row row, int ordinal); @Override StructField getStructField(String columnName); void updateThetaSketch(UpdateSketch updateSketch); @Override void setSparkObject(Object sparkObject); }
@Test(expected = StandardException.class) public void testNegativeOverFlow() throws StandardException { SQLLongint long1 = new SQLLongint(Long.MIN_VALUE); SQLLongint long2 = new SQLLongint(1); long1.minus(long1, long2, null); }
SQLLongint extends NumberDataType { public void writeExternal(ObjectOutput out) throws IOException { out.writeBoolean(isNull); out.writeLong(value); } SQLLongint(); SQLLongint(long val); private SQLLongint(long val, boolean isNullArg); SQLLongint(Long obj); int getInt(); byte getByte(); short getShort(); long getLong(); float getFloat(); double getDouble(); boolean getBoolean(); String getString(); Object getObject(); int getLength(); String getTypeName(); int getTypeFormatId(); void writeExternal(ObjectOutput out); void readExternal(ObjectInput in); void readExternalFromArray(ArrayInputStream in); void restoreToNull(); DataValueDescriptor cloneValue(boolean forceMaterialization); DataValueDescriptor getNewNull(); void setValueFromResultSet(ResultSet resultSet, int colNumber, boolean isNullable); final void setInto(PreparedStatement ps, int position); final void setInto(ResultSet rs, int position); void setValue(String theValue); final void setValue(Number theValue); void setValue(long theValue); void setValue(int theValue); void setValue(float theValue); void setValue(double theValue); void setValue(boolean theValue); void setValue(BigInteger theValue); int typePrecedence(); BooleanDataValue equals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue notEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessOrEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterOrEquals(DataValueDescriptor left, DataValueDescriptor right); NumberDataValue plus(NumberDataValue addend1, NumberDataValue addend2, NumberDataValue result); NumberDataValue minus(NumberDataValue left, NumberDataValue right, NumberDataValue result); NumberDataValue times(NumberDataValue left, NumberDataValue right, NumberDataValue result); NumberDataValue divide(NumberDataValue dividend, NumberDataValue divisor, NumberDataValue result); NumberDataValue mod(NumberDataValue dividend, NumberDataValue divisor, NumberDataValue result); NumberDataValue minus(NumberDataValue result); String toString(); int hashCode(); int estimateMemoryUsage(); Format getFormat(); BigDecimal getBigDecimal(); @Override void read(Row row, int ordinal); @Override StructField getStructField(String columnName); void updateThetaSketch(UpdateSketch updateSketch); @Override void setSparkObject(Object sparkObject); }
@Test public void writeExternal() throws IOException { SQLLongint lint = new SQLLongint(42); MockObjectOutput moo = new MockObjectOutput(); lint.writeExternal(moo); Assert.assertFalse("Shouldn't be null", moo.isNull); Assert.assertTrue("Unexpected value", moo.value == 42); } @Test public void writeExternalNull() throws IOException { SQLLongint lint = new SQLLongint(); MockObjectOutput moo = new MockObjectOutput(); lint.writeExternal(moo); Assert.assertTrue("Should be null", moo.isNull); }
SQLLongint extends NumberDataType { public void readExternal(ObjectInput in) throws IOException { setIsNull(in.readBoolean()); value = in.readLong(); } SQLLongint(); SQLLongint(long val); private SQLLongint(long val, boolean isNullArg); SQLLongint(Long obj); int getInt(); byte getByte(); short getShort(); long getLong(); float getFloat(); double getDouble(); boolean getBoolean(); String getString(); Object getObject(); int getLength(); String getTypeName(); int getTypeFormatId(); void writeExternal(ObjectOutput out); void readExternal(ObjectInput in); void readExternalFromArray(ArrayInputStream in); void restoreToNull(); DataValueDescriptor cloneValue(boolean forceMaterialization); DataValueDescriptor getNewNull(); void setValueFromResultSet(ResultSet resultSet, int colNumber, boolean isNullable); final void setInto(PreparedStatement ps, int position); final void setInto(ResultSet rs, int position); void setValue(String theValue); final void setValue(Number theValue); void setValue(long theValue); void setValue(int theValue); void setValue(float theValue); void setValue(double theValue); void setValue(boolean theValue); void setValue(BigInteger theValue); int typePrecedence(); BooleanDataValue equals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue notEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessOrEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterOrEquals(DataValueDescriptor left, DataValueDescriptor right); NumberDataValue plus(NumberDataValue addend1, NumberDataValue addend2, NumberDataValue result); NumberDataValue minus(NumberDataValue left, NumberDataValue right, NumberDataValue result); NumberDataValue times(NumberDataValue left, NumberDataValue right, NumberDataValue result); NumberDataValue divide(NumberDataValue dividend, NumberDataValue divisor, NumberDataValue result); NumberDataValue mod(NumberDataValue dividend, NumberDataValue divisor, NumberDataValue result); NumberDataValue minus(NumberDataValue result); String toString(); int hashCode(); int estimateMemoryUsage(); Format getFormat(); BigDecimal getBigDecimal(); @Override void read(Row row, int ordinal); @Override StructField getStructField(String columnName); void updateThetaSketch(UpdateSketch updateSketch); @Override void setSparkObject(Object sparkObject); }
@Test public void readExternal() throws IOException { SQLLongint lint = new SQLLongint(); MockObjectInput moi = new MockObjectInput(); moi.isNull = false; moi.value = 42L; lint.readExternal(moi); Assert.assertFalse("Shouldn't be null", lint.isNull()); Assert.assertTrue("Unexpected value", lint.getLong() == 42); } @Test public void readExternalNull() throws IOException { SQLLongint lint = new SQLLongint(); MockObjectInput moi = new MockObjectInput(); moi.isNull = true; moi.value = 0L; lint.readExternal(moi); Assert.assertTrue("Should be null", lint.isNull()); }
SQLBoolean extends DataType implements BooleanDataValue { public boolean getBoolean() { return value; } SQLBoolean(); SQLBoolean(boolean val); SQLBoolean(Boolean obj); private SQLBoolean(boolean val, boolean isNull); boolean getBoolean(); byte getByte(); short getShort(); int getInt(); long getLong(); float getFloat(); double getDouble(); int typeToBigDecimal(); String getString(); Object getObject(); int getLength(); String getTypeName(); DataValueDescriptor recycle(); int getTypeFormatId(); void writeExternal(ObjectOutput out); void readExternal(ObjectInput in); void readExternalFromArray(ArrayInputStream in); void restoreToNull(); @SuppressFBWarnings(value="RV_NEGATING_RESULT_OF_COMPARETO", justification="Using compare method from dominant type") int compare(DataValueDescriptor other); boolean compare(int op, DataValueDescriptor other, boolean orderedNulls, boolean unknownRV); DataValueDescriptor cloneValue(boolean forceMaterialization); DataValueDescriptor getNewNull(); void setValueFromResultSet(ResultSet resultSet, int colNumber, boolean isNullable); final void setInto(PreparedStatement ps, int position); void setValue(boolean theValue); void setValue(Boolean theValue); void setValue(byte theValue); void setValue(short theValue); void setValue(int theValue); void setValue(long theValue); void setValue(float theValue); void setValue(double theValue); void setBigDecimal(Number bigDecimal); void setValue(String theValue); BooleanDataValue equals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue notEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessOrEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterOrEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue and(BooleanDataValue otherValue); BooleanDataValue or(BooleanDataValue otherValue); BooleanDataValue is(BooleanDataValue otherValue); BooleanDataValue isNot(BooleanDataValue otherValue); BooleanDataValue throwExceptionIfFalse( String sqlState, String tableName, String constraintName); int typePrecedence(); static SQLBoolean truthValue( DataValueDescriptor leftOperand, DataValueDescriptor rightOperand, boolean truth); static SQLBoolean truthValue( DataValueDescriptor leftOperand, DataValueDescriptor rightOperand, Boolean truth); static SQLBoolean truthValue(boolean value); static SQLBoolean unknownTruthValue(); static SQLBoolean falseTruthValue(); static SQLBoolean trueTruthValue(); boolean equals(boolean val); BooleanDataValue getImmutable(); String toString(); int hashCode(); int estimateMemoryUsage(); Format getFormat(); @Override void read(Row row, int ordinal); @Override StructField getStructField(String columnName); @Override void updateThetaSketch(UpdateSketch updateSketch); @Override void setSparkObject(Object sparkObject); static final byte F; static final byte T; }
@Test public void rowValueToDVDValue() throws Exception { SQLBoolean bool1 = new SQLBoolean(true); SQLBoolean bool2 = new SQLBoolean(); ExecRow execRow = new ValueRow(2); execRow.setColumn(1, bool1); execRow.setColumn(2, bool2); Assert.assertEquals(true, ((Row) execRow).getBoolean(0)); Assert.assertTrue(((Row) execRow).isNullAt(1)); Row sparkRow = execRow.getSparkRow(); Assert.assertEquals(sparkRow.getBoolean(0), true); Assert.assertTrue(sparkRow.isNullAt(1)); }
SQLDecimal extends NumberDataType implements VariableSizeDataValue { @Override public void setSparkObject(Object sparkObject) throws StandardException { if (sparkObject == null) setToNull(); else { value = (BigDecimal) sparkObject; setIsNull(false); } } SQLDecimal(); SQLDecimal(BigDecimal val); SQLDecimal(BigDecimal val, int precision, int scale); SQLDecimal(String val); int estimateMemoryUsage(); int getInt(); byte getByte(); short getShort(); long getLong(); float getFloat(); double getDouble(); BigDecimal getBigDecimal(); int typeToBigDecimal(); boolean getBoolean(); String getString(); Object getSparkObject(); @Override Object getObject(); void setValue(Double theValue); int getLength(); String getTypeName(); int getTypeFormatId(); void writeExternal(ObjectOutput out); void readExternal(ObjectInput in); void readExternalFromArray(ArrayInputStream in); void restoreToNull(); DataValueDescriptor cloneValue(boolean forceMaterialization); DataValueDescriptor getNewNull(); void setValueFromResultSet(ResultSet resultSet, int colNumber, boolean isNullable); final void setInto(PreparedStatement ps, int position); void setValue(String theValue); void setValue(double theValue); void setValue(float theValue); void setValue(long theValue); void setValue(int theValue); void setValue(BigDecimal theValue); void setBigDecimal(Number theValue); void setValue(Number theValue); void setValue(boolean theValue); int typePrecedence(); void normalize( DataTypeDescriptor desiredType, DataValueDescriptor source); NumberDataValue plus(NumberDataValue addend1, NumberDataValue addend2, NumberDataValue result); NumberDataValue minus(NumberDataValue left, NumberDataValue right, NumberDataValue result); NumberDataValue times(NumberDataValue left, NumberDataValue right, NumberDataValue result); NumberDataValue divide(NumberDataValue dividend, NumberDataValue divisor, NumberDataValue result); NumberDataValue divide(NumberDataValue dividend, NumberDataValue divisor, NumberDataValue result, int scale); NumberDataValue minus(NumberDataValue result); String toString(); int hashCode(); void setWidth(int desiredPrecision, int desiredScale, boolean errorOnTrunc); int getDecimalValuePrecision(); int getDecimalValueScale(); static BigDecimal getBigDecimal(DataValueDescriptor value); Format getFormat(); @Override void read(Row row, int ordinal); int getPrecision(); void setPrecision(int precision); int getScale(); void setScale(int scale); @Override StructField getStructField(String columnName); void updateThetaSketch(UpdateSketch updateSketch); @Override void setSparkObject(Object sparkObject); public int precision; public int scale; }
@Test public void testExecRowSparkRowConversion() throws StandardException { ValueRow execRow = new ValueRow(1); double initialValue = 10d; double val; for (int i = 1; i <= 38; i++) { val = Math.pow(initialValue, i); execRow.setRowArray(new DataValueDescriptor[]{new SQLDecimal(new BigDecimal(val))}); Row row = execRow.getSparkRow(); Assert.assertEquals(new BigDecimal(val), row.getDecimal(0)); ValueRow execRow2 = new ValueRow(1); execRow2.setRowArray(new DataValueDescriptor[]{new SQLDecimal()}); execRow2.getColumn(1).setSparkObject(row.get(0)); Assert.assertEquals("ExecRow Mismatch", execRow, execRow2); } }
SQLInteger extends NumberDataType { public int getInt() { return value; } SQLInteger(); SQLInteger(int val); SQLInteger(char val); SQLInteger(Integer obj); int getInt(); byte getByte(); short getShort(); long getLong(); float getFloat(); double getDouble(); boolean getBoolean(); String getString(); Object getObject(); int getLength(); String getTypeName(); int getTypeFormatId(); void writeExternal(ObjectOutput out); final void readExternal(ObjectInput in); final void readExternalFromArray(ArrayInputStream in); void restoreToNull(); DataValueDescriptor cloneValue(boolean forceMaterialization); DataValueDescriptor getNewNull(); void setValueFromResultSet(ResultSet resultSet, int colNumber, boolean isNullable); final void setInto(PreparedStatement ps, int position); final void setInto(ResultSet rs, int position); void setValue(String theValue); void setValue(int theValue); void setValue(Integer theValue); void setValue(long theValue); void setValue(float theValue); void setValue(double theValue); void setValue(boolean theValue); int typePrecedence(); BooleanDataValue equals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue notEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessOrEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterOrEquals(DataValueDescriptor left, DataValueDescriptor right); NumberDataValue times(NumberDataValue left, NumberDataValue right, NumberDataValue result); NumberDataValue mod(NumberDataValue dividend, NumberDataValue divisor, NumberDataValue result); NumberDataValue minus(NumberDataValue result); String toString(); int hashCode(); int estimateMemoryUsage(); Format getFormat(); BigDecimal getBigDecimal(); @Override void read(Row row, int ordinal); @Override StructField getStructField(String columnName); void updateThetaSketch(UpdateSketch updateSketch); @Override void setSparkObject(Object sparkObject); }
@Test public void addTwo() throws StandardException { SQLInteger integer1 = new SQLInteger(100); SQLInteger integer2 = new SQLInteger(100); Assert.assertEquals("Integer Add Fails", 200, integer1.plus(integer1, integer2, null).getInt(),0); } @Test public void rowValueToDVDValue() throws Exception { SQLInteger int1 = new SQLInteger(10); SQLInteger int2 = new SQLInteger(); ExecRow execRow = new ValueRow(2); execRow.setColumn(1, int1); execRow.setColumn(2, int2); Assert.assertEquals(10, ((Row) execRow).getInt(0)); Assert.assertTrue(((Row) execRow).isNullAt(1)); Row sparkRow = execRow.getSparkRow(); Assert.assertEquals(sparkRow.getInt(0), 10); Assert.assertTrue(sparkRow.isNullAt(1)); }
SQLInteger extends NumberDataType { public NumberDataValue minus(NumberDataValue result) throws StandardException { int operandValue; if (result == null) { result = new SQLInteger(); } if (this.isNull()) { result.setToNull(); return result; } operandValue = this.getInt(); if (operandValue == Integer.MIN_VALUE) { throw outOfRange(); } result.setValue(-operandValue); return result; } SQLInteger(); SQLInteger(int val); SQLInteger(char val); SQLInteger(Integer obj); int getInt(); byte getByte(); short getShort(); long getLong(); float getFloat(); double getDouble(); boolean getBoolean(); String getString(); Object getObject(); int getLength(); String getTypeName(); int getTypeFormatId(); void writeExternal(ObjectOutput out); final void readExternal(ObjectInput in); final void readExternalFromArray(ArrayInputStream in); void restoreToNull(); DataValueDescriptor cloneValue(boolean forceMaterialization); DataValueDescriptor getNewNull(); void setValueFromResultSet(ResultSet resultSet, int colNumber, boolean isNullable); final void setInto(PreparedStatement ps, int position); final void setInto(ResultSet rs, int position); void setValue(String theValue); void setValue(int theValue); void setValue(Integer theValue); void setValue(long theValue); void setValue(float theValue); void setValue(double theValue); void setValue(boolean theValue); int typePrecedence(); BooleanDataValue equals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue notEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterThan(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue lessOrEquals(DataValueDescriptor left, DataValueDescriptor right); BooleanDataValue greaterOrEquals(DataValueDescriptor left, DataValueDescriptor right); NumberDataValue times(NumberDataValue left, NumberDataValue right, NumberDataValue result); NumberDataValue mod(NumberDataValue dividend, NumberDataValue divisor, NumberDataValue result); NumberDataValue minus(NumberDataValue result); String toString(); int hashCode(); int estimateMemoryUsage(); Format getFormat(); BigDecimal getBigDecimal(); @Override void read(Row row, int ordinal); @Override StructField getStructField(String columnName); void updateThetaSketch(UpdateSketch updateSketch); @Override void setSparkObject(Object sparkObject); }
@Test(expected = StandardException.class) public void testNegativeOverFlow() throws StandardException { SQLInteger integer1 = new SQLInteger(Integer.MIN_VALUE); SQLInteger integer2 = new SQLInteger(1); integer1.minus(integer1, integer2, null); }
UniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long nullCount() { return nullCount; } UniqueKeyStatisticsImpl(ExecRow execRow); UniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, long nullCount ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }
@Test public void testNullCount() throws StandardException { Assert.assertEquals(0, impl.nullCount()); }
UniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long notNullCount() { return quantilesSketch.getN(); } UniqueKeyStatisticsImpl(ExecRow execRow); UniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, long nullCount ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }
@Test public void testNotNullCount() throws StandardException { Assert.assertEquals(10000,impl.notNullCount()); }
UniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long totalCount() { return quantilesSketch.getN()+nullCount; } UniqueKeyStatisticsImpl(ExecRow execRow); UniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, long nullCount ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }
@Test public void testTotalCount() throws StandardException { Assert.assertEquals(10000,impl.totalCount()); }
UniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public ExecRow maxValue() { return quantilesSketch.getMaxValue(); } UniqueKeyStatisticsImpl(ExecRow execRow); UniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, long nullCount ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }
@Test public void testMaxValue() throws StandardException { Assert.assertEquals(maxRow,impl.maxValue()); }
UniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public ExecRow minValue() { return quantilesSketch.getMinValue(); } UniqueKeyStatisticsImpl(ExecRow execRow); UniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, long nullCount ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }
@Test public void testMinValue() throws StandardException { Assert.assertEquals(minRow,impl.minValue()); }
UniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long selectivity(ExecRow element) { return 1L; } UniqueKeyStatisticsImpl(ExecRow execRow); UniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, long nullCount ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }
@Test public void testNullSelectivity() throws StandardException { Assert.assertEquals(1,impl.selectivity(null)); } @Test public void testEmptySelectivity() throws StandardException { Assert.assertEquals(1,impl.selectivity(new ValueRow(3))); } @Test public void testIndividualSelectivity() throws StandardException { Assert.assertEquals(1,impl.selectivity(minRow)); }
UniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation) { double startSelectivity = start==null?0.0d:quantilesSketch.getCDF(new ExecRow[]{start})[0]; double stopSelectivity = stop==null?1.0d:quantilesSketch.getCDF(new ExecRow[]{stop})[0]; return (long) ((stopSelectivity-startSelectivity)*quantilesSketch.getN()); } UniqueKeyStatisticsImpl(ExecRow execRow); UniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, long nullCount ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }
@Test public void testRangeSelectivity() throws StandardException { Assert.assertEquals(4000.0d,(double) impl.rangeSelectivity(row2000,row6000,true,false),50.0d); } @Test public void testNullBeginSelectivity() throws StandardException { Assert.assertEquals(6000.0d,(double) impl.rangeSelectivity(null,row6000,true,false),50.0d); } @Test public void testNullEndSelectivity() throws StandardException { Assert.assertEquals(8000.0d,(double) impl.rangeSelectivity(row2000,null,true,false),50.0d); } @Test public void testFullScanSelectivity() throws StandardException { Assert.assertEquals(10000.0d,(double) impl.rangeSelectivity(null,null,true,false),50.0d); }
PrimaryKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long nullCount() { return nullCount; } PrimaryKeyStatisticsImpl(ExecRow execRow); PrimaryKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, long nullCount ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }
@Test public void testNullCount() throws StandardException { Assert.assertEquals(0, impl.nullCount()); }
PrimaryKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long notNullCount() { return quantilesSketch.getN(); } PrimaryKeyStatisticsImpl(ExecRow execRow); PrimaryKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, long nullCount ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }
@Test public void testNotNullCount() throws StandardException { Assert.assertEquals(10000,impl.notNullCount()); }
PrimaryKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long totalCount() { return quantilesSketch.getN()+nullCount; } PrimaryKeyStatisticsImpl(ExecRow execRow); PrimaryKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, long nullCount ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }
@Test public void testTotalCount() throws StandardException { Assert.assertEquals(10000,impl.totalCount()); }
PrimaryKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public ExecRow maxValue() { return quantilesSketch.getMaxValue(); } PrimaryKeyStatisticsImpl(ExecRow execRow); PrimaryKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, long nullCount ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }
@Test public void testMaxValue() throws StandardException { Assert.assertEquals(maxRow,impl.maxValue()); }
PrimaryKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public ExecRow minValue() { return quantilesSketch.getMinValue(); } PrimaryKeyStatisticsImpl(ExecRow execRow); PrimaryKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, long nullCount ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }
@Test public void testMinValue() throws StandardException { Assert.assertEquals(minRow,impl.minValue()); }
PrimaryKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long selectivity(ExecRow element) { return 1L; } PrimaryKeyStatisticsImpl(ExecRow execRow); PrimaryKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, long nullCount ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }
@Test public void testNullSelectivity() throws StandardException { Assert.assertEquals(1,impl.selectivity(null)); } @Test public void testEmptySelectivity() throws StandardException { Assert.assertEquals(1,impl.selectivity(new ValueRow(3))); } @Test public void testIndividualSelectivity() throws StandardException { Assert.assertEquals(1,impl.selectivity(minRow)); }
PrimaryKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation) { double startSelectivity = start==null?0.0d:quantilesSketch.getCDF(new ExecRow[]{start})[0]; double stopSelectivity = stop==null?1.0d:quantilesSketch.getCDF(new ExecRow[]{stop})[0]; return (long) ((stopSelectivity-startSelectivity)*quantilesSketch.getN()); } PrimaryKeyStatisticsImpl(ExecRow execRow); PrimaryKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, long nullCount ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }
@Test public void testRangeSelectivity() throws StandardException { Assert.assertEquals(4000.0d,(double) impl.rangeSelectivity(row2000,row6000,true,false),50.0d); } @Test public void testNullBeginSelectivity() throws StandardException { Assert.assertEquals(6000.0d,(double) impl.rangeSelectivity(null,row6000,true,false),50.0d); } @Test public void testNullEndSelectivity() throws StandardException { Assert.assertEquals(8000.0d,(double) impl.rangeSelectivity(row2000,null,true,false),50.0d); } @Test public void testFullScanSelectivity() throws StandardException { Assert.assertEquals(10000.0d,(double) impl.rangeSelectivity(null,null,true,false),50.0d); }
NonUniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long nullCount() { return 0; } NonUniqueKeyStatisticsImpl(ExecRow execRow); NonUniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, com.yahoo.sketches.frequencies.ItemsSketch<ExecRow> frequenciesSketch, Sketch thetaSketch ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }
@Test public void testNullCount() throws StandardException { Assert.assertEquals(0, impl.nullCount()); }
NonUniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long notNullCount() { return quantilesSketch.getN(); } NonUniqueKeyStatisticsImpl(ExecRow execRow); NonUniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, com.yahoo.sketches.frequencies.ItemsSketch<ExecRow> frequenciesSketch, Sketch thetaSketch ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }
@Test public void testNotNullCount() throws StandardException { Assert.assertEquals(10000,impl.notNullCount()); }
NonUniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long totalCount() { return quantilesSketch.getN(); } NonUniqueKeyStatisticsImpl(ExecRow execRow); NonUniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, com.yahoo.sketches.frequencies.ItemsSketch<ExecRow> frequenciesSketch, Sketch thetaSketch ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }
@Test public void testTotalCount() throws StandardException { Assert.assertEquals(10000,impl.totalCount()); }
NonUniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public ExecRow maxValue() { return quantilesSketch.getMaxValue(); } NonUniqueKeyStatisticsImpl(ExecRow execRow); NonUniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, com.yahoo.sketches.frequencies.ItemsSketch<ExecRow> frequenciesSketch, Sketch thetaSketch ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }
@Test public void testMaxValue() throws StandardException { Assert.assertEquals(maxRow,impl.maxValue()); }
NonUniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public ExecRow minValue() { return quantilesSketch.getMinValue(); } NonUniqueKeyStatisticsImpl(ExecRow execRow); NonUniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, com.yahoo.sketches.frequencies.ItemsSketch<ExecRow> frequenciesSketch, Sketch thetaSketch ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }
@Test public void testMinValue() throws StandardException { Assert.assertEquals(minRow,impl.minValue()); }
NonUniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long selectivity(ExecRow element) { long count = frequenciesSketch.getEstimate(element); if (count>0) return count; return (long) (quantilesSketch.getN()/thetaSketch.getEstimate()); } NonUniqueKeyStatisticsImpl(ExecRow execRow); NonUniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, com.yahoo.sketches.frequencies.ItemsSketch<ExecRow> frequenciesSketch, Sketch thetaSketch ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }
@Test public void testNullSelectivity() throws StandardException { Assert.assertEquals(1,impl.selectivity(null)); } @Test public void testEmptySelectivity() throws StandardException { Assert.assertEquals(1,impl.selectivity(new ValueRow(3))); } @Test public void testIndividualSelectivity() throws StandardException { Assert.assertEquals(1,impl.selectivity(minRow)); }
NonUniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation) { double startSelectivity = start==null?0.0d:quantilesSketch.getCDF(new ExecRow[]{start})[0]; double stopSelectivity = stop==null?1.0d:quantilesSketch.getCDF(new ExecRow[]{stop})[0]; return (long) ((stopSelectivity-startSelectivity)*quantilesSketch.getN()); } NonUniqueKeyStatisticsImpl(ExecRow execRow); NonUniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, com.yahoo.sketches.frequencies.ItemsSketch<ExecRow> frequenciesSketch, Sketch thetaSketch ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }
@Test public void testRangeSelectivity() throws StandardException { Assert.assertEquals(4000.0d,(double) impl.rangeSelectivity(row2000,row6000,true,false),50.0d); } @Test public void testNullBeginSelectivity() throws StandardException { Assert.assertEquals(6000.0d,(double) impl.rangeSelectivity(null,row6000,true,false),50.0d); } @Test public void testNullEndSelectivity() throws StandardException { Assert.assertEquals(8000.0d,(double) impl.rangeSelectivity(row2000,null,true,false),50.0d); } @Test public void testFullScanSelectivity() throws StandardException { Assert.assertEquals(10000.0d,(double) impl.rangeSelectivity(null,null,true,false),50.0d); }
CurrentDatetime { public Date getCurrentDate() { if (currentDate == null) { setCurrentDatetime(); currentDate = Date.valueOf(currentDateTime.toLocalDate()); } return currentDate; } CurrentDatetime(); Date getCurrentDate(); Time getCurrentTime(); Timestamp getCurrentTimestamp(); void forget(); int getTimestampPrecision(); void setTimestampPrecision(int timestampPrecision); }
@Test public void testGetCurrentDate() { LocalDate local = LocalDate.now(); Date date = cut.getCurrentDate(); long difference = ChronoUnit.DAYS.between(local, date.toLocalDate()); assertTrue(difference <= 1); }
CurrentDatetime { public Time getCurrentTime() { if (currentTime == null) { setCurrentDatetime(); currentTime = Time.valueOf(currentDateTime.toLocalTime()); } return currentTime; } CurrentDatetime(); Date getCurrentDate(); Time getCurrentTime(); Timestamp getCurrentTimestamp(); void forget(); int getTimestampPrecision(); void setTimestampPrecision(int timestampPrecision); }
@Test public void testGetCurrentTime() { LocalTime local = LocalTime.now(); Time time = cut.getCurrentTime(); long difference = ChronoUnit.SECONDS.between(local, time.toLocalTime()); assertTrue(difference <= 1); }
CurrentDatetime { public Timestamp getCurrentTimestamp() { if (currentTimestamp == null) { setCurrentDatetime(); currentTimestamp = Timestamp.valueOf(currentDateTime); int mask = POWERS_OF_10[9 - timestampPrecision]; int newNanos = currentTimestamp.getNanos() / mask * mask; currentTimestamp.setNanos(newNanos); } return currentTimestamp; } CurrentDatetime(); Date getCurrentDate(); Time getCurrentTime(); Timestamp getCurrentTimestamp(); void forget(); int getTimestampPrecision(); void setTimestampPrecision(int timestampPrecision); }
@Test public void testGetCurrentTimestamp() { LocalDateTime local = LocalDateTime.now(); Timestamp timestamp = cut.getCurrentTimestamp(); long difference = ChronoUnit.MILLIS.between(local, timestamp.toLocalDateTime()); assertTrue(difference <= 500); }