提交 0a4e9192 authored 作者: Andrei Tokar's avatar Andrei Tokar

Merge remote-tracking branch 'h2database/master' into append-single

...@@ -109,6 +109,12 @@ ...@@ -109,6 +109,12 @@
<version>4.12</version> <version>4.12</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>6.1</version>
<scope>test</scope>
</dependency>
<!-- END TEST DEPENDENCIES !--> <!-- END TEST DEPENDENCIES !-->
</dependencies> </dependencies>
......
...@@ -21,6 +21,14 @@ Change Log ...@@ -21,6 +21,14 @@ Change Log
<h2>Next Version (unreleased)</h2> <h2>Next Version (unreleased)</h2>
<ul> <ul>
<li>Issue #1618: GROUP BY does not work with two identical columns in selected expressions
</li>
<li>Issue #1619: Two-phase commit regression in MASTER
</li>
<li>PR #1626: fix doc
</li>
<li>PR #1625: Prepare to release: javadoc cleanup, fix maven build, fix javadoc build
</li>
<li>Issue #1620: UUIDs are unexpectedly sorted as signed <li>Issue #1620: UUIDs are unexpectedly sorted as signed
</li> </li>
<li>PR #1614: Use bulk .addAll() operation <li>PR #1614: Use bulk .addAll() operation
......
...@@ -6940,6 +6940,13 @@ public class Parser { ...@@ -6940,6 +6940,13 @@ public class Parser {
return command; return command;
} }
/**
* Checks the table is the DUAL special table.
*
* @param tableName table name.
* @return {@code true} if the table is DUAL special table. Otherwise returns {@code false}.
* @see <a href="https://en.wikipedia.org/wiki/DUAL_table">Wikipedia: DUAL table</a>
*/
boolean isDualTable(String tableName) { boolean isDualTable(String tableName) {
return ((schemaName == null || equalsToken(schemaName, "SYS")) && equalsToken("DUAL", tableName)) return ((schemaName == null || equalsToken(schemaName, "SYS")) && equalsToken("DUAL", tableName))
|| (database.getMode().sysDummy1 && (schemaName == null || equalsToken(schemaName, "SYSIBM")) || (database.getMode().sysDummy1 && (schemaName == null || equalsToken(schemaName, "SYSIBM"))
......
...@@ -52,8 +52,14 @@ public abstract class Query extends Prepared { ...@@ -52,8 +52,14 @@ public abstract class Query extends Prepared {
*/ */
Expression[] expressionArray; Expression[] expressionArray;
/**
* Describes elements of the ORDER BY clause of a query.
*/
ArrayList<SelectOrderBy> orderList; ArrayList<SelectOrderBy> orderList;
/**
* A sort order represents an ORDER BY clause in a query.
*/
SortOrder sort; SortOrder sort;
/** /**
...@@ -459,6 +465,18 @@ public abstract class Query extends Prepared { ...@@ -459,6 +465,18 @@ public abstract class Query extends Prepared {
} }
} }
/**
* Initialize the 'ORDER BY' or 'DISTINCT' expressions.
*
* @param session the session
* @param expressions the select list expressions
* @param expressionSQL the select list SQL snippets
* @param e the expression.
* @param visible the number of visible columns in the select list
* @param mustBeInResult all order by expressions must be in the select list
* @param filters the table filters.
* @return index on the expression in the {@link #expressions} list.
*/
static int initExpression(Session session, ArrayList<Expression> expressions, static int initExpression(Session session, ArrayList<Expression> expressions,
ArrayList<String> expressionSQL, Expression e, int visible, boolean mustBeInResult, ArrayList<String> expressionSQL, Expression e, int visible, boolean mustBeInResult,
ArrayList<TableFilter> filters) { ArrayList<TableFilter> filters) {
...@@ -690,6 +708,11 @@ public abstract class Query extends Prepared { ...@@ -690,6 +708,11 @@ public abstract class Query extends Prepared {
return visitor.getMaxDataModificationId(); return visitor.getMaxDataModificationId();
} }
/**
* Appends query limits info to the plan.
*
* @param buff query plan string builder.
*/
void appendLimitToSQL(StringBuilder buff) { void appendLimitToSQL(StringBuilder buff) {
if (offsetExpr != null) { if (offsetExpr != null) {
String count = StringUtils.unEnclose(offsetExpr.getSQL()); String count = StringUtils.unEnclose(offsetExpr.getSQL());
......
...@@ -108,6 +108,9 @@ public class Select extends Query { ...@@ -108,6 +108,9 @@ public class Select extends Query {
SelectGroups groupData; SelectGroups groupData;
private int havingIndex; private int havingIndex;
private int[] groupByCopies;
boolean isGroupQuery; boolean isGroupQuery;
private boolean isGroupSortedQuery; private boolean isGroupSortedQuery;
private boolean isWindowQuery; private boolean isWindowQuery;
...@@ -462,7 +465,8 @@ public class Select extends Query { ...@@ -462,7 +465,8 @@ public class Select extends Query {
void updateAgg(int columnCount, int stage) { void updateAgg(int columnCount, int stage) {
for (int i = 0; i < columnCount; i++) { for (int i = 0; i < columnCount; i++) {
if (groupByExpression == null || !groupByExpression[i]) { if ((groupByExpression == null || !groupByExpression[i])
&& (groupByCopies == null || groupByCopies[i] < 0)) {
Expression expr = expressions.get(i); Expression expr = expressions.get(i);
expr.updateAggregate(session, stage); expr.updateAggregate(session, stage);
} }
...@@ -480,6 +484,13 @@ public class Select extends Query { ...@@ -480,6 +484,13 @@ public class Select extends Query {
if (groupByExpression != null && groupByExpression[j]) { if (groupByExpression != null && groupByExpression[j]) {
continue; continue;
} }
if (groupByCopies != null) {
int original = groupByCopies[j];
if (original >= 0) {
row[j] = row[original];
continue;
}
}
Expression expr = expressions.get(j); Expression expr = expressions.get(j);
row[j] = expr.getValue(session); row[j] = expr.getValue(session);
} }
...@@ -1047,7 +1058,7 @@ public class Select extends Query { ...@@ -1047,7 +1058,7 @@ public class Select extends Query {
for (int j = 0; j < expSize; j++) { for (int j = 0; j < expSize; j++) {
String s2 = expressionSQL.get(j); String s2 = expressionSQL.get(j);
if (db.equalsIdentifiers(s2, sql)) { if (db.equalsIdentifiers(s2, sql)) {
found = j; found = mergeGroupByExpressions(db, j, expressionSQL, false);
break; break;
} }
} }
...@@ -1056,12 +1067,12 @@ public class Select extends Query { ...@@ -1056,12 +1067,12 @@ public class Select extends Query {
for (int j = 0; j < expSize; j++) { for (int j = 0; j < expSize; j++) {
Expression e = expressions.get(j); Expression e = expressions.get(j);
if (db.equalsIdentifiers(sql, e.getAlias())) { if (db.equalsIdentifiers(sql, e.getAlias())) {
found = j; found = mergeGroupByExpressions(db, j, expressionSQL, true);
break; break;
} }
sql = expr.getAlias(); sql = expr.getAlias();
if (db.equalsIdentifiers(sql, e.getAlias())) { if (db.equalsIdentifiers(sql, e.getAlias())) {
found = j; found = mergeGroupByExpressions(db, j, expressionSQL, true);
break; break;
} }
} }
...@@ -1074,6 +1085,14 @@ public class Select extends Query { ...@@ -1074,6 +1085,14 @@ public class Select extends Query {
groupIndex[i] = found; groupIndex[i] = found;
} }
} }
checkUsed: if (groupByCopies != null) {
for (int i : groupByCopies) {
if (i >= 0) {
break checkUsed;
}
}
groupByCopies = null;
}
groupByExpression = new boolean[expressions.size()]; groupByExpression = new boolean[expressions.size()];
for (int gi : groupIndex) { for (int gi : groupIndex) {
groupByExpression[gi] = true; groupByExpression[gi] = true;
...@@ -1092,6 +1111,50 @@ public class Select extends Query { ...@@ -1092,6 +1111,50 @@ public class Select extends Query {
checkInit = true; checkInit = true;
} }
private int mergeGroupByExpressions(Database db, int index, ArrayList<String> expressionSQL, boolean scanPrevious)
{
/*
* -1: uniqueness of expression is not known yet
*
* -2: expression that is used as a source for a copy or does not have
* copies
*
* >=0: expression is a copy of expression at this index
*/
if (groupByCopies != null) {
int c = groupByCopies[index];
if (c >= 0) {
return c;
} else if (c == -2) {
return index;
}
} else {
groupByCopies = new int[expressionSQL.size()];
Arrays.fill(groupByCopies, -1);
}
String sql = expressionSQL.get(index);
if (scanPrevious) {
/*
* If expression was matched using an alias previous expressions may
* be identical.
*/
for (int i = 0; i < index; i++) {
if (db.equalsIdentifiers(sql, expressionSQL.get(i))) {
index = i;
break;
}
}
}
int l = expressionSQL.size();
for (int i = index + 1; i < l; i++) {
if (db.equalsIdentifiers(sql, expressionSQL.get(i))) {
groupByCopies[i] = index;
}
}
groupByCopies[index] = -2;
return index;
}
@Override @Override
public void prepare() { public void prepare() {
if (isPrepared) { if (isPrepared) {
......
...@@ -194,8 +194,14 @@ public abstract class SelectGroups { ...@@ -194,8 +194,14 @@ public abstract class SelectGroups {
} }
} }
/**
* The session.
*/
final Session session; final Session session;
/**
* The query's column list, including invisible expressions such as order by expressions.
*/
final ArrayList<Expression> expressions; final ArrayList<Expression> expressions;
/** /**
...@@ -235,6 +241,7 @@ public abstract class SelectGroups { ...@@ -235,6 +241,7 @@ public abstract class SelectGroups {
* is this query is a group query * is this query is a group query
* @param groupIndex * @param groupIndex
* the indexes of group expressions, or null * the indexes of group expressions, or null
* @return new instance of the grouped data.
*/ */
public static SelectGroups getInstance(Session session, ArrayList<Expression> expressions, boolean isGroupQuery, public static SelectGroups getInstance(Session session, ArrayList<Expression> expressions, boolean isGroupQuery,
int[] groupIndex) { int[] groupIndex) {
...@@ -247,7 +254,10 @@ public abstract class SelectGroups { ...@@ -247,7 +254,10 @@ public abstract class SelectGroups {
} }
/** /**
* Is there currently a group-by active * Is there currently a group-by active.
*
* @return {@code true} if there is currently a group-by active,
* otherwise returns {@code false}.
*/ */
public boolean isCurrentGroup() { public boolean isCurrentGroup() {
return currentGroupByExprData != null; return currentGroupByExprData != null;
...@@ -273,7 +283,7 @@ public abstract class SelectGroups { ...@@ -273,7 +283,7 @@ public abstract class SelectGroups {
* *
* @param expr * @param expr
* expression * expression
* @param object * @param obj
* expression data to set * expression data to set
*/ */
public final void setCurrentGroupExprData(Expression expr, Object obj) { public final void setCurrentGroupExprData(Expression expr, Object obj) {
...@@ -292,6 +302,11 @@ public abstract class SelectGroups { ...@@ -292,6 +302,11 @@ public abstract class SelectGroups {
currentGroupByExprData[index] = obj; currentGroupByExprData[index] = obj;
} }
/**
* Creates new object arrays to holds group-by data.
*
* @return new object array to holds group-by data.
*/
final Object[] createRow() { final Object[] createRow() {
return new Object[Math.max(exprToIndexInGroupByData.size(), expressions.size())]; return new Object[Math.max(exprToIndexInGroupByData.size(), expressions.size())];
} }
...@@ -321,7 +336,7 @@ public abstract class SelectGroups { ...@@ -321,7 +336,7 @@ public abstract class SelectGroups {
* expression * expression
* @param partitionKey * @param partitionKey
* a key of partition * a key of partition
* @param object * @param obj
* window expression data to set * window expression data to set
*/ */
public final void setWindowExprData(DataAnalysisOperation expr, Value partitionKey, PartitionData obj) { public final void setWindowExprData(DataAnalysisOperation expr, Value partitionKey, PartitionData obj) {
...@@ -338,6 +353,9 @@ public abstract class SelectGroups { ...@@ -338,6 +353,9 @@ public abstract class SelectGroups {
} }
} }
/**
* Update group-by data specified by implementation.
*/
abstract void updateCurrentGroupExprData(); abstract void updateCurrentGroupExprData();
/** /**
...@@ -412,4 +430,10 @@ public abstract class SelectGroups { ...@@ -412,4 +430,10 @@ public abstract class SelectGroups {
currentGroupRowId++; currentGroupRowId++;
} }
/**
* @return Expressions.
*/
public ArrayList<Expression> expressions() {
return expressions;
}
} }
...@@ -22,6 +22,11 @@ class OnExitDatabaseCloser extends Thread { ...@@ -22,6 +22,11 @@ class OnExitDatabaseCloser extends Thread {
private static boolean terminated; private static boolean terminated;
/**
* Register database instance to close one on the JVM process shutdown.
*
* @param db Database instance.
*/
static synchronized void register(Database db) { static synchronized void register(Database db) {
if (terminated) { if (terminated) {
// Shutdown in progress // Shutdown in progress
...@@ -46,6 +51,11 @@ class OnExitDatabaseCloser extends Thread { ...@@ -46,6 +51,11 @@ class OnExitDatabaseCloser extends Thread {
} }
} }
/**
* Unregister database instance.
*
* @param db Database instance.
*/
static synchronized void unregister(Database db) { static synchronized void unregister(Database db) {
if (terminated) { if (terminated) {
// Shutdown in progress, do nothing // Shutdown in progress, do nothing
......
...@@ -34,7 +34,7 @@ import org.h2.mvstore.db.MVTable; ...@@ -34,7 +34,7 @@ import org.h2.mvstore.db.MVTable;
import org.h2.mvstore.db.MVTableEngine; import org.h2.mvstore.db.MVTableEngine;
import org.h2.mvstore.tx.Transaction; import org.h2.mvstore.tx.Transaction;
import org.h2.mvstore.tx.TransactionStore; import org.h2.mvstore.tx.TransactionStore;
import org.h2.mvstore.tx.VersionedValue; import org.h2.value.VersionedValue;
import org.h2.result.ResultInterface; import org.h2.result.ResultInterface;
import org.h2.result.Row; import org.h2.result.Row;
import org.h2.result.SortOrder; import org.h2.result.SortOrder;
...@@ -1830,7 +1830,7 @@ public class Session extends SessionWithState implements TransactionStore.Rollba ...@@ -1830,7 +1830,7 @@ public class Session extends SessionWithState implements TransactionStore.Rollba
private static Row getRowFromVersionedValue(MVTable table, long recKey, private static Row getRowFromVersionedValue(MVTable table, long recKey,
VersionedValue versionedValue) { VersionedValue versionedValue) {
Object value = versionedValue == null ? null : versionedValue.value; Object value = versionedValue == null ? null : versionedValue.getCurrentValue();
if (value == null) { if (value == null) {
return null; return null;
} }
......
...@@ -65,6 +65,14 @@ public class ConditionInParameter extends Condition { ...@@ -65,6 +65,14 @@ public class ConditionInParameter extends Condition {
private final Parameter parameter; private final Parameter parameter;
/**
* Gets evaluated condition value.
*
* @param database database instance.
* @param l left value.
* @param value parameter value.
* @return Evaluated condition value.
*/
static Value getValue(Database database, Value l, Value value) { static Value getValue(Database database, Value l, Value value) {
boolean hasNull = false; boolean hasNull = false;
if (value.containsNull()) { if (value.containsNull()) {
......
...@@ -69,8 +69,19 @@ public abstract class JdbcLob extends TraceObject { ...@@ -69,8 +69,19 @@ public abstract class JdbcLob extends TraceObject {
CLOSED; CLOSED;
} }
/**
* JDBC connection.
*/
final JdbcConnection conn; final JdbcConnection conn;
/**
* Value.
*/
Value value; Value value;
/**
* State.
*/
State state; State state;
JdbcLob(JdbcConnection conn, Value value, State state, int type, int id) { JdbcLob(JdbcConnection conn, Value value, State state, int type, int id) {
...@@ -80,6 +91,10 @@ public abstract class JdbcLob extends TraceObject { ...@@ -80,6 +91,10 @@ public abstract class JdbcLob extends TraceObject {
this.state = state; this.state = state;
} }
/**
* Check that connection and LOB is not closed, otherwise throws exception with
* error code {@link org.h2.api.ErrorCode#OBJECT_CLOSED}.
*/
void checkClosed() { void checkClosed() {
conn.checkClosed(); conn.checkClosed();
if (state == State.CLOSED) { if (state == State.CLOSED) {
...@@ -87,6 +102,10 @@ public abstract class JdbcLob extends TraceObject { ...@@ -87,6 +102,10 @@ public abstract class JdbcLob extends TraceObject {
} }
} }
/**
* Check the state of the LOB and throws the exception when check failed
* (set is supported only for a new LOB).
*/
void checkEditable() { void checkEditable() {
checkClosed(); checkClosed();
if (state != State.NEW) { if (state != State.NEW) {
...@@ -94,6 +113,10 @@ public abstract class JdbcLob extends TraceObject { ...@@ -94,6 +113,10 @@ public abstract class JdbcLob extends TraceObject {
} }
} }
/**
* Check the state of the LOB and throws the exception when check failed
* (the LOB must be set completely before read).
*/
void checkReadable() throws SQLException, IOException { void checkReadable() throws SQLException, IOException {
checkClosed(); checkClosed();
if (state == State.SET_CALLED) { if (state == State.SET_CALLED) {
...@@ -101,6 +124,10 @@ public abstract class JdbcLob extends TraceObject { ...@@ -101,6 +124,10 @@ public abstract class JdbcLob extends TraceObject {
} }
} }
/**
* Change the state LOB state (LOB value is set completely and available to read).
* @param blob LOB value.
*/
void completeWrite(Value blob) { void completeWrite(Value blob) {
checkClosed(); checkClosed();
state = State.WITH_VALUE; state = State.WITH_VALUE;
...@@ -146,10 +173,22 @@ public abstract class JdbcLob extends TraceObject { ...@@ -146,10 +173,22 @@ public abstract class JdbcLob extends TraceObject {
} }
} }
/**
* Returns the writer.
*
* @return Writer.
* @throws IOException If an I/O error occurs.
*/
Writer setCharacterStreamImpl() throws IOException { Writer setCharacterStreamImpl() throws IOException {
return IOUtils.getBufferedWriter(setClobOutputStreamImpl()); return IOUtils.getBufferedWriter(setClobOutputStreamImpl());
} }
/**
* Returns the writer stream.
*
* @return Output stream..
* @throws IOException If an I/O error occurs.
*/
LobPipedOutputStream setClobOutputStreamImpl() throws IOException { LobPipedOutputStream setClobOutputStreamImpl() throws IOException {
// PipedReader / PipedWriter are a lot slower // PipedReader / PipedWriter are a lot slower
// than PipedInputStream / PipedOutputStream // than PipedInputStream / PipedOutputStream
......
...@@ -3606,7 +3606,7 @@ public class JdbcResultSet extends TraceObject implements ResultSet, JdbcResultS ...@@ -3606,7 +3606,7 @@ public class JdbcResultSet extends TraceObject implements ResultSet, JdbcResultS
* Updates a column in the current or insert row. * Updates a column in the current or insert row.
* *
* @param columnIndex (1,2,...) * @param columnIndex (1,2,...)
* @param x the value * @param xmlObject the value
* @throws SQLException if the result set is closed or not updatable * @throws SQLException if the result set is closed or not updatable
*/ */
@Override @Override
...@@ -3633,7 +3633,7 @@ public class JdbcResultSet extends TraceObject implements ResultSet, JdbcResultS ...@@ -3633,7 +3633,7 @@ public class JdbcResultSet extends TraceObject implements ResultSet, JdbcResultS
* Updates a column in the current or insert row. * Updates a column in the current or insert row.
* *
* @param columnLabel the column label * @param columnLabel the column label
* @param x the value * @param xmlObject the value
* @throws SQLException if the result set is closed or not updatable * @throws SQLException if the result set is closed or not updatable
*/ */
@Override @Override
......
...@@ -55,6 +55,10 @@ public class DbException extends RuntimeException { ...@@ -55,6 +55,10 @@ public class DbException extends RuntimeException {
private static final Properties MESSAGES = new Properties(); private static final Properties MESSAGES = new Properties();
/**
* Thrown when OOME exception is happened on handle error
* inside {@link #convert(java.lang.Throwable)}.
*/
public static final SQLException SQL_OOME = public static final SQLException SQL_OOME =
new SQLException("OutOfMemoryError", "HY000", OUT_OF_MEMORY, new OutOfMemoryError()); new SQLException("OutOfMemoryError", "HY000", OUT_OF_MEMORY, new OutOfMemoryError());
private static final DbException OOME = new DbException(SQL_OOME); private static final DbException OOME = new DbException(SQL_OOME);
...@@ -432,6 +436,7 @@ public class DbException extends RuntimeException { ...@@ -432,6 +436,7 @@ public class DbException extends RuntimeException {
* @param errorCode the error code * @param errorCode the error code
* @param cause the exception that was the reason for this exception * @param cause the exception that was the reason for this exception
* @param stackTrace the stack trace * @param stackTrace the stack trace
* @return the SQLException object
*/ */
public static SQLException getJdbcSQLException(String message, String sql, String state, int errorCode, public static SQLException getJdbcSQLException(String message, String sql, String state, int errorCode,
Throwable cause, String stackTrace) { Throwable cause, String stackTrace) {
......
...@@ -252,6 +252,7 @@ public final class DataUtils { ...@@ -252,6 +252,7 @@ public final class DataUtils {
* *
* @param out the output stream * @param out the output stream
* @param x the value * @param x the value
* @throws IOException if some data could not be written
*/ */
public static void writeVarInt(OutputStream out, int x) throws IOException { public static void writeVarInt(OutputStream out, int x) throws IOException {
while ((x & ~0x7f) != 0) { while ((x & ~0x7f) != 0) {
...@@ -341,6 +342,7 @@ public final class DataUtils { ...@@ -341,6 +342,7 @@ public final class DataUtils {
* *
* @param out the output stream * @param out the output stream
* @param x the value * @param x the value
* @throws IOException if some data could not be written
*/ */
public static void writeVarLong(OutputStream out, long x) public static void writeVarLong(OutputStream out, long x)
throws IOException { throws IOException {
......
...@@ -156,6 +156,7 @@ public class MVMap<K, V> extends AbstractMap<K, V> ...@@ -156,6 +156,7 @@ public class MVMap<K, V> extends AbstractMap<K, V>
* *
* @param key the key (may not be null) * @param key the key (may not be null)
* @param value the value (may not be null) * @param value the value (may not be null)
* @param decisionMaker callback object for update logic
* @return the old value if the key existed, or null otherwise * @return the old value if the key existed, or null otherwise
*/ */
public final V put(K key, V value, DecisionMaker<? super V> decisionMaker) { public final V put(K key, V value, DecisionMaker<? super V> decisionMaker) {
...@@ -877,6 +878,9 @@ public class MVMap<K, V> extends AbstractMap<K, V> ...@@ -877,6 +878,9 @@ public class MVMap<K, V> extends AbstractMap<K, V>
* @param oldRoot the old root reference, will use the current root reference, * @param oldRoot the old root reference, will use the current root reference,
* if null is specified * if null is specified
* @param newRoot the new root page * @param newRoot the new root page
* @param attemptUpdateCounter how many attempt (including current)
* were made to update root
* @return new RootReference or null if update failed
*/ */
protected final boolean updateRoot(RootReference oldRoot, Page newRoot, int attemptUpdateCounter) { protected final boolean updateRoot(RootReference oldRoot, Page newRoot, int attemptUpdateCounter) {
return setNewRoot(oldRoot, newRoot, attemptUpdateCounter, true) != null; return setNewRoot(oldRoot, newRoot, attemptUpdateCounter, true) != null;
......
...@@ -474,6 +474,7 @@ public class MVStore implements AutoCloseable { ...@@ -474,6 +474,7 @@ public class MVStore implements AutoCloseable {
* does not yet exist. If a map with this name is already open, this map is * does not yet exist. If a map with this name is already open, this map is
* returned. * returned.
* *
* @param <M> the map type
* @param <K> the key type * @param <K> the key type
* @param <V> the value type * @param <V> the value type
* @param name the name of the map * @param name the name of the map
...@@ -1386,7 +1387,7 @@ public class MVStore implements AutoCloseable { ...@@ -1386,7 +1387,7 @@ public class MVStore implements AutoCloseable {
} }
/** /**
* Collect ids for chunks that are no longer in use. * Collect ids for chunks that are in use.
* @param fast if true, simplified version is used, which assumes that recent chunks * @param fast if true, simplified version is used, which assumes that recent chunks
* are still in-use and do not scan recent versions of the store. * are still in-use and do not scan recent versions of the store.
* Also is this case only oldest available version of the store is scanned. * Also is this case only oldest available version of the store is scanned.
......
...@@ -95,6 +95,7 @@ public class StreamStore { ...@@ -95,6 +95,7 @@ public class StreamStore {
* *
* @param in the stream * @param in the stream
* @return the id (potentially an empty array) * @return the id (potentially an empty array)
* @throws IOException If an I/O error occurs
*/ */
@SuppressWarnings("resource") @SuppressWarnings("resource")
public byte[] put(InputStream in) throws IOException { public byte[] put(InputStream in) throws IOException {
......
...@@ -28,7 +28,8 @@ import org.h2.mvstore.rtree.MVRTreeMap.RTreeCursor; ...@@ -28,7 +28,8 @@ import org.h2.mvstore.rtree.MVRTreeMap.RTreeCursor;
import org.h2.mvstore.rtree.SpatialKey; import org.h2.mvstore.rtree.SpatialKey;
import org.h2.mvstore.tx.Transaction; import org.h2.mvstore.tx.Transaction;
import org.h2.mvstore.tx.TransactionMap; import org.h2.mvstore.tx.TransactionMap;
import org.h2.mvstore.tx.VersionedValue; import org.h2.mvstore.tx.VersionedValueType;
import org.h2.value.VersionedValue;
import org.h2.result.Row; import org.h2.result.Row;
import org.h2.result.SearchRow; import org.h2.result.SearchRow;
import org.h2.result.SortOrder; import org.h2.result.SortOrder;
...@@ -98,7 +99,7 @@ public class MVSpatialIndex extends BaseIndex implements SpatialIndex, MVIndex { ...@@ -98,7 +99,7 @@ public class MVSpatialIndex extends BaseIndex implements SpatialIndex, MVIndex {
} }
String mapName = "index." + getId(); String mapName = "index." + getId();
ValueDataType vt = new ValueDataType(db, null); ValueDataType vt = new ValueDataType(db, null);
VersionedValue.Type valueType = new VersionedValue.Type(vt); VersionedValueType valueType = new VersionedValueType(vt);
MVRTreeMap.Builder<VersionedValue> mapBuilder = MVRTreeMap.Builder<VersionedValue> mapBuilder =
new MVRTreeMap.Builder<VersionedValue>(). new MVRTreeMap.Builder<VersionedValue>().
valueType(valueType); valueType(valueType);
......
...@@ -6,6 +6,7 @@ ...@@ -6,6 +6,7 @@
package org.h2.mvstore.tx; package org.h2.mvstore.tx;
import org.h2.mvstore.MVMap; import org.h2.mvstore.MVMap;
import org.h2.value.VersionedValue;
/** /**
* Class CommitDecisionMaker makes a decision during post-commit processing * Class CommitDecisionMaker makes a decision during post-commit processing
...@@ -36,7 +37,7 @@ final class CommitDecisionMaker extends MVMap.DecisionMaker<VersionedValue> { ...@@ -36,7 +37,7 @@ final class CommitDecisionMaker extends MVMap.DecisionMaker<VersionedValue> {
// see TxDecisionMaker.decide() // see TxDecisionMaker.decide()
decision = MVMap.Decision.ABORT; decision = MVMap.Decision.ABORT;
} else /* this is final undo log entry for this key */ if (existingValue.value == null) { } else /* this is final undo log entry for this key */ if (existingValue.getCurrentValue() == null) {
decision = MVMap.Decision.REMOVE; decision = MVMap.Decision.REMOVE;
} else { } else {
decision = MVMap.Decision.PUT; decision = MVMap.Decision.PUT;
...@@ -49,7 +50,7 @@ final class CommitDecisionMaker extends MVMap.DecisionMaker<VersionedValue> { ...@@ -49,7 +50,7 @@ final class CommitDecisionMaker extends MVMap.DecisionMaker<VersionedValue> {
public VersionedValue selectValue(VersionedValue existingValue, VersionedValue providedValue) { public VersionedValue selectValue(VersionedValue existingValue, VersionedValue providedValue) {
assert decision == MVMap.Decision.PUT; assert decision == MVMap.Decision.PUT;
assert existingValue != null; assert existingValue != null;
return VersionedValue.getInstance(existingValue.value); return VersionedValueCommitted.getInstance(existingValue.getCurrentValue());
} }
@Override @Override
......
...@@ -6,6 +6,7 @@ ...@@ -6,6 +6,7 @@
package org.h2.mvstore.tx; package org.h2.mvstore.tx;
import org.h2.mvstore.MVMap; import org.h2.mvstore.MVMap;
import org.h2.value.VersionedValue;
/** /**
* Class RollbackDecisionMaker process undo log record during transaction rollback. * Class RollbackDecisionMaker process undo log record during transaction rollback.
......
...@@ -9,6 +9,7 @@ import org.h2.mvstore.DataUtils; ...@@ -9,6 +9,7 @@ import org.h2.mvstore.DataUtils;
import org.h2.mvstore.MVMap; import org.h2.mvstore.MVMap;
import org.h2.mvstore.MVStore; import org.h2.mvstore.MVStore;
import org.h2.mvstore.type.DataType; import org.h2.mvstore.type.DataType;
import org.h2.value.VersionedValue;
import java.util.Iterator; import java.util.Iterator;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
...@@ -561,6 +562,8 @@ public class Transaction { ...@@ -561,6 +562,8 @@ public class Transaction {
/** /**
* Remove the map. * Remove the map.
* *
* @param <K> the key type
* @param <V> the value type
* @param map the map * @param map the map
*/ */
public <K, V> void removeMap(TransactionMap<K, V> map) { public <K, V> void removeMap(TransactionMap<K, V> map) {
......
...@@ -10,6 +10,7 @@ import org.h2.mvstore.DataUtils; ...@@ -10,6 +10,7 @@ import org.h2.mvstore.DataUtils;
import org.h2.mvstore.MVMap; import org.h2.mvstore.MVMap;
import org.h2.mvstore.Page; import org.h2.mvstore.Page;
import org.h2.mvstore.type.DataType; import org.h2.mvstore.type.DataType;
import org.h2.value.VersionedValue;
import java.util.AbstractMap; import java.util.AbstractMap;
import java.util.AbstractSet; import java.util.AbstractSet;
...@@ -146,7 +147,7 @@ public class TransactionMap<K, V> extends AbstractMap<K, V> { ...@@ -146,7 +147,7 @@ public class TransactionMap<K, V> extends AbstractMap<K, V> {
int txId = TransactionStore.getTransactionId(operationId); int txId = TransactionStore.getTransactionId(operationId);
boolean isVisible = txId == transaction.transactionId || boolean isVisible = txId == transaction.transactionId ||
committingTransactions.get(txId); committingTransactions.get(txId);
Object v = isVisible ? currentValue.value : currentValue.getCommittedValue(); Object v = isVisible ? currentValue.getCurrentValue() : currentValue.getCommittedValue();
if (v == null) { if (v == null) {
--size; --size;
} }
...@@ -177,7 +178,7 @@ public class TransactionMap<K, V> extends AbstractMap<K, V> { ...@@ -177,7 +178,7 @@ public class TransactionMap<K, V> extends AbstractMap<K, V> {
int txId = TransactionStore.getTransactionId(operationId); int txId = TransactionStore.getTransactionId(operationId);
boolean isVisible = txId == transaction.transactionId || boolean isVisible = txId == transaction.transactionId ||
committingTransactions.get(txId); committingTransactions.get(txId);
Object v = isVisible ? currentValue.value : currentValue.getCommittedValue(); Object v = isVisible ? currentValue.getCurrentValue() : currentValue.getCommittedValue();
if (v == null) { if (v == null) {
--size; --size;
} }
...@@ -274,10 +275,10 @@ public class TransactionMap<K, V> extends AbstractMap<K, V> { ...@@ -274,10 +275,10 @@ public class TransactionMap<K, V> extends AbstractMap<K, V> {
*/ */
public V putCommitted(K key, V value) { public V putCommitted(K key, V value) {
DataUtils.checkArgument(value != null, "The value may not be null"); DataUtils.checkArgument(value != null, "The value may not be null");
VersionedValue newValue = VersionedValue.getInstance(value); VersionedValue newValue = VersionedValueCommitted.getInstance(value);
VersionedValue oldValue = map.put(key, newValue); VersionedValue oldValue = map.put(key, newValue);
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
V result = (V) (oldValue == null ? null : oldValue.value); V result = (V) (oldValue == null ? null : oldValue.getCurrentValue());
return result; return result;
} }
...@@ -308,7 +309,7 @@ public class TransactionMap<K, V> extends AbstractMap<K, V> { ...@@ -308,7 +309,7 @@ public class TransactionMap<K, V> extends AbstractMap<K, V> {
blockingTransaction = decisionMaker.getBlockingTransaction(); blockingTransaction = decisionMaker.getBlockingTransaction();
if (decision != MVMap.Decision.ABORT || blockingTransaction == null) { if (decision != MVMap.Decision.ABORT || blockingTransaction == null) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
V res = result == null ? null : (V) result.value; V res = result == null ? null : (V) result.getCurrentValue();
return res; return res;
} }
decisionMaker.reset(); decisionMaker.reset();
...@@ -389,12 +390,12 @@ public class TransactionMap<K, V> extends AbstractMap<K, V> { ...@@ -389,12 +390,12 @@ public class TransactionMap<K, V> extends AbstractMap<K, V> {
long id = data.getOperationId(); long id = data.getOperationId();
if (id == 0) { if (id == 0) {
// it is committed // it is committed
return (V)data.value; return (V)data.getCurrentValue();
} }
int tx = TransactionStore.getTransactionId(id); int tx = TransactionStore.getTransactionId(id);
if (tx == transaction.transactionId || transaction.store.committingTransactions.get().get(tx)) { if (tx == transaction.transactionId || transaction.store.committingTransactions.get().get(tx)) {
// added by this transaction or another transaction which is committed by now // added by this transaction or another transaction which is committed by now
return (V)data.value; return (V) data.getCurrentValue();
} else { } else {
return (V) data.getCommittedValue(); return (V) data.getCommittedValue();
} }
...@@ -663,7 +664,7 @@ public class TransactionMap<K, V> extends AbstractMap<K, V> { ...@@ -663,7 +664,7 @@ public class TransactionMap<K, V> extends AbstractMap<K, V> {
@Override @Override
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
protected Map.Entry<K, V> registerCurrent(K key, VersionedValue data) { protected Map.Entry<K, V> registerCurrent(K key, VersionedValue data) {
return new AbstractMap.SimpleImmutableEntry<>(key, (V) data.value); return new AbstractMap.SimpleImmutableEntry<>(key, (V) data.getCurrentValue());
} }
} }
...@@ -718,12 +719,12 @@ public class TransactionMap<K, V> extends AbstractMap<K, V> { ...@@ -718,12 +719,12 @@ public class TransactionMap<K, V> extends AbstractMap<K, V> {
// current value comes from another uncommitted transaction // current value comes from another uncommitted transaction
// take committed value instead // take committed value instead
Object committedValue = data.getCommittedValue(); Object committedValue = data.getCommittedValue();
data = committedValue == null ? null : VersionedValue.getInstance(committedValue); data = committedValue == null ? null : VersionedValueCommitted.getInstance(committedValue);
} }
} }
} }
} }
if (data != null && (data.value != null || if (data != null && (data.getCurrentValue() != null ||
includeAllUncommitted && transactionId != includeAllUncommitted && transactionId !=
TransactionStore.getTransactionId(data.getOperationId()))) { TransactionStore.getTransactionId(data.getOperationId()))) {
current = registerCurrent(key, data); current = registerCurrent(key, data);
......
...@@ -20,6 +20,7 @@ import org.h2.mvstore.WriteBuffer; ...@@ -20,6 +20,7 @@ import org.h2.mvstore.WriteBuffer;
import org.h2.mvstore.type.DataType; import org.h2.mvstore.type.DataType;
import org.h2.mvstore.type.ObjectDataType; import org.h2.mvstore.type.ObjectDataType;
import org.h2.util.StringUtils; import org.h2.util.StringUtils;
import org.h2.value.VersionedValue;
/** /**
* A store that supports concurrent MVCC read-committed transactions. * A store that supports concurrent MVCC read-committed transactions.
...@@ -128,14 +129,14 @@ public class TransactionStore { ...@@ -128,14 +129,14 @@ public class TransactionStore {
this.timeoutMillis = timeoutMillis; this.timeoutMillis = timeoutMillis;
preparedTransactions = store.openMap("openTransactions", preparedTransactions = store.openMap("openTransactions",
new MVMap.Builder<Integer, Object[]>()); new MVMap.Builder<Integer, Object[]>());
DataType oldValueType = new VersionedValue.Type(dataType); DataType oldValueType = new VersionedValueType(dataType);
ArrayType undoLogValueType = new ArrayType(new DataType[]{ ArrayType undoLogValueType = new ArrayType(new DataType[]{
new ObjectDataType(), dataType, oldValueType new ObjectDataType(), dataType, oldValueType
}); });
undoLogBuilder = new MVMap.Builder<Long, Object[]>() undoLogBuilder = new MVMap.Builder<Long, Object[]>()
.singleWriter() .singleWriter()
.valueType(undoLogValueType); .valueType(undoLogValueType);
DataType vt = new VersionedValue.Type(dataType); DataType vt = new VersionedValueType(dataType);
mapBuilder = new MVMap.Builder<Object, VersionedValue>() mapBuilder = new MVMap.Builder<Object, VersionedValue>()
.keyType(dataType).valueType(vt); .keyType(dataType).valueType(vt);
} }
...@@ -494,7 +495,7 @@ public class TransactionStore { ...@@ -494,7 +495,7 @@ public class TransactionStore {
if (valueType == null) { if (valueType == null) {
valueType = new ObjectDataType(); valueType = new ObjectDataType();
} }
VersionedValue.Type vt = new VersionedValue.Type(valueType); VersionedValueType vt = new VersionedValueType(valueType);
MVMap<K, VersionedValue> map; MVMap<K, VersionedValue> map;
MVMap.Builder<K, VersionedValue> builder = MVMap.Builder<K, VersionedValue> builder =
new MVMap.Builder<K, VersionedValue>(). new MVMap.Builder<K, VersionedValue>().
...@@ -640,7 +641,7 @@ public class TransactionStore { ...@@ -640,7 +641,7 @@ public class TransactionStore {
MVMap<Object, VersionedValue> m = openMap(mapId); MVMap<Object, VersionedValue> m = openMap(mapId);
if (m != null) { // could be null if map was removed later on if (m != null) { // could be null if map was removed later on
VersionedValue oldValue = (VersionedValue) op[2]; VersionedValue oldValue = (VersionedValue) op[2];
current = new Change(m.getName(), op[1], oldValue == null ? null : oldValue.value); current = new Change(m.getName(), op[1], oldValue == null ? null : oldValue.getCurrentValue());
return; return;
} }
} }
......
...@@ -6,6 +6,7 @@ ...@@ -6,6 +6,7 @@
package org.h2.mvstore.tx; package org.h2.mvstore.tx;
import org.h2.mvstore.MVMap; import org.h2.mvstore.MVMap;
import org.h2.value.VersionedValue;
/** /**
* Class TxDecisionMaker. * Class TxDecisionMaker.
...@@ -47,7 +48,7 @@ abstract class TxDecisionMaker extends MVMap.DecisionMaker<VersionedValue> { ...@@ -47,7 +48,7 @@ abstract class TxDecisionMaker extends MVMap.DecisionMaker<VersionedValue> {
// We assume that we are looking at the final value for this transaction, // We assume that we are looking at the final value for this transaction,
// and if it's not the case, then it will fail later, // and if it's not the case, then it will fail later,
// because a tree root has definitely been changed. // because a tree root has definitely been changed.
logIt(existingValue.value == null ? null : VersionedValue.getInstance(existingValue.value)); logIt(existingValue.getCurrentValue() == null ? null : VersionedValueCommitted.getInstance(existingValue.getCurrentValue()));
decision = MVMap.Decision.PUT; decision = MVMap.Decision.PUT;
} else if (getBlockingTransaction() != null) { } else if (getBlockingTransaction() != null) {
// this entry comes from a different transaction, and this // this entry comes from a different transaction, and this
...@@ -63,7 +64,7 @@ abstract class TxDecisionMaker extends MVMap.DecisionMaker<VersionedValue> { ...@@ -63,7 +64,7 @@ abstract class TxDecisionMaker extends MVMap.DecisionMaker<VersionedValue> {
// was written but not undo log), and will effectively roll it back // was written but not undo log), and will effectively roll it back
// (just assume committed value and overwrite). // (just assume committed value and overwrite).
Object committedValue = existingValue.getCommittedValue(); Object committedValue = existingValue.getCommittedValue();
logIt(committedValue == null ? null : VersionedValue.getInstance(committedValue)); logIt(committedValue == null ? null : VersionedValueCommitted.getInstance(committedValue));
decision = MVMap.Decision.PUT; decision = MVMap.Decision.PUT;
} else { } else {
// transaction has been committed/rolled back and is closed by now, so // transaction has been committed/rolled back and is closed by now, so
...@@ -138,7 +139,7 @@ abstract class TxDecisionMaker extends MVMap.DecisionMaker<VersionedValue> { ...@@ -138,7 +139,7 @@ abstract class TxDecisionMaker extends MVMap.DecisionMaker<VersionedValue> {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public final VersionedValue selectValue(VersionedValue existingValue, VersionedValue providedValue) { public final VersionedValue selectValue(VersionedValue existingValue, VersionedValue providedValue) {
return VersionedValue.getInstance(undoKey, value, return VersionedValueUncommitted.getInstance(undoKey, value,
existingValue == null ? null : existingValue.getCommittedValue()); existingValue == null ? null : existingValue.getCommittedValue());
} }
} }
...@@ -163,7 +164,7 @@ abstract class TxDecisionMaker extends MVMap.DecisionMaker<VersionedValue> { ...@@ -163,7 +164,7 @@ abstract class TxDecisionMaker extends MVMap.DecisionMaker<VersionedValue> {
if (id == 0 // entry is a committed one if (id == 0 // entry is a committed one
// or it came from the same transaction // or it came from the same transaction
|| isThisTransaction(blockingId = TransactionStore.getTransactionId(id))) { || isThisTransaction(blockingId = TransactionStore.getTransactionId(id))) {
if(existingValue.value != null) { if(existingValue.getCurrentValue() != null) {
return setDecision(MVMap.Decision.ABORT); return setDecision(MVMap.Decision.ABORT);
} }
logIt(existingValue); logIt(existingValue);
...@@ -171,7 +172,7 @@ abstract class TxDecisionMaker extends MVMap.DecisionMaker<VersionedValue> { ...@@ -171,7 +172,7 @@ abstract class TxDecisionMaker extends MVMap.DecisionMaker<VersionedValue> {
} else if (isCommitted(blockingId)) { } else if (isCommitted(blockingId)) {
// entry belongs to a committing transaction // entry belongs to a committing transaction
// and therefore will be committed soon // and therefore will be committed soon
if(existingValue.value != null) { if(existingValue.getCurrentValue() != null) {
return setDecision(MVMap.Decision.ABORT); return setDecision(MVMap.Decision.ABORT);
} }
logIt(null); logIt(null);
...@@ -228,8 +229,8 @@ abstract class TxDecisionMaker extends MVMap.DecisionMaker<VersionedValue> { ...@@ -228,8 +229,8 @@ abstract class TxDecisionMaker extends MVMap.DecisionMaker<VersionedValue> {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public VersionedValue selectValue(VersionedValue existingValue, VersionedValue providedValue) { public VersionedValue selectValue(VersionedValue existingValue, VersionedValue providedValue) {
return VersionedValue.getInstance(undoKey, return VersionedValueUncommitted.getInstance(undoKey,
existingValue == null ? null : existingValue.value, existingValue == null ? null : existingValue.getCurrentValue(),
existingValue == null ? null : existingValue.getCommittedValue()); existingValue == null ? null : existingValue.getCommittedValue());
} }
} }
......
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.mvstore.tx;
import org.h2.engine.Constants;
import org.h2.mvstore.DataUtils;
import org.h2.mvstore.WriteBuffer;
import org.h2.mvstore.type.DataType;
import java.nio.ByteBuffer;
/**
* A versioned value (possibly null).
* It contains current value and latest committed value if current one is uncommitted.
* Also for uncommitted values it contains operationId - a combination of
* transactionId and logId.
*/
public class VersionedValue {
public static final VersionedValue DUMMY = new VersionedValue(new Object());
/**
* The current value.
*/
public final Object value;
static VersionedValue getInstance(Object value) {
assert value != null;
return new VersionedValue(value);
}
public static VersionedValue getInstance(long operationId, Object value, Object committedValue) {
return new Uncommitted(operationId, value, committedValue);
}
VersionedValue(Object value) {
this.value = value;
}
public boolean isCommitted() {
return true;
}
public long getOperationId() {
return 0L;
}
public Object getCommittedValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
private static class Uncommitted extends VersionedValue
{
private final long operationId;
private final Object committedValue;
Uncommitted(long operationId, Object value, Object committedValue) {
super(value);
assert operationId != 0;
this.operationId = operationId;
this.committedValue = committedValue;
}
@Override
public boolean isCommitted() {
return false;
}
@Override
public long getOperationId() {
return operationId;
}
@Override
public Object getCommittedValue() {
return committedValue;
}
@Override
public String toString() {
return super.toString() +
" " + TransactionStore.getTransactionId(operationId) + "/" +
TransactionStore.getLogId(operationId) + " " + committedValue;
}
}
/**
* The value type for a versioned value.
*/
public static class Type implements DataType {
private final DataType valueType;
public Type(DataType valueType) {
this.valueType = valueType;
}
@Override
public int getMemory(Object obj) {
if(obj == null) return 0;
VersionedValue v = (VersionedValue) obj;
int res = Constants.MEMORY_OBJECT + 8 + 2 * Constants.MEMORY_POINTER +
getValMemory(v.value);
if (v.getOperationId() != 0) {
res += getValMemory(v.getCommittedValue());
}
return res;
}
private int getValMemory(Object obj) {
return obj == null ? 0 : valueType.getMemory(obj);
}
@Override
public int compare(Object aObj, Object bObj) {
if (aObj == bObj) {
return 0;
} else if (aObj == null) {
return -1;
} else if (bObj == null) {
return 1;
}
VersionedValue a = (VersionedValue) aObj;
VersionedValue b = (VersionedValue) bObj;
long comp = a.getOperationId() - b.getOperationId();
if (comp == 0) {
return valueType.compare(a.value, b.value);
}
return Long.signum(comp);
}
@Override
public void read(ByteBuffer buff, Object[] obj, int len, boolean key) {
if (buff.get() == 0) {
// fast path (no op ids or null entries)
for (int i = 0; i < len; i++) {
obj[i] = new VersionedValue(valueType.read(buff));
}
} else {
// slow path (some entries may be null)
for (int i = 0; i < len; i++) {
obj[i] = read(buff);
}
}
}
@Override
public Object read(ByteBuffer buff) {
long operationId = DataUtils.readVarLong(buff);
if (operationId == 0) {
return new VersionedValue(valueType.read(buff));
} else {
byte flags = buff.get();
Object value = (flags & 1) != 0 ? valueType.read(buff) : null;
Object committedValue = (flags & 2) != 0 ? valueType.read(buff) : null;
return new Uncommitted(operationId, value, committedValue);
}
}
@Override
public void write(WriteBuffer buff, Object[] obj, int len, boolean key) {
boolean fastPath = true;
for (int i = 0; i < len; i++) {
VersionedValue v = (VersionedValue) obj[i];
if (v.getOperationId() != 0 || v.value == null) {
fastPath = false;
}
}
if (fastPath) {
buff.put((byte) 0);
for (int i = 0; i < len; i++) {
VersionedValue v = (VersionedValue) obj[i];
valueType.write(buff, v.value);
}
} else {
// slow path:
// store op ids, and some entries may be null
buff.put((byte) 1);
for (int i = 0; i < len; i++) {
write(buff, obj[i]);
}
}
}
@Override
public void write(WriteBuffer buff, Object obj) {
VersionedValue v = (VersionedValue) obj;
long operationId = v.getOperationId();
buff.putVarLong(operationId);
if (operationId == 0) {
valueType.write(buff, v.value);
} else {
Object committedValue = v.getCommittedValue();
int flags = (v.value == null ? 0 : 1) | (committedValue == null ? 0 : 2);
buff.put((byte) flags);
if (v.value != null) {
valueType.write(buff, v.value);
}
if (committedValue != null) {
valueType.write(buff, committedValue);
}
}
}
}
}
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.mvstore.tx;
import org.h2.value.VersionedValue;
/**
* Class CommittedVersionedValue.
*
* @author <a href='mailto:andrei.tokar@gmail.com'>Andrei Tokar</a>
*/
class VersionedValueCommitted extends VersionedValue {
/**
* The current value.
*/
public final Object value;
VersionedValueCommitted(Object value) {
this.value = value;
}
static VersionedValue getInstance(Object value) {
assert value != null;
return value instanceof VersionedValue ? (VersionedValue) value : new VersionedValueCommitted(value);
}
public Object getCurrentValue() {
return value;
}
public Object getCommittedValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
}
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.mvstore.tx;
import org.h2.engine.Constants;
import org.h2.mvstore.DataUtils;
import org.h2.mvstore.WriteBuffer;
import org.h2.mvstore.type.DataType;
import org.h2.value.VersionedValue;
import java.nio.ByteBuffer;
/**
* The value type for a versioned value.
*/
public class VersionedValueType implements DataType {
private final DataType valueType;
public VersionedValueType(DataType valueType) {
this.valueType = valueType;
}
@Override
public int getMemory(Object obj) {
if(obj == null) return 0;
VersionedValue v = (VersionedValue) obj;
int res = Constants.MEMORY_OBJECT + 8 + 2 * Constants.MEMORY_POINTER +
getValMemory(v.getCurrentValue());
if (v.getOperationId() != 0) {
res += getValMemory(v.getCommittedValue());
}
return res;
}
private int getValMemory(Object obj) {
return obj == null ? 0 : valueType.getMemory(obj);
}
@Override
public int compare(Object aObj, Object bObj) {
if (aObj == bObj) {
return 0;
} else if (aObj == null) {
return -1;
} else if (bObj == null) {
return 1;
}
VersionedValue a = (VersionedValue) aObj;
VersionedValue b = (VersionedValue) bObj;
long comp = a.getOperationId() - b.getOperationId();
if (comp == 0) {
return valueType.compare(a.getCurrentValue(), b.getCurrentValue());
}
return Long.signum(comp);
}
@Override
public void read(ByteBuffer buff, Object[] obj, int len, boolean key) {
if (buff.get() == 0) {
// fast path (no op ids or null entries)
for (int i = 0; i < len; i++) {
obj[i] = VersionedValueCommitted.getInstance(valueType.read(buff));
}
} else {
// slow path (some entries may be null)
for (int i = 0; i < len; i++) {
obj[i] = read(buff);
}
}
}
@Override
public Object read(ByteBuffer buff) {
long operationId = DataUtils.readVarLong(buff);
if (operationId == 0) {
return VersionedValueCommitted.getInstance(valueType.read(buff));
} else {
byte flags = buff.get();
Object value = (flags & 1) != 0 ? valueType.read(buff) : null;
Object committedValue = (flags & 2) != 0 ? valueType.read(buff) : null;
return VersionedValueUncommitted.getInstance(operationId, value, committedValue);
}
}
@Override
public void write(WriteBuffer buff, Object[] obj, int len, boolean key) {
boolean fastPath = true;
for (int i = 0; i < len; i++) {
VersionedValue v = (VersionedValue) obj[i];
if (v.getOperationId() != 0 || v.getCurrentValue() == null) {
fastPath = false;
}
}
if (fastPath) {
buff.put((byte) 0);
for (int i = 0; i < len; i++) {
VersionedValue v = (VersionedValue) obj[i];
valueType.write(buff, v.getCurrentValue());
}
} else {
// slow path:
// store op ids, and some entries may be null
buff.put((byte) 1);
for (int i = 0; i < len; i++) {
write(buff, obj[i]);
}
}
}
@Override
public void write(WriteBuffer buff, Object obj) {
VersionedValue v = (VersionedValue) obj;
long operationId = v.getOperationId();
buff.putVarLong(operationId);
if (operationId == 0) {
valueType.write(buff, v.getCurrentValue());
} else {
Object committedValue = v.getCommittedValue();
int flags = (v.getCurrentValue() == null ? 0 : 1) | (committedValue == null ? 0 : 2);
buff.put((byte) flags);
if (v.getCurrentValue() != null) {
valueType.write(buff, v.getCurrentValue());
}
if (committedValue != null) {
valueType.write(buff, committedValue);
}
}
}
}
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.mvstore.tx;
import org.h2.value.VersionedValue;
/**
* Class VersionedValueUncommitted.
*
* @author <a href='mailto:andrei.tokar@gmail.com'>Andrei Tokar</a>
*/
class VersionedValueUncommitted extends VersionedValueCommitted {
private final long operationId;
private final Object committedValue;
private VersionedValueUncommitted(long operationId, Object value, Object committedValue) {
super(value);
assert operationId != 0;
this.operationId = operationId;
this.committedValue = committedValue;
}
static VersionedValue getInstance(long operationId, Object value, Object committedValue) {
return new VersionedValueUncommitted(operationId, value, committedValue);
}
@Override
public boolean isCommitted() {
return false;
}
@Override
public long getOperationId() {
return operationId;
}
@Override
public Object getCommittedValue() {
return committedValue;
}
@Override
public String toString() {
return super.toString() +
" " + TransactionStore.getTransactionId(operationId) + "/" +
TransactionStore.getLogId(operationId) + " " + committedValue;
}
}
...@@ -94,16 +94,36 @@ public class SimpleResult implements ResultInterface { ...@@ -94,16 +94,36 @@ public class SimpleResult implements ResultInterface {
this.rowId = -1; this.rowId = -1;
} }
/**
* Add column to the result.
*
* @param alias Column's alias.
* @param columnName Column's name.
* @param columnType Column's type.
* @param columnPrecision Column's precision.
* @param columnScale Column's scale.
* @param displaySize Column's display data size.
*/
public void addColumn(String alias, String columnName, int columnType, long columnPrecision, int columnScale, public void addColumn(String alias, String columnName, int columnType, long columnPrecision, int columnScale,
int displaySize) { int displaySize) {
addColumn(new Column(alias, columnName, columnType, columnPrecision, columnScale, displaySize)); addColumn(new Column(alias, columnName, columnType, columnPrecision, columnScale, displaySize));
} }
/**
* Add column to the result.
*
* @param column Column info.
*/
void addColumn(Column column) { void addColumn(Column column) {
assert rows.isEmpty(); assert rows.isEmpty();
columns.add(column); columns.add(column);
} }
/**
* Add row to result.
*
* @param values Row's values.
*/
public void addRow(Value... values) { public void addRow(Value... values) {
assert values.length == columns.size(); assert values.length == columns.size();
rows.add(values); rows.add(values);
......
...@@ -20,7 +20,7 @@ public class AuthenticationInfo { ...@@ -20,7 +20,7 @@ public class AuthenticationInfo {
private String realm; private String realm;
/* /*
* Can be used by authenticator to hold informations * Can be used by authenticator to hold information.
*/ */
Object nestedIdentity; Object nestedIdentity;
...@@ -58,14 +58,16 @@ public class AuthenticationInfo { ...@@ -58,14 +58,16 @@ public class AuthenticationInfo {
} }
/** /**
* get nested identity * Gets nested identity.
*
* @return nested identity object.
*/ */
public Object getNestedIdentity() { public Object getNestedIdentity() {
return nestedIdentity; return nestedIdentity;
} }
/** /**
* Method used by authenticators to hold informations about authenticated * Method used by authenticators to hold information about authenticated
* user * user
* *
* @param nestedIdentity * @param nestedIdentity
...@@ -75,6 +77,9 @@ public class AuthenticationInfo { ...@@ -75,6 +77,9 @@ public class AuthenticationInfo {
this.nestedIdentity = nestedIdentity; this.nestedIdentity = nestedIdentity;
} }
/**
* Clean authentication data.
*/
public void clean() { public void clean() {
this.password = null; this.password = null;
this.nestedIdentity = null; this.nestedIdentity = null;
......
...@@ -16,6 +16,8 @@ public interface Authenticator { ...@@ -16,6 +16,8 @@ public interface Authenticator {
/** /**
* Perform user authentication. * Perform user authentication.
* *
* @param authenticationInfo authentication info.
* @param database target database instance.
* @return valid database user or null if user doesn't exists in the * @return valid database user or null if user doesn't exists in the
* database * database
*/ */
......
...@@ -10,6 +10,10 @@ package org.h2.security.auth; ...@@ -10,6 +10,10 @@ package org.h2.security.auth;
*/ */
public class AuthenticatorFactory { public class AuthenticatorFactory {
/**
* Factory method.
* @return authenticator instance.
*/
public static Authenticator createAuthenticator() { public static Authenticator createAuthenticator() {
return DefaultAuthenticator.getInstance(); return DefaultAuthenticator.getInstance();
} }
......
...@@ -38,6 +38,13 @@ public class ConfigProperties { ...@@ -38,6 +38,13 @@ public class ConfigProperties {
} }
} }
/**
* Returns the string value of specified property.
*
* @param name property name.
* @param defaultValue default value.
* @return the string property value or {@code defaultValue} if the property is missing.
*/
public String getStringValue(String name, String defaultValue) { public String getStringValue(String name, String defaultValue) {
String result = properties.get(name); String result = properties.get(name);
if (result == null) { if (result == null) {
...@@ -46,6 +53,13 @@ public class ConfigProperties { ...@@ -46,6 +53,13 @@ public class ConfigProperties {
return result; return result;
} }
/**
* Returns the string value of specified property.
*
* @param name property name.
* @return the string property value.
* @throws AuthConfigException if the property is missing.
*/
public String getStringValue(String name) { public String getStringValue(String name) {
String result = properties.get(name); String result = properties.get(name);
if (result == null) { if (result == null) {
...@@ -54,6 +68,13 @@ public class ConfigProperties { ...@@ -54,6 +68,13 @@ public class ConfigProperties {
return result; return result;
} }
/**
* Returns the integer value of specified property.
*
* @param name property name.
* @param defaultValue default value.
* @return the integer property value or {@code defaultValue} if the property is missing.
*/
public int getIntValue(String name, int defaultValue) { public int getIntValue(String name, int defaultValue) {
String result = properties.get(name); String result = properties.get(name);
if (result == null) { if (result == null) {
...@@ -62,6 +83,13 @@ public class ConfigProperties { ...@@ -62,6 +83,13 @@ public class ConfigProperties {
return Integer.parseInt(result); return Integer.parseInt(result);
} }
/**
* Returns the integer value of specified property.
*
* @param name property name.
* @return the integer property value.
* @throws AuthConfigException if the property is missing.
*/
public int getIntValue(String name) { public int getIntValue(String name) {
String result = properties.get(name); String result = properties.get(name);
if (result == null) { if (result == null) {
...@@ -70,6 +98,13 @@ public class ConfigProperties { ...@@ -70,6 +98,13 @@ public class ConfigProperties {
return Integer.parseInt(result); return Integer.parseInt(result);
} }
/**
* Returns the boolean value of specified property.
*
* @param name property name.
* @param defaultValue default value.
* @return the boolean property value or {@code defaultValue} if the property is missing.
*/
public boolean getBooleanValue(String name, boolean defaultValue) { public boolean getBooleanValue(String name, boolean defaultValue) {
String result = properties.get(name); String result = properties.get(name);
if (result == null) { if (result == null) {
......
...@@ -54,19 +54,12 @@ public class DefaultAuthenticator implements Authenticator { ...@@ -54,19 +54,12 @@ public class DefaultAuthenticator implements Authenticator {
public static final String DEFAULT_REALMNAME = "H2"; public static final String DEFAULT_REALMNAME = "H2";
private Map<String, CredentialsValidator> realms = new HashMap<>(); private Map<String, CredentialsValidator> realms = new HashMap<>();
private List<UserToRolesMapper> userToRolesMappers = new ArrayList<>(); private List<UserToRolesMapper> userToRolesMappers = new ArrayList<>();
private boolean allowUserRegistration; private boolean allowUserRegistration;
private boolean persistUsers; private boolean persistUsers;
private boolean createMissingRoles; private boolean createMissingRoles;
private boolean skipDefaultInitialization; private boolean skipDefaultInitialization;
private boolean initialized; private boolean initialized;
private static DefaultAuthenticator instance; private static DefaultAuthenticator instance;
protected static final DefaultAuthenticator getInstance() { protected static final DefaultAuthenticator getInstance() {
...@@ -95,34 +88,62 @@ public class DefaultAuthenticator implements Authenticator { ...@@ -95,34 +88,62 @@ public class DefaultAuthenticator implements Authenticator {
/** /**
* If set save users externals defined during the authentication. * If set save users externals defined during the authentication.
*
* @return {@code true} if user will be persisted,
* otherwise returns {@code false}
*/ */
public boolean isPersistUsers() { public boolean isPersistUsers() {
return persistUsers; return persistUsers;
} }
/**
* If set to {@code true} saves users externals defined during the authentication.
*
* @param persistUsers {@code true} if user will be persisted,
* otherwise {@code false}.
*/
public void setPersistUsers(boolean persistUsers) { public void setPersistUsers(boolean persistUsers) {
this.persistUsers = persistUsers; this.persistUsers = persistUsers;
} }
/** /**
* If set create external users in the database if not present. * If set create external users in the database if not present.
*
* @return {@code true} if creation external user is allowed,
* otherwise returns {@code false}
*/ */
public boolean isAllowUserRegistration() { public boolean isAllowUserRegistration() {
return allowUserRegistration; return allowUserRegistration;
} }
/**
* If set to{@code true} creates external users in the database if not present.
*
* @param allowUserRegistration {@code true} if creation external user is allowed,
* otherwise returns {@code false}
*/
public void setAllowUserRegistration(boolean allowUserRegistration) { public void setAllowUserRegistration(boolean allowUserRegistration) {
this.allowUserRegistration = allowUserRegistration; this.allowUserRegistration = allowUserRegistration;
} }
/** /**
* When set create roles not found in the database. If not set roles not * When set create roles not found in the database. If not set roles not
* found in the database are silently skipped * found in the database are silently skipped.
*
* @return {@code true} if not found roles will be created,
* {@code false} roles are silently skipped.
*/ */
public boolean isCreateMissingRoles() { public boolean isCreateMissingRoles() {
return createMissingRoles; return createMissingRoles;
} }
/**
* Sets the flag that define behavior in case external roles not found in the database.
*
*
* @param createMissingRoles when is {@code true} not found roles are created,
* when is {@code false} roles are silently skipped.
*/
public void setCreateMissingRoles(boolean createMissingRoles) { public void setCreateMissingRoles(boolean createMissingRoles) {
this.createMissingRoles = createMissingRoles; this.createMissingRoles = createMissingRoles;
} }
...@@ -209,7 +230,7 @@ public class DefaultAuthenticator implements Authenticator { ...@@ -209,7 +230,7 @@ public class DefaultAuthenticator implements Authenticator {
} }
} }
void defaultConfiguration() { private void defaultConfiguration() {
createMissingRoles = false; createMissingRoles = false;
allowUserRegistration = true; allowUserRegistration = true;
realms = new HashMap<>(); realms = new HashMap<>();
...@@ -232,7 +253,7 @@ public class DefaultAuthenticator implements Authenticator { ...@@ -232,7 +253,7 @@ public class DefaultAuthenticator implements Authenticator {
configureFrom(config); configureFrom(config);
} }
void configureFrom(H2AuthConfig config) throws AuthenticationException { private void configureFrom(H2AuthConfig config) throws AuthenticationException {
allowUserRegistration = config.isAllowUserRegistration(); allowUserRegistration = config.isAllowUserRegistration();
createMissingRoles = config.isCreateMissingRoles(); createMissingRoles = config.isCreateMissingRoles();
Map<String, CredentialsValidator> newRealms = new HashMap<>(); Map<String, CredentialsValidator> newRealms = new HashMap<>();
...@@ -270,7 +291,7 @@ public class DefaultAuthenticator implements Authenticator { ...@@ -270,7 +291,7 @@ public class DefaultAuthenticator implements Authenticator {
this.userToRolesMappers = newUserToRolesMapper; this.userToRolesMappers = newUserToRolesMapper;
} }
boolean updateRoles(AuthenticationInfo authenticationInfo, User user, Database database) private boolean updateRoles(AuthenticationInfo authenticationInfo, User user, Database database)
throws AuthenticationException { throws AuthenticationException {
boolean updatedDb = false; boolean updatedDb = false;
Set<String> roles = new HashSet<>(); Set<String> roles = new HashSet<>();
......
...@@ -9,32 +9,56 @@ import java.util.ArrayList; ...@@ -9,32 +9,56 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
/** /**
* Describe configuration of H2 DefaultAuthenticator * Describe configuration of H2 DefaultAuthenticator.
*/ */
public class H2AuthConfig { public class H2AuthConfig {
private boolean allowUserRegistration=true; private boolean allowUserRegistration=true;
private boolean createMissingRoles=true;
private List<RealmConfig> realms;
private List<UserToRolesMapperConfig> userToRolesMappers;
/**
* Allow user registration flag. If set to {@code true}
* creates external users in the database if not present.
*
* @return {@code true} in case user registration is allowed,
* otherwise returns {@code false}.
*/
public boolean isAllowUserRegistration() { public boolean isAllowUserRegistration() {
return allowUserRegistration; return allowUserRegistration;
} }
/**
* @param allowUserRegistration Allow user registration flag.
*/
public void setAllowUserRegistration(boolean allowUserRegistration) { public void setAllowUserRegistration(boolean allowUserRegistration) {
this.allowUserRegistration = allowUserRegistration; this.allowUserRegistration = allowUserRegistration;
} }
boolean createMissingRoles=true; /**
* When set create roles not found in the database. If not set roles not
* found in the database are silently skipped.
* @return {@code true} if the flag is set, otherwise returns {@code false}.
*/
public boolean isCreateMissingRoles() { public boolean isCreateMissingRoles() {
return createMissingRoles; return createMissingRoles;
} }
/**
* When set create roles not found in the database. If not set roles not
* found in the database are silently skipped
* @param createMissingRoles missing roles flag.
*/
public void setCreateMissingRoles(boolean createMissingRoles) { public void setCreateMissingRoles(boolean createMissingRoles) {
this.createMissingRoles = createMissingRoles; this.createMissingRoles = createMissingRoles;
} }
List<RealmConfig> realms; /**
* Gets configuration of authentication realms.
*
* @return configuration of authentication realms.
*/
public List<RealmConfig> getRealms() { public List<RealmConfig> getRealms() {
if (realms == null) { if (realms == null) {
realms = new ArrayList<>(); realms = new ArrayList<>();
...@@ -42,12 +66,20 @@ public class H2AuthConfig { ...@@ -42,12 +66,20 @@ public class H2AuthConfig {
return realms; return realms;
} }
/**
* Sets configuration of authentication realms.
*
* @param realms configuration of authentication realms.
*/
public void setRealms(List<RealmConfig> realms) { public void setRealms(List<RealmConfig> realms) {
this.realms = realms; this.realms = realms;
} }
List<UserToRolesMapperConfig> userToRolesMappers; /**
* Gets configuration of the mappers external users to database roles.
*
* @return configuration of the mappers external users to database roles.
*/
public List<UserToRolesMapperConfig> getUserToRolesMappers() { public List<UserToRolesMapperConfig> getUserToRolesMappers() {
if (userToRolesMappers == null) { if (userToRolesMappers == null) {
userToRolesMappers = new ArrayList<>(); userToRolesMappers = new ArrayList<>();
...@@ -55,6 +87,11 @@ public class H2AuthConfig { ...@@ -55,6 +87,11 @@ public class H2AuthConfig {
return userToRolesMappers; return userToRolesMappers;
} }
/**
* Sets configuration of the mappers external users to database roles.
*
* @param userToRolesMappers configuration of the mappers external users to database roles.
*/
public void setUserToRolesMappers(List<UserToRolesMapperConfig> userToRolesMappers) { public void setUserToRolesMappers(List<UserToRolesMapperConfig> userToRolesMappers) {
this.userToRolesMappers = userToRolesMappers; this.userToRolesMappers = userToRolesMappers;
} }
......
...@@ -20,9 +20,8 @@ import org.xml.sax.helpers.DefaultHandler; ...@@ -20,9 +20,8 @@ import org.xml.sax.helpers.DefaultHandler;
*/ */
public class H2AuthConfigXml extends DefaultHandler{ public class H2AuthConfigXml extends DefaultHandler{
H2AuthConfig result; private H2AuthConfig result;
private HasConfigProperties lastConfigProperties;
HasConfigProperties lastConfigProperties;
@Override @Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
...@@ -68,7 +67,7 @@ public class H2AuthConfigXml extends DefaultHandler{ ...@@ -68,7 +67,7 @@ public class H2AuthConfigXml extends DefaultHandler{
} }
} }
static String getMandatoryAttributeValue(String attributeName, Attributes attributes) throws SAXException { private static String getMandatoryAttributeValue(String attributeName, Attributes attributes) throws SAXException {
String attributeValue=attributes.getValue(attributeName); String attributeValue=attributes.getValue(attributeName);
if (attributeValue==null || attributeValue.trim().equals("")) { if (attributeValue==null || attributeValue.trim().equals("")) {
throw new SAXException("missing attribute "+attributeName); throw new SAXException("missing attribute "+attributeName);
...@@ -77,7 +76,7 @@ public class H2AuthConfigXml extends DefaultHandler{ ...@@ -77,7 +76,7 @@ public class H2AuthConfigXml extends DefaultHandler{
} }
static String getAttributeValueOr(String attributeName, Attributes attributes, String defaultValue) { private static String getAttributeValueOr(String attributeName, Attributes attributes, String defaultValue) {
String attributeValue=attributes.getValue(attributeName); String attributeValue=attributes.getValue(attributeName);
if (attributeValue==null || attributeValue.trim().equals("")) { if (attributeValue==null || attributeValue.trim().equals("")) {
return defaultValue; return defaultValue;
...@@ -85,12 +84,23 @@ public class H2AuthConfigXml extends DefaultHandler{ ...@@ -85,12 +84,23 @@ public class H2AuthConfigXml extends DefaultHandler{
return attributeValue; return attributeValue;
} }
/**
* Returns parsed authenticator configuration.
*
* @return Authenticator configuration.
*/
public H2AuthConfig getResult() { public H2AuthConfig getResult() {
return result; return result;
} }
/** /**
* Parse the xml * Parse the xml.
*
* @param url the source of the xml configuration.
* @return Authenticator configuration.
* @throws ParserConfigurationException if a parser cannot be created.
* @throws SAXException for SAX errors.
* @throws IOException If an I/O error occurs
*/ */
public static H2AuthConfig parseFrom(URL url) public static H2AuthConfig parseFrom(URL url)
throws SAXException, IOException, ParserConfigurationException { throws SAXException, IOException, ParserConfigurationException {
...@@ -99,6 +109,15 @@ public class H2AuthConfigXml extends DefaultHandler{ ...@@ -99,6 +109,15 @@ public class H2AuthConfigXml extends DefaultHandler{
} }
} }
/**
* Parse the xml.
*
* @param inputStream the source of the xml configuration.
* @return Authenticator configuration.
* @throws ParserConfigurationException if a parser cannot be created.
* @throws SAXException for SAX errors.
* @throws IOException If an I/O error occurs
*/
public static H2AuthConfig parseFrom(InputStream inputStream) public static H2AuthConfig parseFrom(InputStream inputStream)
throws SAXException, IOException, ParserConfigurationException { throws SAXException, IOException, ParserConfigurationException {
SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
......
...@@ -14,27 +14,45 @@ import java.util.List; ...@@ -14,27 +14,45 @@ import java.util.List;
public class RealmConfig implements HasConfigProperties { public class RealmConfig implements HasConfigProperties {
private String name; private String name;
private String validatorClass;
private List<PropertyConfig> properties;
/**
* Gets realm's name.
*
* @return realm's name.
*/
public String getName() { public String getName() {
return name; return name;
} }
/**
* Sets realm's name.
*
* @param name realm's name.
*/
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
String validatorClass; /**
* Gets validator class name.
*
* @return validator class name.
*/
public String getValidatorClass() { public String getValidatorClass() {
return validatorClass; return validatorClass;
} }
/**
* Sets validator class name.
*
* @param validatorClass validator class name.
*/
public void setValidatorClass(String validatorClass) { public void setValidatorClass(String validatorClass) {
this.validatorClass = validatorClass; this.validatorClass = validatorClass;
} }
List<PropertyConfig> properties;
@Override @Override
public List<PropertyConfig> getProperties() { public List<PropertyConfig> getProperties() {
if (properties == null) { if (properties == null) {
......
...@@ -10,21 +10,31 @@ import java.util.List; ...@@ -10,21 +10,31 @@ import java.util.List;
/** /**
* Configuration for class that maps users to their roles. * Configuration for class that maps users to their roles.
*
* @see org.h2.api.UserToRolesMapper
*/ */
public class UserToRolesMapperConfig implements HasConfigProperties { public class UserToRolesMapperConfig implements HasConfigProperties {
private String className; private String className;
private List<PropertyConfig> properties; private List<PropertyConfig> properties;
/**
* @return Mapper class name.
*/
public String getClassName() { public String getClassName() {
return className; return className;
} }
/**
* @param className mapper class name.
*/
public void setClassName(String className) { public void setClassName(String className) {
this.className = className; this.className = className;
} }
/**
* @return Mapper properties.
*/
@Override @Override
public List<PropertyConfig> getProperties() { public List<PropertyConfig> getProperties() {
if (properties == null) { if (properties == null) {
......
...@@ -218,6 +218,7 @@ public abstract class FilePath { ...@@ -218,6 +218,7 @@ public abstract class FilePath {
* @param append if true, the file will grow, if false, the file will be * @param append if true, the file will grow, if false, the file will be
* truncated first * truncated first
* @return the output stream * @return the output stream
* @throws IOException If an I/O error occurs
*/ */
public abstract OutputStream newOutputStream(boolean append) throws IOException; public abstract OutputStream newOutputStream(boolean append) throws IOException;
...@@ -226,6 +227,7 @@ public abstract class FilePath { ...@@ -226,6 +227,7 @@ public abstract class FilePath {
* *
* @param mode the access mode. Supported are r, rw, rws, rwd * @param mode the access mode. Supported are r, rw, rws, rwd
* @return the file object * @return the file object
* @throws IOException If an I/O error occurs
*/ */
public abstract FileChannel open(String mode) throws IOException; public abstract FileChannel open(String mode) throws IOException;
...@@ -233,6 +235,7 @@ public abstract class FilePath { ...@@ -233,6 +235,7 @@ public abstract class FilePath {
* Create an input stream to read from the file. * Create an input stream to read from the file.
* *
* @return the input stream * @return the input stream
* @throws IOException If an I/O error occurs
*/ */
public abstract InputStream newInputStream() throws IOException; public abstract InputStream newInputStream() throws IOException;
......
...@@ -656,6 +656,13 @@ public abstract class Table extends SchemaObjectBase { ...@@ -656,6 +656,13 @@ public abstract class Table extends SchemaObjectBase {
} }
} }
/**
* Create a new row for a table.
*
* @param data the values.
* @param memory whether the row is in memory.
* @return the created row.
*/
public Row createRow(Value[] data, int memory) { public Row createRow(Value[] data, int memory) {
return database.createRow(data, memory); return database.createRow(data, memory);
} }
......
...@@ -457,6 +457,14 @@ public class DateTimeUtils { ...@@ -457,6 +457,14 @@ public class DateTimeUtils {
return ((((hour * 60L) + minute) * 60) + second) * NANOS_PER_SECOND + nanos; return ((((hour * 60L) + minute) * 60) + second) * NANOS_PER_SECOND + nanos;
} }
/**
* Parse nanoseconds.
*
* @param s String to parse.
* @param start Begin position at the string to read.
* @param end End position at the string to read.
* @return Parsed nanoseconds.
*/
static int parseNanos(String s, int start, int end) { static int parseNanos(String s, int start, int end) {
if (start >= end) { if (start >= end) {
throw new IllegalArgumentException(s); throw new IllegalArgumentException(s);
...@@ -1230,6 +1238,8 @@ public class DateTimeUtils { ...@@ -1230,6 +1238,8 @@ public class DateTimeUtils {
} }
/** /**
* Creates the instance of the {@link ValueTimestampTimeZone} from milliseconds.
*
* @param ms milliseconds since 1970-01-01 (UTC) * @param ms milliseconds since 1970-01-01 (UTC)
* @return timestamp with time zone with specified value and current time zone * @return timestamp with time zone with specified value and current time zone
*/ */
...@@ -1473,6 +1483,11 @@ public class DateTimeUtils { ...@@ -1473,6 +1483,11 @@ public class DateTimeUtils {
} }
} }
/**
* Skip trailing zeroes.
*
* @param buff String buffer.
*/
static void stripTrailingZeroes(StringBuilder buff) { static void stripTrailingZeroes(StringBuilder buff) {
int i = buff.length() - 1; int i = buff.length() - 1;
if (buff.charAt(i) == '0') { if (buff.charAt(i) == '0') {
......
...@@ -665,6 +665,8 @@ public class IntervalUtils { ...@@ -665,6 +665,8 @@ public class IntervalUtils {
} }
/** /**
* Returns years value of interval, if any.
*
* @param qualifier * @param qualifier
* qualifier * qualifier
* @param negative * @param negative
...@@ -688,6 +690,8 @@ public class IntervalUtils { ...@@ -688,6 +690,8 @@ public class IntervalUtils {
} }
/** /**
* Returns months value of interval, if any.
*
* @param qualifier * @param qualifier
* qualifier * qualifier
* @param negative * @param negative
...@@ -715,6 +719,8 @@ public class IntervalUtils { ...@@ -715,6 +719,8 @@ public class IntervalUtils {
} }
/** /**
* Returns days value of interval, if any.
*
* @param qualifier * @param qualifier
* qualifier * qualifier
* @param negative * @param negative
...@@ -723,7 +729,7 @@ public class IntervalUtils { ...@@ -723,7 +729,7 @@ public class IntervalUtils {
* value of leading field * value of leading field
* @param remaining * @param remaining
* values of all remaining fields * values of all remaining fields
* @return months, or 0 * @return days, or 0
*/ */
public static long daysFromInterval(IntervalQualifier qualifier, boolean negative, long leading, long remaining) { public static long daysFromInterval(IntervalQualifier qualifier, boolean negative, long leading, long remaining) {
switch (qualifier) { switch (qualifier) {
...@@ -742,6 +748,8 @@ public class IntervalUtils { ...@@ -742,6 +748,8 @@ public class IntervalUtils {
} }
/** /**
* Returns hours value of interval, if any.
*
* @param qualifier * @param qualifier
* qualifier * qualifier
* @param negative * @param negative
...@@ -779,6 +787,8 @@ public class IntervalUtils { ...@@ -779,6 +787,8 @@ public class IntervalUtils {
} }
/** /**
* Returns minutes value of interval, if any.
*
* @param qualifier * @param qualifier
* qualifier * qualifier
* @param negative * @param negative
...@@ -819,6 +829,8 @@ public class IntervalUtils { ...@@ -819,6 +829,8 @@ public class IntervalUtils {
} }
/** /**
* Returns nanoseconds value of interval, if any.
*
* @param qualifier * @param qualifier
* qualifier * qualifier
* @param negative * @param negative
......
...@@ -35,7 +35,14 @@ import org.h2.value.ValueNull; ...@@ -35,7 +35,14 @@ import org.h2.value.ValueNull;
*/ */
public class ValueHashMap<V> extends HashBase { public class ValueHashMap<V> extends HashBase {
/**
* Keys array.
*/
Value[] keys; Value[] keys;
/**
* Values array.
*/
V[] values; V[] values;
@Override @Override
...@@ -202,6 +209,11 @@ public class ValueHashMap<V> extends HashBase { ...@@ -202,6 +209,11 @@ public class ValueHashMap<V> extends HashBase {
} }
} }
/**
* Gets all map's entries.
*
* @return all map's entries.
*/
public Iterable<Map.Entry<Value, V>> entries() { public Iterable<Map.Entry<Value, V>> entries() {
return new EntryIterable(); return new EntryIterable();
} }
......
...@@ -269,7 +269,7 @@ public final class EWKBUtils { ...@@ -269,7 +269,7 @@ public final class EWKBUtils {
* *
* @param ewkb * @param ewkb
* source EWKB * source EWKB
* @param dimension * @param dimensionSystem
* dimension system * dimension system
* @return canonical EWKB, may be the same as the source * @return canonical EWKB, may be the same as the source
*/ */
......
...@@ -563,7 +563,7 @@ public final class EWKTUtils { ...@@ -563,7 +563,7 @@ public final class EWKTUtils {
* *
* @param ewkb * @param ewkb
* source EWKB * source EWKB
* @param dimension * @param dimensionSystem
* dimension system * dimension system
* @return EWKT representation * @return EWKT representation
*/ */
...@@ -594,7 +594,7 @@ public final class EWKTUtils { ...@@ -594,7 +594,7 @@ public final class EWKTUtils {
* *
* @param ewkt * @param ewkt
* source EWKT * source EWKT
* @param dimension * @param dimensionSystem
* dimension system * dimension system
* @return EWKB representation * @return EWKB representation
*/ */
...@@ -608,7 +608,7 @@ public final class EWKTUtils { ...@@ -608,7 +608,7 @@ public final class EWKTUtils {
/** /**
* Parses a EWKB. * Parses a EWKB.
* *
* @param source * @param ewkt
* source EWKT * source EWKT
* @param target * @param target
* output target * output target
......
...@@ -40,7 +40,7 @@ import org.h2.util.StringUtils; ...@@ -40,7 +40,7 @@ import org.h2.util.StringUtils;
* @author Noel Grandin * @author Noel Grandin
* @author Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888 * @author Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888
*/ */
public abstract class Value { public abstract class Value extends VersionedValue {
/** /**
* The data type is unknown at this time. * The data type is unknown at this time.
...@@ -1347,6 +1347,12 @@ public abstract class Value { ...@@ -1347,6 +1347,12 @@ public abstract class Value {
return ValueResultSet.get(result); return ValueResultSet.get(result);
} }
/**
* Creates new instance of the DbException for data conversion error.
*
* @param targetType Target data type.
* @return instance of the DbException.
*/
DbException getDataConversionError(int targetType) { DbException getDataConversionError(int targetType) {
DataType from = DataType.getDataType(getType()); DataType from = DataType.getDataType(getType());
DataType to = DataType.getDataType(targetType); DataType to = DataType.getDataType(targetType);
...@@ -1489,6 +1495,13 @@ public abstract class Value { ...@@ -1489,6 +1495,13 @@ public abstract class Value {
return (short) x; return (short) x;
} }
/**
* Checks value by Integer type numeric range.
*
* @param x integer value.
* @param column Column info.
* @return x
*/
public static int convertToInt(long x, Object column) { public static int convertToInt(long x, Object column) {
if (x > Integer.MAX_VALUE || x < Integer.MIN_VALUE) { if (x > Integer.MAX_VALUE || x < Integer.MIN_VALUE) {
throw DbException.get( throw DbException.get(
......
...@@ -16,6 +16,9 @@ import org.h2.util.MathUtils; ...@@ -16,6 +16,9 @@ import org.h2.util.MathUtils;
*/ */
public abstract class ValueCollectionBase extends Value { public abstract class ValueCollectionBase extends Value {
/**
* Values.
*/
final Value[] values; final Value[] values;
private int hash; private int hash;
......
...@@ -53,6 +53,8 @@ public class ValueInterval extends Value { ...@@ -53,6 +53,8 @@ public class ValueInterval extends Value {
private final long remaining; private final long remaining;
/** /**
* Creates interval value.
*
* @param qualifier * @param qualifier
* qualifier * qualifier
* @param negative * @param negative
...@@ -80,6 +82,7 @@ public class ValueInterval extends Value { ...@@ -80,6 +82,7 @@ public class ValueInterval extends Value {
* @param scale * @param scale
* fractional seconds precision. Ignored if specified type of * fractional seconds precision. Ignored if specified type of
* interval does not have seconds. * interval does not have seconds.
* @return displayed size.
*/ */
public static int getDisplaySize(int type, int precision, int scale) { public static int getDisplaySize(int type, int precision, int scale) {
switch (type) { switch (type) {
......
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
/**
* A versioned value (possibly null).
* It contains current value and latest committed value if current one is uncommitted.
* Also for uncommitted values it contains operationId - a combination of
* transactionId and logId.
*/
public class VersionedValue {
public static final VersionedValue DUMMY = new VersionedValue();
protected VersionedValue() {}
public boolean isCommitted() {
return true;
}
public long getOperationId() {
return 0L;
}
public Object getCurrentValue() {
return this;
}
public Object getCommittedValue() {
return this;
}
}
...@@ -440,6 +440,10 @@ java org.h2.test.TestAll timer ...@@ -440,6 +440,10 @@ java org.h2.test.TestAll timer
private Server server; private Server server;
/**
* The map of executed tests to detect not executed tests.
* Boolean value is 'false' for a disabled test.
*/
HashMap<Class<? extends TestBase>, Boolean> executedTests = new HashMap<>(); HashMap<Class<? extends TestBase>, Boolean> executedTests = new HashMap<>();
/** /**
......
...@@ -185,7 +185,7 @@ public class TestSQLXML extends TestDb { ...@@ -185,7 +185,7 @@ public class TestSQLXML extends TestDb {
} }
} }
void testSettersImpl(SQLXML sqlxml) throws SQLException { private void testSettersImpl(SQLXML sqlxml) throws SQLException {
PreparedStatement prep = conn.prepareStatement("UPDATE TEST SET X = ?"); PreparedStatement prep = conn.prepareStatement("UPDATE TEST SET X = ?");
prep.setSQLXML(1, sqlxml); prep.setSQLXML(1, sqlxml);
assertEquals(1, prep.executeUpdate()); assertEquals(1, prep.executeUpdate());
......
...@@ -289,7 +289,7 @@ public class TestScript extends TestDb { ...@@ -289,7 +289,7 @@ public class TestScript extends TestDb {
return s; return s;
} }
public void putBack(String line) { private void putBack(String line) {
putBack.addLast(line); putBack.addLast(line);
} }
......
...@@ -466,3 +466,46 @@ DROP TABLE TEST; ...@@ -466,3 +466,46 @@ DROP TABLE TEST;
SELECT 1 = ALL (SELECT * FROM VALUES (NULL), (1), (2), (NULL) ORDER BY 1); SELECT 1 = ALL (SELECT * FROM VALUES (NULL), (1), (2), (NULL) ORDER BY 1);
>> FALSE >> FALSE
CREATE TABLE TEST(G INT, V INT);
> ok
INSERT INTO TEST VALUES (10, 1), (11, 2), (20, 4);
> update count: 3
SELECT G / 10 G1, G / 10 G2, SUM(T.V) S FROM TEST T GROUP BY G / 10, G / 10;
> G1 G2 S
> -- -- -
> 1 1 3
> 2 2 4
> rows: 2
SELECT G / 10 G1, G / 10 G2, SUM(T.V) S FROM TEST T GROUP BY G2;
> G1 G2 S
> -- -- -
> 1 1 3
> 2 2 4
> rows: 2
DROP TABLE TEST;
> ok
@reconnect off
CALL RAND(0);
>> 0.730967787376657
SELECT RAND(), RAND() + 1, RAND() + 1, RAND() GROUP BY RAND() + 1;
> RAND() RAND() + 1 RAND() + 1 RAND()
> ------------------ ------------------ ------------------ ------------------
> 0.6374174253501083 1.2405364156714858 1.2405364156714858 0.5504370051176339
> rows: 1
SELECT RAND() A, RAND() + 1 B, RAND() + 1 C, RAND() D, RAND() + 2 E, RAND() + 3 F GROUP BY B, C, E, F;
> A B C D E F
> ------------------ ------------------ ------------------ ------------------ ------------------ ------------------
> 0.8791825178724801 1.3332183994766498 1.3332183994766498 0.9412491794821144 2.3851891847407183 3.9848415401998087
> rows: 1
@reconnect on
...@@ -50,6 +50,7 @@ public class TestLocalResultFactory extends TestBase { ...@@ -50,6 +50,7 @@ public class TestLocalResultFactory extends TestBase {
* Test local result factory. * Test local result factory.
*/ */
public static class MyTestLocalResultFactory extends LocalResultFactory { public static class MyTestLocalResultFactory extends LocalResultFactory {
/** Call counter for the factory methods. */
static final AtomicInteger COUNTER = new AtomicInteger(); static final AtomicInteger COUNTER = new AtomicInteger();
@Override public LocalResult create(Session session, Expression[] expressions, int visibleColumnCount) { @Override public LocalResult create(Session session, Expression[] expressions, int visibleColumnCount) {
......
...@@ -483,7 +483,7 @@ public class TestValue extends TestDb { ...@@ -483,7 +483,7 @@ public class TestValue extends TestDb {
return lob1.compareTypeSafe(lob2, null); return lob1.compareTypeSafe(lob2, null);
} }
static Value createLob(DataHandler dh, int type, byte[] bytes) { private static Value createLob(DataHandler dh, int type, byte[] bytes) {
if (dh == null) { if (dh == null) {
return ValueLobDb.createSmallLob(type, bytes); return ValueLobDb.createSmallLob(type, bytes);
} }
......
...@@ -668,7 +668,9 @@ public class Build extends BuildBase { ...@@ -668,7 +668,9 @@ public class Build extends BuildBase {
File.pathSeparator + "ext/lucene-queryparser-5.5.5.jar" + File.pathSeparator + "ext/lucene-queryparser-5.5.5.jar" +
File.pathSeparator + "ext/org.osgi.core-4.2.0.jar" + File.pathSeparator + "ext/org.osgi.core-4.2.0.jar" +
File.pathSeparator + "ext/org.osgi.enterprise-4.2.0.jar" + File.pathSeparator + "ext/org.osgi.enterprise-4.2.0.jar" +
File.pathSeparator + "ext/jts-core-1.15.0.jar", File.pathSeparator + "ext/jts-core-1.15.0.jar" +
File.pathSeparator + "ext/asm-6.1.jar" +
File.pathSeparator + "ext/junit-4.12.jar",
"-subpackages", "org.h2"); "-subpackages", "org.h2");
mkdir("docs/javadocImpl3"); mkdir("docs/javadocImpl3");
...@@ -701,7 +703,9 @@ public class Build extends BuildBase { ...@@ -701,7 +703,9 @@ public class Build extends BuildBase {
File.pathSeparator + "ext/lucene-queryparser-5.5.5.jar" + File.pathSeparator + "ext/lucene-queryparser-5.5.5.jar" +
File.pathSeparator + "ext/org.osgi.core-4.2.0.jar" + File.pathSeparator + "ext/org.osgi.core-4.2.0.jar" +
File.pathSeparator + "ext/org.osgi.enterprise-4.2.0.jar" + File.pathSeparator + "ext/org.osgi.enterprise-4.2.0.jar" +
File.pathSeparator + "ext/jts-core-1.15.0.jar", File.pathSeparator + "ext/jts-core-1.15.0.jar" +
File.pathSeparator + "ext/asm-6.1.jar" +
File.pathSeparator + "ext/junit-4.12.jar",
"-subpackages", "org.h2", "-subpackages", "org.h2",
"-package", "-package",
"-docletpath", "bin" + File.pathSeparator + "temp", "-docletpath", "bin" + File.pathSeparator + "temp",
......
...@@ -805,3 +805,4 @@ queryparser tokenized freeze factorings recompilation unenclosed rfe dsync ...@@ -805,3 +805,4 @@ queryparser tokenized freeze factorings recompilation unenclosed rfe dsync
econd irst bcef ordinality nord unnest econd irst bcef ordinality nord unnest
analyst occupation distributive josaph aor engineer sajeewa isuru randil kevin doctor businessman artist ashan analyst occupation distributive josaph aor engineer sajeewa isuru randil kevin doctor businessman artist ashan
corrupts splitted disruption unintentional octets preconditions predicates subq objectweb insn opcodes corrupts splitted disruption unintentional octets preconditions predicates subq objectweb insn opcodes
preserves
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论