提交 2067590e authored 作者: andrei's avatar andrei

Merge remote-tracking branch 'h2database/master' into non_blocking

# Conflicts:
#	h2/src/main/org/h2/mvstore/DataUtils.java
#	h2/src/main/org/h2/mvstore/MVStore.java
#	h2/src/main/org/h2/mvstore/Page.java
......@@ -4,7 +4,7 @@
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.196-SNAPSHOT</version>
<version>1.4.197-SNAPSHOT</version>
<packaging>jar</packaging>
<name>H2 Database Engine</name>
<url>http://www.h2database.com</url>
......
......@@ -21,8 +21,24 @@ Change Log
<h2>Next Version (unreleased)</h2>
<ul>
<li>PR #989: Fix more issues with range table and improve its documentation
</li>
</ul>
<h2>Version 1.4.197 (2018-03-18)</h2>
<ul>
<li>PR #988: Fix RangeTable.getRowCount() for non-default step
</li>
<li>PR #987: ValueBoolean constants are not cleared and may be used directly
</li>
<li>PR #986: Check parameters in JdbcPreparedStatement.addBatch()
</li>
<li>PR #984: Minor refactorings in Parser
</li>
<li>PR #983: Code cleanups via IntelliJ IDEA inspections
</li>
<li>Issue #960: Implement remaining time unit in "date_trunc" function
</li>
<li>Issue #933: MVStore background writer endless loop
</li>
<li>PR #981: Reorganize date-time functions
......
......@@ -37,12 +37,27 @@ of all tables in the database as well as the current settings.
<h2 id="range_table" class="notranslate">Range Table</h2>
<p>
The range table is a dynamic system table that contains all values from a start to an end value.
The table contains one column called X. Both the start and end values are included in the result.
Non-zero step value may be also specified, default is 1.
Start value, end value, and optional step value are converted to BIGINT data type.
The table contains one column called X.
If start value is greater than end value and step is positive the result is empty.
If start value is less than end value and step is negative the result is empty too.
If start value is equal to end value the result contains only start value.
Start value, start value plus step, start value plus step multiplied by two and so on are included in result.
If step is positive the last value is less than or equal to the specified end value.
If step in negative the last value is greater than or equal to the specified end value.
The table is used as follows:
</p>
<p>Example:</p>
<p>Examples:</p>
<pre>
SELECT X FROM SYSTEM_RANGE(1, 10);
-- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
SELECT X FROM SYSTEM_RANGE(1, 10, 2);
-- 1, 3, 5, 7, 9
SELECT X FROM SYSTEM_RANGE(1, 10, -1);
-- No rows
SELECT X FROM SYSTEM_RANGE(10, 2, -2);
-- 10, 8, 6, 4, 2
</pre>
<!-- [close] { --></div></td></tr></table><!-- } --><!-- analytics --></body></html>
......@@ -79,6 +79,9 @@ The following can be skipped currently; benchmarks should probably be removed:
## Build the Release
Switch to Java 1.7.
In Build.java, comment "-Xdoclint:none", but don't commit that change.
Run the following commands:
Non-Windows:
......@@ -110,21 +113,23 @@ Newsletter: send (always to BCC!), the following:
Create tweet at http://twitter.com
Sign files and publish files on Maven Central
(check java version is 1.7)
## Sign files and publish files on Maven Central
Switch to Java 1.7.
In Build.java, comment "-Xdoclint:none", but don't commit that change.
./build.sh clean compile jar mavenDeployCentral
cd /data/h2database/m2-repo/com/h2database
# remove sha and md5 files:
find . -name "*.sha1" -delete
find . -name "*.md5" -delete
cd h2/1...
cd h2/1<latest>
# for each file separately (-javadoc.jar, -sources.jar, .jar, .pom):
gpg -u "Thomas Mueller Graf <thomas.tom.mueller@gmail.com>" -ab h2-...
gpg -u "Thomas Mueller Graf <thomas.tom.mueller@gmail.com>" -ab h2-<...>
jar -cvf bundle.jar h2-*
cd ../../h2-mvstore/1...
cd ../../h2-mvstore/1<latest>
# for each file separately (-javadoc.jar, -sources.jar, .jar, .pom):
gpg -u "Thomas Mueller Graf <thomas.tom.mueller@gmail.com>" -ab h2-mvstore...
gpg -u "Thomas Mueller Graf <thomas.tom.mueller@gmail.com>" -ab h2-mvstore<...>
jar -cvf bundle.jar h2-*
# http://central.sonatype.org/pages/ossrh-guide.html
# http://central.sonatype.org/pages/manual-staging-bundle-creation-and-deployment.html
......
......@@ -362,7 +362,7 @@ public class Bnf {
* @return the tokenizer
*/
public static StringTokenizer getTokenizer(String s) {
return new StringTokenizer(s, " [](){}|.,\r\n<>:-+*/=<\">!'$", true);
return new StringTokenizer(s, " [](){}|.,\r\n<>:-+*/=\"!'$", true);
}
}
......@@ -58,7 +58,7 @@ public class DbSchema {
DbSchema(DbContents contents, String name, boolean isDefault) {
this.contents = contents;
this.name = name;
this.quotedName = contents.quoteIdentifier(name);
this.quotedName = contents.quoteIdentifier(name);
this.isDefault = isDefault;
if (name == null) {
// firebird
......
......@@ -370,8 +370,7 @@ public abstract class Command implements CommandInterface {
public void reuse() {
canReuse = false;
ArrayList<? extends ParameterInterface> parameters = getParameters();
for (int i = 0, size = parameters.size(); i < size; i++) {
ParameterInterface param = parameters.get(i);
for (ParameterInterface param : parameters) {
param.setValue(null, true);
}
}
......
......@@ -285,13 +285,7 @@ public class Parser {
if (hasMore) {
String remaining = originalSQL.substring(parseIndex);
if (remaining.trim().length() != 0) {
CommandList list = new CommandList(this, sql, c, remaining);
// list.addCommand(c);
// do {
// c = parseCommand();
// list.addCommand(c);
// } while (currentToken.equals(";"));
c = list;
c = new CommandList(this, sql, c, remaining);
}
}
return c;
......@@ -1135,9 +1129,9 @@ public class Parser {
command.setQuery(parseSelect());
read(")");
}
command.setQueryAlias(readFromAlias(null, Arrays.asList("ON")));
command.setQueryAlias(readFromAlias(null, Collections.singletonList("ON")));
String[] querySQLOutput = new String[]{null};
String[] querySQLOutput = {null};
List<Column> columnTemplateList = TableView.createQueryColumnTemplateList(null, command.getQuery(),
querySQLOutput);
TableView temporarySourceTableView = createCTEView(
......@@ -1152,7 +1146,7 @@ public class Parser {
command.setSourceTableFilter(sourceTableFilter);
} else {
/* Its a table name, simulate a query by building a select query for the table */
List<String> excludeIdentifiers = Arrays.asList("ON");
List<String> excludeIdentifiers = Collections.singletonList("ON");
TableFilter sourceTableFilter = readSimpleTableFilter(0, excludeIdentifiers);
command.setSourceTableFilter(sourceTableFilter);
......@@ -1206,8 +1200,7 @@ public class Parser {
StringBuilder targetMatchQuerySQL = new StringBuilder(
"SELECT _ROWID_ FROM " + command.getTargetTable().getName());
if (command.getTargetTableFilter().getTableAlias() != null) {
targetMatchQuerySQL.append(
" AS " + command.getTargetTableFilter().getTableAlias());
targetMatchQuerySQL.append(" AS ").append(command.getTargetTableFilter().getTableAlias());
}
targetMatchQuerySQL
.append(" WHERE ").append(command.getOnCondition().getSQL());
......@@ -2137,8 +2130,7 @@ public class Parser {
query.setNeverLazy(true);
return query;
}
Select select = parseSelectSimple();
return select;
return parseSelectSimple();
}
private void parseSelectSimpleFromPart(Select command) {
......@@ -2443,7 +2435,7 @@ public class Parser {
if (database.getMode().prohibitEmptyInPredicate) {
throw getSyntaxError();
}
r = ValueExpression.get(ValueBoolean.get(false));
r = ValueExpression.get(ValueBoolean.FALSE);
} else {
if (isSelect()) {
Query query = parseSelect();
......@@ -2533,7 +2525,7 @@ public class Parser {
} else {
rightFilter.mapAndAddFilter(r);
}
r = ValueExpression.get(ValueBoolean.get(true));
r = ValueExpression.get(ValueBoolean.TRUE);
}
}
} else {
......@@ -2684,8 +2676,7 @@ public class Parser {
ArrayList<SelectOrderBy> orderList = New.arrayList();
do {
SelectOrderBy order = new SelectOrderBy();
Expression expr = readExpression();
order.expression = expr;
order.expression = readExpression();
if (readIf("DESC")) {
order.descending = true;
} else {
......@@ -2717,8 +2708,7 @@ public class Parser {
argList.add(readExpression());
}
args = argList.toArray(new Expression[0]);
JavaFunction func = new JavaFunction(functionAlias, args);
return func;
return new JavaFunction(functionAlias, args);
}
private JavaAggregate readJavaAggregate(UserAggregate aggregate) {
......@@ -2930,8 +2920,7 @@ public class Parser {
if (database.isAllowBuiltinAliasOverride()) {
FunctionAlias functionAlias = database.getSchema(session.getCurrentSchemaName()).findFunction(name);
if (functionAlias != null) {
JavaFunction func = new JavaFunction(functionAlias, new Expression[0]);
return func;
return new JavaFunction(functionAlias, new Expression[0]);
}
}
Function function = Function.getFunction(database, name);
......@@ -3280,11 +3269,11 @@ public class Parser {
break;
case TRUE:
read();
r = ValueExpression.get(ValueBoolean.get(true));
r = ValueExpression.get(ValueBoolean.TRUE);
break;
case FALSE:
read();
r = ValueExpression.get(ValueBoolean.get(false));
r = ValueExpression.get(ValueBoolean.FALSE);
break;
case ROWNUM:
read();
......@@ -3331,8 +3320,7 @@ public class Parser {
throw getSyntaxError();
}
Expression[] args = { r };
JavaFunction func = new JavaFunction(f, args);
r = func;
r = new JavaFunction(f, args);
} else {
Column col = parseColumnWithType(null);
Function function = Function.getFunction(database, "CAST");
......@@ -3465,8 +3453,7 @@ public class Parser {
if (!(expr instanceof ValueExpression)) {
throw DbException.getSyntaxError(sqlCommand, parseIndex, "string");
}
String s = expr.getValue(session).getString();
return s;
return expr.getValue(session).getString();
}
// TODO: why does this function allow defaultSchemaName=null - which resets
......@@ -3575,23 +3562,15 @@ public class Parser {
private boolean equalsToken(String a, String b) {
if (a == null) {
return b == null;
} else if (a.equals(b)) {
return true;
} else if (!identifiersToUpper && a.equalsIgnoreCase(b)) {
return true;
}
return false;
} else
return a.equals(b) || !identifiersToUpper && a.equalsIgnoreCase(b);
}
private static boolean equalsTokenIgnoreCase(String a, String b) {
if (a == null) {
return b == null;
} else if (a.equals(b)) {
return true;
} else if (a.equalsIgnoreCase(b)) {
return true;
}
return false;
} else
return a.equals(b) || a.equalsIgnoreCase(b);
}
private boolean isTokenInList(Collection<String> upperCaseTokenList) {
......@@ -4843,8 +4822,8 @@ public class Parser {
} while (readIf(","));
int columnCount = columns.size();
int rowCount = rows.size();
for (int i = 0; i < rowCount; i++) {
if (rows.get(i).size() != columnCount) {
for (ArrayList<Expression> row : rows) {
if (row.size() != columnCount) {
throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
}
}
......@@ -4864,10 +4843,9 @@ public class Parser {
tf.setColumns(columns);
tf.doneWithParameters();
Table table = new FunctionTable(mainSchema, session, tf, tf);
TableFilter filter = new TableFilter(session, table, null,
return new TableFilter(session, table, null,
rightsChecked, currentSelect, orderInFrom,
null);
return filter;
}
private Call parseCall() {
......@@ -5218,7 +5196,6 @@ public class Parser {
Table recursiveTable = null;
ArrayList<Column> columns = New.arrayList();
String[] cols = null;
Database db = database;
// column names are now optional - they can be inferred from the named
// query, if not supplied by user
......@@ -5264,9 +5241,9 @@ public class Parser {
* data and table if we don't have a working CTE already.
*/
recursiveTable = TableView.createShadowTableForRecursiveTableExpression(
isPersistent, session, cteViewName, schema, columns, db);
isPersistent, session, cteViewName, schema, columns, database);
List<Column> columnTemplateList;
String[] querySQLOutput = new String[]{null};
String[] querySQLOutput = {null};
try {
read("AS");
read("(");
......@@ -5281,13 +5258,11 @@ public class Parser {
TableView.destroyShadowTableForRecursiveExpression(isPersistent, session, recursiveTable);
}
TableView view = createCTEView(cteViewName,
return createCTEView(cteViewName,
querySQLOutput[0], columnTemplateList,
true/* allowRecursiveQueryDetection */,
true/* add to session */,
isPersistent, session);
return view;
}
private TableView createCTEView(String cteViewName, String querySQL,
......
......@@ -166,8 +166,7 @@ public abstract class Prepared {
*/
protected void checkParameters() {
if (parameters != null) {
for (int i = 0, size = parameters.size(); i < size; i++) {
Parameter param = parameters.get(i);
for (Parameter param : parameters) {
param.checkSet();
}
}
......
......@@ -6,6 +6,7 @@
package org.h2.command.ddl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
......@@ -340,9 +341,7 @@ public class AlterTableAddConstraint extends SchemaCommand {
}
Column[] indexCols = idx.getColumns();
HashSet<Column> indexColsSet = new HashSet<>();
for (Column c : indexCols) {
indexColsSet.add(c);
}
Collections.addAll(indexColsSet, indexCols);
HashSet<Column> colsSet = new HashSet<>();
for (IndexColumn c : cols) {
colsSet.add(c.column);
......
......@@ -7,7 +7,6 @@ package org.h2.command.ddl;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.command.Parser;
......@@ -343,8 +342,7 @@ public class AlterTableAlterColumn extends CommandWithColumns {
if (type == CommandInterface.ALTER_TABLE_DROP_COLUMN) {
for (Column removeCol : columnsToRemove) {
Column foundCol = null;
for (Iterator<Column> it = newColumns.iterator(); it.hasNext();) {
Column newCol = it.next();
for (Column newCol : newColumns) {
if (newCol.getName().equals(removeCol.getName())) {
foundCol = newCol;
break;
......
......@@ -95,8 +95,9 @@ public class DropTable extends SchemaCommand {
}
}
}
if (buff.length() > 0)
if (buff.length() > 0) {
throw DbException.get(ErrorCode.CANNOT_DROP_2, tableName, buff.toString());
}
}
table.lock(session, true, true);
......@@ -142,4 +143,4 @@ public class DropTable extends SchemaCommand {
return CommandInterface.DROP_TABLE;
}
}
\ No newline at end of file
}
......@@ -97,14 +97,9 @@ class Optimizer {
}
private boolean canStop(int x) {
if ((x & 127) == 0) {
long t = System.nanoTime() - startNs;
// don't calculate for simple queries (no rows or so)
if (cost >= 0 && 10 * t > cost * TimeUnit.MILLISECONDS.toNanos(1)) {
return true;
}
}
return false;
return (x & 127) == 0
&& cost >= 0 // don't calculate for simple queries (no rows or so)
&& 10 * (System.nanoTime() - startNs) > cost * TimeUnit.MILLISECONDS.toNanos(1);
}
private void calculateBruteForceAll() {
......
......@@ -429,8 +429,7 @@ public abstract class Query extends Prepared {
found = false;
if (filters != null) {
// select id from test order by test.id
for (int i = 0, size = filters.size(); i < size; i++) {
TableFilter f = filters.get(i);
for (TableFilter f : filters) {
if (db.equalsIdentifiers(f.getTableAlias(), tableAlias)) {
found = true;
break;
......@@ -487,8 +486,7 @@ public abstract class Query extends Prepared {
expressionSQL.add(sql);
}
o.columnIndexExpr = ValueExpression.get(ValueInt.get(idx + 1));
Expression expr = expressions.get(idx).getNonAliasExpression();
o.expression = expr;
o.expression = expressions.get(idx).getNonAliasExpression();
}
}
......
......@@ -232,10 +232,7 @@ public class Select extends Query {
}
private boolean isHavingNullOrFalse(Value[] row) {
if (havingIndex >= 0) {
return !row[havingIndex].getBoolean();
}
return false;
return havingIndex >= 0 && !row[havingIndex].getBoolean();
}
private Index getGroupSortedIndex() {
......@@ -244,8 +241,7 @@ public class Select extends Query {
}
ArrayList<Index> indexes = topTableFilter.getTable().getIndexes();
if (indexes != null) {
for (int i = 0, size = indexes.size(); i < size; i++) {
Index index = indexes.get(i);
for (Index index : indexes) {
if (index.getIndexType().isScan()) {
continue;
}
......@@ -348,8 +344,7 @@ public class Select extends Query {
}
currentGroup = values;
currentGroupRowId++;
int len = columnCount;
for (int i = 0; i < len; i++) {
for (int i = 0; i < columnCount; i++) {
if (groupByExpression == null || !groupByExpression[i]) {
Expression expr = expressions.get(i);
expr.updateAggregate(session);
......@@ -426,8 +421,7 @@ public class Select extends Query {
ArrayList<Index> list = topTableFilter.getTable().getIndexes();
if (list != null) {
int[] sortTypes = sort.getSortTypesWithNullPosition();
for (int i = 0, size = list.size(); i < size; i++) {
Index index = list.get(i);
for (Index index : list) {
if (index.getCreateSQL() == null) {
// can't use the scan index
continue;
......@@ -1009,8 +1003,7 @@ public class Select extends Query {
@Override
public void fireBeforeSelectTriggers() {
for (int i = 0, size = filters.size(); i < size; i++) {
TableFilter filter = filters.get(i);
for (TableFilter filter : filters) {
filter.getTable().fire(session, Trigger.SELECT, true);
}
}
......@@ -1086,7 +1079,6 @@ public class Select extends Query {
// skip the generation of plan SQL for this already recursive persistent CTEs,
// since using a with statement will re-create the common table expression
// views.
continue;
} else {
buff.append("WITH RECURSIVE ").append(t.getName()).append('(');
buff.resetCount();
......@@ -1334,8 +1326,7 @@ public class Select extends Query {
if (isForUpdate) {
return false;
}
for (int i = 0, size = filters.size(); i < size; i++) {
TableFilter f = filters.get(i);
for (TableFilter f : filters) {
if (!f.getTable().isDeterministic()) {
return false;
}
......@@ -1343,8 +1334,7 @@ public class Select extends Query {
break;
}
case ExpressionVisitor.SET_MAX_DATA_MODIFICATION_ID: {
for (int i = 0, size = filters.size(); i < size; i++) {
TableFilter f = filters.get(i);
for (TableFilter f : filters) {
long m = f.getTable().getMaxDataModificationId();
visitor.addDataModificationId(m);
}
......@@ -1357,8 +1347,7 @@ public class Select extends Query {
break;
}
case ExpressionVisitor.GET_DEPENDENCIES: {
for (int i = 0, size = filters.size(); i < size; i++) {
TableFilter f = filters.get(i);
for (TableFilter f : filters) {
Table table = f.getTable();
visitor.addDependency(table);
table.addDependencies(visitor.getDependencies());
......@@ -1369,8 +1358,7 @@ public class Select extends Query {
}
ExpressionVisitor v2 = visitor.incrementQueryLevel(1);
boolean result = true;
for (int i = 0, size = expressions.size(); i < size; i++) {
Expression e = expressions.get(i);
for (Expression e : expressions) {
if (!e.isEverything(v2)) {
result = false;
break;
......@@ -1403,10 +1391,7 @@ public class Select extends Query {
@Override
public boolean allowGlobalConditions() {
if (offsetExpr == null && (limitExpr == null || sort == null)) {
return true;
}
return false;
return offsetExpr == null && (limitExpr == null || sort == null);
}
public SortOrder getSortOrder() {
......
......@@ -194,8 +194,7 @@ public class Update extends Prepared {
public String getPlanSQL() {
StatementBuilder buff = new StatementBuilder("UPDATE ");
buff.append(targetTableFilter.getPlanSQL(false)).append("\nSET\n ");
for (int i = 0, size = columns.size(); i < size; i++) {
Column c = columns.get(i);
for (Column c : columns) {
Expression e = expressionMap.get(c);
buff.appendExceptFirst(",\n ");
buff.append(c.getName()).append(" = ").append(e.getSQL());
......@@ -217,8 +216,7 @@ public class Update extends Prepared {
condition = condition.optimize(session);
condition.createIndexConditions(session, targetTableFilter);
}
for (int i = 0, size = columns.size(); i < size; i++) {
Column c = columns.get(i);
for (Column c : columns) {
Expression e = expressionMap.get(c);
e.mapColumns(targetTableFilter, 0);
if (sourceTableFilter!=null){
......
......@@ -376,10 +376,10 @@ public class ConnectionInfo implements Cloneable {
if (nameNormalized == null) {
if (!SysProperties.IMPLICIT_RELATIVE_PATH) {
if (!FileUtils.isAbsolute(name)) {
if (name.indexOf("./") < 0 &&
name.indexOf(".\\") < 0 &&
name.indexOf(":/") < 0 &&
name.indexOf(":\\") < 0) {
if (!name.contains("./") &&
!name.contains(".\\") &&
!name.contains(":/") &&
!name.contains(":\\")) {
// the name could start with "./", or
// it could start with a prefix such as "nio:./"
// for Windows, the path "\test" is not considered
......@@ -456,7 +456,7 @@ public class ConnectionInfo implements Cloneable {
*/
String getProperty(String key) {
Object value = prop.get(key);
if (value == null || !(value instanceof String)) {
if (!(value instanceof String)) {
return null;
}
return value.toString();
......
......@@ -15,22 +15,22 @@ public class Constants {
/**
* The build date is updated for each public release.
*/
public static final String BUILD_DATE = "2017-06-10";
public static final String BUILD_DATE = "2018-03-18";
/**
* The build date of the last stable release.
*/
public static final String BUILD_DATE_STABLE = "2017-04-23";
public static final String BUILD_DATE_STABLE = "2017-06-10";
/**
* The build id is incremented for each public release.
*/
public static final int BUILD_ID = 196;
public static final int BUILD_ID = 197;
/**
* The build id of the last stable release.
*/
public static final int BUILD_ID_STABLE = 195;
public static final int BUILD_ID_STABLE = 196;
/**
* Whether this is a snapshot version.
......@@ -101,7 +101,7 @@ public class Constants {
/**
* The TCP protocol version number 17.
* @since 1.4.197 (TODO)
* @since 1.4.197 (2018-03-18)
*/
public static final int TCP_PROTOCOL_VERSION_17 = 17;
......
......@@ -934,8 +934,7 @@ public class Database implements DataHandler {
+ session +", sessionid="+ session.getId() + " on same thread");
}
}
boolean wasLocked = meta.lock(session, true, true);
return wasLocked;
return meta.lock(session, true, true);
}
/**
......@@ -2871,13 +2870,7 @@ public class Database implements DataHandler {
* @return true if they match
*/
public boolean equalsIdentifiers(String a, String b) {
if (a == b || a.equals(b)) {
return true;
}
if (!dbSettings.databaseToUpper && a.equalsIgnoreCase(b)) {
return true;
}
return false;
return a.equals(b) || (!dbSettings.databaseToUpper && a.equalsIgnoreCase(b));
}
@Override
......
......@@ -44,7 +44,7 @@ public class Mode {
* Multiple rows with identical values in indexed columns are not allowed in
* unique index.
*/
FORBID_ANY_DUPLICATES;
FORBID_ANY_DUPLICATES
}
private static final HashMap<String, Mode> MODES = new HashMap<>();
......
......@@ -654,8 +654,7 @@ public class Session extends SessionWithState {
// see the changes
// TODO should not rely on locking
if (!locks.isEmpty()) {
for (int i = 0, size = locks.size(); i < size; i++) {
Table t = locks.get(i);
for (Table t : locks) {
if (t instanceof MVTable) {
((MVTable) t).commit();
}
......@@ -681,8 +680,7 @@ public class Session extends SessionWithState {
rows.add(entry.getRow());
undoLog.removeLast(false);
}
for (int i = 0, size = rows.size(); i < size; i++) {
Row r = rows.get(i);
for (Row r : rows) {
r.commit();
}
}
......@@ -932,7 +930,7 @@ public class Session extends SessionWithState {
if (lockMode != Constants.LOCK_MODE_OFF &&
!database.isMultiVersion()) {
TableType tableType = log.getTable().getTableType();
if (locks.indexOf(log.getTable()) < 0
if (!locks.contains(log.getTable())
&& TableType.TABLE_LINK != tableType
&& TableType.EXTERNAL_TABLE_ENGINE != tableType) {
DbException.throwInternalError("" + tableType);
......@@ -944,8 +942,7 @@ public class Session extends SessionWithState {
if (database.isMultiVersion()) {
// see also UndoLogRecord.commit
ArrayList<Index> indexes = table.getIndexes();
for (int i = 0, size = indexes.size(); i < size; i++) {
Index index = indexes.get(i);
for (Index index : indexes) {
index.commit(operation, row);
}
row.commit();
......@@ -992,8 +989,7 @@ public class Session extends SessionWithState {
}
if (!locks.isEmpty()) {
// don't use the enhanced for loop to save memory
for (int i = 0, size = locks.size(); i < size; i++) {
Table t = locks.get(i);
for (Table t : locks) {
t.unlock(this);
}
locks.clear();
......@@ -1477,9 +1473,9 @@ public class Session extends SessionWithState {
public Table[] getLocks() {
// copy the data without synchronizing
ArrayList<Table> copy = New.arrayList();
for (int i = 0; i < locks.size(); i++) {
for (Table lock : locks) {
try {
copy.add(locks.get(i));
copy.add(lock);
} catch (Exception e) {
// ignore
break;
......
......@@ -73,7 +73,6 @@ public class SessionRemote extends SessionWithState implements DataHandler {
private ArrayList<Transfer> transferList = New.arrayList();
private int nextId;
private boolean autoCommit = true;
private CommandInterface autoCommitFalse, autoCommitTrue;
private ConnectionInfo connectionInfo;
private String databaseName;
private String cipher;
......@@ -101,8 +100,7 @@ public class SessionRemote extends SessionWithState implements DataHandler {
@Override
public ArrayList<String> getClusterServers() {
ArrayList<String> serverList = new ArrayList<>();
for (int i = 0; i < transferList.size(); i++) {
Transfer transfer = transferList.get(i);
for (Transfer transfer : transferList) {
serverList.add(transfer.getSocket().getInetAddress().
getHostAddress() + ":" +
transfer.getSocket().getPort());
......@@ -247,31 +245,15 @@ public class SessionRemote extends SessionWithState implements DataHandler {
}
private synchronized void setAutoCommitSend(boolean autoCommit) {
if (clientVersion >= Constants.TCP_PROTOCOL_VERSION_8) {
for (int i = 0, count = 0; i < transferList.size(); i++) {
Transfer transfer = transferList.get(i);
try {
traceOperation("SESSION_SET_AUTOCOMMIT", autoCommit ? 1 : 0);
transfer.writeInt(SessionRemote.SESSION_SET_AUTOCOMMIT).
writeBoolean(autoCommit);
done(transfer);
} catch (IOException e) {
removeServer(e, i--, ++count);
}
}
} else {
if (autoCommit) {
if (autoCommitTrue == null) {
autoCommitTrue = prepareCommand(
"SET AUTOCOMMIT TRUE", Integer.MAX_VALUE);
}
autoCommitTrue.executeUpdate(false);
} else {
if (autoCommitFalse == null) {
autoCommitFalse = prepareCommand(
"SET AUTOCOMMIT FALSE", Integer.MAX_VALUE);
}
autoCommitFalse.executeUpdate(false);
for (int i = 0, count = 0; i < transferList.size(); i++) {
Transfer transfer = transferList.get(i);
try {
traceOperation("SESSION_SET_AUTOCOMMIT", autoCommit ? 1 : 0);
transfer.writeInt(SessionRemote.SESSION_SET_AUTOCOMMIT).
writeBoolean(autoCommit);
done(transfer);
} catch (IOException e) {
removeServer(e, i--, ++count);
}
}
}
......@@ -443,8 +425,7 @@ public class SessionRemote extends SessionWithState implements DataHandler {
// TODO cluster: support more than 2 connections
boolean switchOffCluster = false;
try {
for (int i = 0; i < len; i++) {
String s = servers[i];
for (String s : servers) {
try {
Transfer trans = initTransfer(ci, databaseName, s);
transferList.add(trans);
......@@ -626,8 +607,7 @@ public class SessionRemote extends SessionWithState implements DataHandler {
errorCode, null, stackTrace);
if (errorCode == ErrorCode.CONNECTION_BROKEN_1) {
// allow re-connect
IOException e = new IOException(s.toString(), s);
throw e;
throw new IOException(s.toString(), s);
}
throw DbException.convert(s);
} else if (status == STATUS_CLOSED) {
......
......@@ -177,7 +177,6 @@ public class UndoLog {
memoryUndo = 0;
records.clear();
file.autoDelete();
return;
}
} else {
if (!entry.isStored()) {
......@@ -193,8 +192,7 @@ public class UndoLog {
file.seek(FileStore.HEADER_LENGTH);
rowBuff = Data.create(database, Constants.DEFAULT_PAGE_SIZE);
Data buff = rowBuff;
for (int i = 0; i < records.size(); i++) {
UndoLogRecord r = records.get(i);
for (UndoLogRecord r : records) {
saveIfPossible(r, buff);
}
} else {
......
......@@ -66,10 +66,7 @@ public class UndoLogRecord {
*/
boolean canStore() {
// if large transactions are enabled, this method is not called
if (table.getUniqueIndex() != null) {
return true;
}
return false;
return table.getUniqueIndex() != null;
}
/**
......
......@@ -145,10 +145,7 @@ public class User extends RightOwner {
return true;
}
}
if (isRightGrantedRecursive(table, rightMask)) {
return true;
}
return false;
return isRightGrantedRecursive(table, rightMask);
}
/**
......
......@@ -725,8 +725,7 @@ public class Aggregate extends Expression {
TableFilter filter = col.getTableFilter();
if (filter != null) {
Table table = filter.getTable();
Index index = table.getIndexForColumn(column, true, false);
return index;
return table.getIndexForColumn(column, true, false);
}
}
return null;
......@@ -767,16 +766,14 @@ public class Aggregate extends Expression {
return false;
}
if (groupConcatOrderList != null) {
for (int i = 0, size = groupConcatOrderList.size(); i < size; i++) {
SelectOrderBy o = groupConcatOrderList.get(i);
for (SelectOrderBy o : groupConcatOrderList) {
if (!o.expression.isEverything(visitor)) {
return false;
}
}
}
if (arrayAggOrderList != null) {
for (int i = 0, size = arrayAggOrderList.size(); i < size; i++) {
SelectOrderBy o = arrayAggOrderList.get(i);
for (SelectOrderBy o : arrayAggOrderList) {
if (!o.expression.isEverything(visitor)) {
return false;
}
......
......@@ -29,7 +29,6 @@ class AggregateDataCount extends AggregateData {
distinctValues = ValueHashMap.newInstance();
}
distinctValues.put(v, this);
return;
}
}
......
......@@ -119,8 +119,9 @@ class AggregateDataMedian extends AggregateData {
count--;
cursor.next();
hasNulls = true;
} else
} else {
break;
}
}
if (count == 0) {
return ValueNull.INSTANCE;
......
......@@ -244,7 +244,7 @@ public class Comparison extends Condition {
result = l == ValueNull.INSTANCE;
break;
case IS_NOT_NULL:
result = !(l == ValueNull.INSTANCE);
result = l != ValueNull.INSTANCE;
break;
default:
throw DbException.throwInternalError("type=" + compareType);
......@@ -275,7 +275,7 @@ public class Comparison extends Condition {
return ValueBoolean.get(result);
}
private String[] getEnumerators(Value left, Value right) {
private static String[] getEnumerators(Value left, Value right) {
if (left.getType() == Value.ENUM) {
return ((ValueEnum) left).getEnumerators();
} else if (right.getType() == Value.ENUM) {
......
......@@ -100,7 +100,7 @@ public class ConditionAndOr extends Condition {
if (r == ValueNull.INSTANCE) {
return r;
}
return ValueBoolean.get(true);
return ValueBoolean.TRUE;
}
case OR: {
if (l.getBoolean()) {
......@@ -116,7 +116,7 @@ public class ConditionAndOr extends Condition {
if (r == ValueNull.INSTANCE) {
return r;
}
return ValueBoolean.get(false);
return ValueBoolean.FALSE;
}
default:
throw DbException.throwInternalError("type=" + andOrType);
......@@ -151,8 +151,7 @@ public class ConditionAndOr extends Condition {
session, compRight, true);
if (added != null) {
added = added.optimize(session);
ConditionAndOr a = new ConditionAndOr(AND, this, added);
return a;
return new ConditionAndOr(AND, this, added);
}
}
}
......
......@@ -138,7 +138,6 @@ public class ConditionIn extends Condition {
}
}
filter.addIndexCondition(IndexCondition.getInList(l, valueList));
return;
}
}
......
......@@ -94,7 +94,6 @@ public class ConditionInConstantSet extends Condition {
}
if (session.getDatabase().getSettings().optimizeInList) {
filter.addIndexCondition(IndexCondition.getInList(l, valueList));
return;
}
}
......@@ -143,8 +142,7 @@ public class ConditionInConstantSet extends Condition {
@Override
public int getCost() {
int cost = left.getCost();
return cost;
return left.getCost();
}
/**
......
......@@ -62,16 +62,16 @@ public class ConditionInSelect extends Condition {
}
int dataType = rows.getColumnType(0);
if (dataType == Value.NULL) {
return ValueBoolean.get(false);
return ValueBoolean.FALSE;
}
l = l.convertTo(dataType);
if (rows.containsDistinct(new Value[] { l })) {
return ValueBoolean.get(true);
return ValueBoolean.TRUE;
}
if (rows.containsDistinct(new Value[] { ValueNull.INSTANCE })) {
return ValueNull.INSTANCE;
}
return ValueBoolean.get(false);
return ValueBoolean.FALSE;
}
private Value getValueSlow(ResultInterface rows, Value l) {
......
......@@ -330,7 +330,7 @@ public class ExpressionColumn extends Expression {
if (filter == tf && column.getType() == Value.BOOLEAN) {
IndexCondition cond = IndexCondition.get(
Comparison.EQUAL, this, ValueExpression.get(
ValueBoolean.get(true)));
ValueBoolean.TRUE));
filter.addIndexCondition(cond);
}
}
......@@ -338,7 +338,7 @@ public class ExpressionColumn extends Expression {
@Override
public Expression getNotIfPossible(Session session) {
return new Comparison(session, Comparison.EQUAL, this,
ValueExpression.get(ValueBoolean.get(false)));
ValueExpression.get(ValueBoolean.FALSE));
}
}
......@@ -294,10 +294,9 @@ public class ExpressionVisitor {
*/
public static HashSet<Column> allColumnsForTableFilters(TableFilter[] filters) {
HashSet<Column> allColumnsSet = new HashSet<>();
for (int i = 0; i < filters.length; i++) {
if (filters[i].getSelect() != null) {
filters[i].getSelect().isEverything(
ExpressionVisitor.getColumnsVisitor(allColumnsSet));
for (TableFilter filter : filters) {
if (filter.getSelect() != null) {
filter.getSelect().isEverything(ExpressionVisitor.getColumnsVisitor(allColumnsSet));
}
}
return allColumnsSet;
......
......@@ -107,7 +107,7 @@ public class Function extends Expression implements FunctionCall {
* Pseudo functions for DATEADD, DATEDIFF, and EXTRACT.
*/
public static final int MILLISECOND = 126, EPOCH = 127, MICROSECOND = 128, NANOSECOND = 129,
TIMEZONE_HOUR = 130, TIMEZONE_MINUTE = 131, DECADE = 132, CENTURY = 133,
TIMEZONE_HOUR = 130, TIMEZONE_MINUTE = 131, DECADE = 132, CENTURY = 133,
MILLENNIUM = 134;
public static final int DATABASE = 150, USER = 151, CURRENT_USER = 152,
......@@ -714,9 +714,9 @@ public class Function extends Expression implements FunctionCall {
String tmp = v.getString();
if (!StringUtils.isNullOrEmpty(separator)
&& !StringUtils.isNullOrEmpty(tmp)) {
tmp = separator.concat(tmp);
tmp = separator + tmp;
}
result = ValueString.get(result.getString().concat(tmp),
result = ValueString.get(result.getString() + tmp,
database.getMode().treatEmptyStringsAsNull);
}
}
......@@ -956,7 +956,7 @@ public class Function extends Expression implements FunctionCall {
result = v0;
for (int i = 0; i < args.length; i++) {
Value v = getNullOrValue(session, args, values, i);
if (!(v == ValueNull.INSTANCE)) {
if (v != ValueNull.INSTANCE) {
result = v.convertTo(dataType);
break;
}
......@@ -968,7 +968,7 @@ public class Function extends Expression implements FunctionCall {
result = ValueNull.INSTANCE;
for (int i = 0; i < args.length; i++) {
Value v = getNullOrValue(session, args, values, i);
if (!(v == ValueNull.INSTANCE)) {
if (v != ValueNull.INSTANCE) {
v = v.convertTo(dataType);
if (result == ValueNull.INSTANCE) {
result = v;
......@@ -1005,7 +1005,7 @@ public class Function extends Expression implements FunctionCall {
// (expr, when, then, else)
// (expr, when, then, when, then)
// (expr, when, then, when, then, else)
if (!(v0 == ValueNull.INSTANCE)) {
if (v0 != ValueNull.INSTANCE) {
for (int i = 1, len = args.length - 1; i < len; i += 2) {
Value when = args[i].getValue(session);
if (database.areEqual(v0, when)) {
......@@ -1048,13 +1048,13 @@ public class Function extends Expression implements FunctionCall {
break;
}
case ARRAY_CONTAINS: {
result = ValueBoolean.get(false);
result = ValueBoolean.FALSE;
if (v0.getType() == Value.ARRAY) {
Value v1 = getNullOrValue(session, args, values, 1);
Value[] list = ((ValueArray) v0).getList();
for (Value v : list) {
if (v.equals(v1)) {
result = ValueBoolean.get(true);
result = ValueBoolean.TRUE;
break;
}
}
......@@ -1512,9 +1512,8 @@ public class Function extends Expression implements FunctionCall {
String[] columns = StringUtils.arraySplit(columnList,
fieldSeparator, true);
try {
ValueResultSet vr = ValueResultSet.get(csv.read(fileName,
result = ValueResultSet.get(csv.read(fileName,
columns, charset));
result = vr;
} catch (SQLException e) {
throw DbException.convert(e);
}
......@@ -1645,8 +1644,9 @@ public class Function extends Expression implements FunctionCall {
break;
case SIGNAL: {
String sqlState = v0.getString();
if (sqlState.startsWith("00") || !SIGNAL_PATTERN.matcher(sqlState).matches())
if (sqlState.startsWith("00") || !SIGNAL_PATTERN.matcher(sqlState).matches()) {
throw DbException.getInvalidValueException("SQLSTATE", sqlState);
}
String msgText = v1.getString();
throw DbException.fromUser(sqlState, msgText);
}
......
......@@ -110,10 +110,7 @@ public class JavaAggregate extends Expression {
return false;
}
}
if (filterCondition != null && !filterCondition.isEverything(visitor)) {
return false;
}
return true;
return filterCondition == null || filterCondition.isEverything(visitor);
}
@Override
......
......@@ -85,7 +85,7 @@ public class Parameter extends Expression implements ParameterInterface {
@Override
public Expression optimize(Session session) {
if (session.getDatabase().getMode().treatEmptyStringsAsNull) {
if (value != null && value instanceof ValueString) {
if (value instanceof ValueString) {
value = ValueString.get(value.getString(), true);
}
}
......@@ -176,7 +176,7 @@ public class Parameter extends Expression implements ParameterInterface {
@Override
public Expression getNotIfPossible(Session session) {
return new Comparison(session, Comparison.EQUAL, this,
ValueExpression.get(ValueBoolean.get(false)));
ValueExpression.get(ValueBoolean.FALSE));
}
public void setColumn(Column column) {
......
......@@ -124,9 +124,8 @@ public class TableFunction extends Function {
}
}
result.done();
ValueResultSet vr = ValueResultSet.get(getSimpleResultSet(result,
return ValueResultSet.get(getSimpleResultSet(result,
Integer.MAX_VALUE));
return vr;
}
private static SimpleResultSet getSimpleResultSet(LocalResult rs,
......
......@@ -91,7 +91,7 @@ public class ValueExpression extends Expression {
@Override
public Expression getNotIfPossible(Session session) {
return new Comparison(session, Comparison.EQUAL, this,
ValueExpression.get(ValueBoolean.get(false)));
ValueExpression.get(ValueBoolean.FALSE));
}
@Override
......
......@@ -90,7 +90,7 @@ public class HashIndex extends BaseIndex {
@Override
public long getRowCount(Session session) {
return getRowCountApproximation();
return rows.size();
}
@Override
......
......@@ -83,8 +83,7 @@ public class IndexCursor implements Cursor {
inResultTested = null;
intersects = null;
// don't use enhanced for loop to avoid creating objects
for (int i = 0, size = indexConditions.size(); i < size; i++) {
IndexCondition condition = indexConditions.get(i);
for (IndexCondition condition : indexConditions) {
if (condition.isAlwaysFalse()) {
alwaysFalse = true;
break;
......
......@@ -286,10 +286,7 @@ public abstract class PageBtree extends Page {
@Override
public boolean canRemove() {
if (changeCount >= index.getPageStore().getChangeCount()) {
return false;
}
return true;
return changeCount < index.getPageStore().getChangeCount();
}
}
......@@ -154,9 +154,8 @@ public class PageBtreeLeaf extends PageBtree {
if (entryCount > 0) {
byte[] d = data.getBytes();
int dataStart = offsets[entryCount - 1];
int dataEnd = offset;
System.arraycopy(d, dataStart, d, dataStart - rowLength,
dataEnd - dataStart + rowLength);
offset - dataStart + rowLength);
}
index.writeRow(data, offset, row, onlyPosition);
}
......@@ -206,7 +205,7 @@ public class PageBtreeLeaf extends PageBtree {
PageBtree split(int splitPoint) {
int newPageId = index.getPageStore().allocatePage();
PageBtreeLeaf p2 = PageBtreeLeaf.create(index, newPageId, parentPageId);
for (int i = splitPoint; i < entryCount;) {
while (splitPoint < entryCount) {
p2.addRow(getRow(splitPoint), false);
removeRow(splitPoint);
}
......
......@@ -250,7 +250,7 @@ public class PageBtreeNode extends PageBtree {
}
int firstChild = childPageIds[splitPoint];
readAllRows();
for (int i = splitPoint; i < entryCount;) {
while (splitPoint < entryCount) {
p2.addChild(p2.entryCount, childPageIds[splitPoint + 1], getRow(splitPoint));
removeChild(splitPoint);
}
......
......@@ -244,10 +244,7 @@ abstract class PageData extends Page {
@Override
public boolean canRemove() {
if (changeCount >= index.getPageStore().getChangeCount()) {
return false;
}
return true;
return changeCount < index.getPageStore().getChangeCount();
}
}
......@@ -311,9 +311,8 @@ public class PageDataIndex extends PageIndex {
public double getCost(Session session, int[] masks,
TableFilter[] filters, int filter, SortOrder sortOrder,
HashSet<Column> allColumnsSet) {
long cost = 10 * (tableData.getRowCountApproximation() +
return 10 * (tableData.getRowCountApproximation() +
Constants.COST_ROW_OFFSET);
return cost;
}
@Override
......
......@@ -370,7 +370,7 @@ public class PageDataLeaf extends PageData {
PageData split(int splitPoint) {
int newPageId = index.getPageStore().allocatePage();
PageDataLeaf p2 = PageDataLeaf.create(index, newPageId, parentPageId);
for (int i = splitPoint; i < entryCount;) {
while (splitPoint < entryCount) {
int split = p2.addRowTry(getRowAt(splitPoint));
if (split != -1) {
DbException.throwInternalError("split " + split);
......
......@@ -172,7 +172,7 @@ public class PageDataNode extends PageData {
int newPageId = index.getPageStore().allocatePage();
PageDataNode p2 = PageDataNode.create(index, newPageId, parentPageId);
int firstChild = childPageIds[splitPoint];
for (int i = splitPoint; i < entryCount;) {
while (splitPoint < entryCount) {
p2.addChild(p2.entryCount, childPageIds[splitPoint + 1], keys[splitPoint]);
removeChild(splitPoint);
}
......
......@@ -47,20 +47,34 @@ public class RangeIndex extends BaseIndex {
@Override
public Cursor find(Session session, SearchRow first, SearchRow last) {
long min = rangeTable.getMin(session), start = min;
long max = rangeTable.getMax(session), end = max;
long min = rangeTable.getMin(session);
long max = rangeTable.getMax(session);
long step = rangeTable.getStep(session);
try {
start = Math.max(min, first == null ? min : first.getValue(0).getLong());
long v = first.getValue(0).getLong();
if (step > 0) {
if (v > min) {
min += (v - min + step - 1) / step * step;
}
} else if (v > max) {
max = v;
}
} catch (Exception e) {
// error when converting the value - ignore
}
try {
end = Math.min(max, last == null ? max : last.getValue(0).getLong());
long v = last.getValue(0).getLong();
if (step > 0) {
if (v < max) {
max = v;
}
} else if (v < min) {
min -= (min - v - step - 1) / step * step;
}
} catch (Exception e) {
// error when converting the value - ignore
}
return new RangeCursor(session, start, end, step);
return new RangeCursor(session, min, max, step);
}
@Override
......@@ -108,7 +122,7 @@ public class RangeIndex extends BaseIndex {
@Override
public long getRowCount(Session session) {
return rangeTable.getRowCountApproximation();
return rangeTable.getRowCount(session);
}
@Override
......
......@@ -245,8 +245,7 @@ public class ViewIndex extends BaseIndex implements SpatialIndex {
SearchRow intersection) {
ArrayList<Parameter> paramList = query.getParameters();
if (originalParameters != null) {
for (int i = 0, size = originalParameters.size(); i < size; i++) {
Parameter orig = originalParameters.get(i);
for (Parameter orig : originalParameters) {
int idx = orig.getIndex();
Value value = orig.getValue(session);
setParameter(paramList, idx, value);
......
......@@ -258,7 +258,7 @@ public class JdbcArray extends TraceObject implements Array {
// TODO array result set: there are multiple data types possible
rs.addColumn("VALUE", Types.NULL, 0, 0);
for (int i = 0; i < array.length; i++) {
rs.addRow(Long.valueOf(offset + i + 1), array[i]);
rs.addRow(offset + i + 1, array[i]);
}
return rs;
}
......
......@@ -190,7 +190,7 @@ public class JdbcBlob extends TraceObject implements Blob {
if (value.getPrecision() != 0) {
throw DbException.getInvalidValueException("length", value.getPrecision());
}
final JdbcConnection c = conn;
final JdbcConnection c = conn; // local variable avoids generating synthetic accessor method
final PipedInputStream in = new PipedInputStream();
final Task task = new Task() {
@Override
......
......@@ -138,7 +138,7 @@ public class JdbcClob extends TraceObject implements NClob
if (value.getPrecision() != 0) {
throw DbException.getInvalidValueException("length", value.getPrecision());
}
final JdbcConnection c = conn;
final JdbcConnection c = conn; // required to avoid synthetic method creation
// PipedReader / PipedWriter are a lot slower
// than PipedInputStream / PipedOutputStream
// (Sun/Oracle Java 1.6.0_20)
......
......@@ -1049,9 +1049,8 @@ public class JdbcConnection extends TraceObject
"SAVEPOINT " + JdbcSavepoint.getName(name, 0),
Integer.MAX_VALUE);
set.executeUpdate(false);
JdbcSavepoint savepoint = new JdbcSavepoint(this, 0, name, trace,
return new JdbcSavepoint(this, 0, name, trace,
id);
return savepoint;
} catch (Exception e) {
throw logAndConvert(e);
}
......@@ -1599,9 +1598,8 @@ public class JdbcConnection extends TraceObject
+ "WHERE SCOPE_IDENTITY() IS NOT NULL",
getGeneratedKeys);
ResultInterface result = getGeneratedKeys.executeQuery(0, false);
ResultSet rs = new JdbcResultSet(this, stat, getGeneratedKeys, result,
return new JdbcResultSet(this, stat, getGeneratedKeys, result,
id, false, true, false);
return rs;
}
/**
......
......@@ -143,19 +143,44 @@ public class JdbcDatabaseMetaData extends TraceObject implements
", " + quoteArray(types) + ");");
}
checkClosed();
String tableType;
if (types != null && types.length > 0) {
StatementBuilder buff = new StatementBuilder("TABLE_TYPE IN(");
for (int i = 0; i < types.length; i++) {
buff.appendExceptFirst(", ");
buff.append('?');
}
tableType = buff.append(')').toString();
} else {
tableType = "TRUE";
}
int typesLength = types != null ? types.length : 0;
boolean includeSynonyms = types == null || Arrays.asList(types).contains("SYNONYM");
String tableSelect = "SELECT "
// (1024 - 16) is enough for the most cases
StringBuilder select = new StringBuilder(1008);
if (includeSynonyms) {
select.append("SELECT "
+ "TABLE_CAT, "
+ "TABLE_SCHEM, "
+ "TABLE_NAME, "
+ "TABLE_TYPE, "
+ "REMARKS, "
+ "TYPE_CAT, "
+ "TYPE_SCHEM, "
+ "TYPE_NAME, "
+ "SELF_REFERENCING_COL_NAME, "
+ "REF_GENERATION, "
+ "SQL "
+ "FROM ("
+ "SELECT "
+ "SYNONYM_CATALOG TABLE_CAT, "
+ "SYNONYM_SCHEMA TABLE_SCHEM, "
+ "SYNONYM_NAME as TABLE_NAME, "
+ "TYPE_NAME AS TABLE_TYPE, "
+ "REMARKS, "
+ "TYPE_NAME TYPE_CAT, "
+ "TYPE_NAME TYPE_SCHEM, "
+ "TYPE_NAME AS TYPE_NAME, "
+ "TYPE_NAME SELF_REFERENCING_COL_NAME, "
+ "TYPE_NAME REF_GENERATION, "
+ "NULL AS SQL "
+ "FROM INFORMATION_SCHEMA.SYNONYMS "
+ "WHERE SYNONYM_CATALOG LIKE ?1 ESCAPE ?4 "
+ "AND SYNONYM_SCHEMA LIKE ?2 ESCAPE ?4 "
+ "AND SYNONYM_NAME LIKE ?3 ESCAPE ?4 "
+ "UNION ");
}
select.append("SELECT "
+ "TABLE_CATALOG TABLE_CAT, "
+ "TABLE_SCHEMA TABLE_SCHEM, "
+ "TABLE_NAME, "
......@@ -168,58 +193,30 @@ public class JdbcDatabaseMetaData extends TraceObject implements
+ "TYPE_NAME REF_GENERATION, "
+ "SQL "
+ "FROM INFORMATION_SCHEMA.TABLES "
+ "WHERE TABLE_CATALOG LIKE ? ESCAPE ? "
+ "AND TABLE_SCHEMA LIKE ? ESCAPE ? "
+ "AND TABLE_NAME LIKE ? ESCAPE ? "
+ "AND (" + tableType + ") ";
boolean includeSynonyms = types == null || Arrays.asList(types).contains("SYNONYM");
String synonymSelect = "SELECT "
+ "SYNONYM_CATALOG TABLE_CAT, "
+ "SYNONYM_SCHEMA TABLE_SCHEM, "
+ "SYNONYM_NAME as TABLE_NAME, "
+ "TYPE_NAME AS TABLE_TYPE, "
+ "REMARKS, "
+ "TYPE_NAME TYPE_CAT, "
+ "TYPE_NAME TYPE_SCHEM, "
+ "TYPE_NAME AS TYPE_NAME, "
+ "TYPE_NAME SELF_REFERENCING_COL_NAME, "
+ "TYPE_NAME REF_GENERATION, "
+ "NULL AS SQL "
+ "FROM INFORMATION_SCHEMA.SYNONYMS "
+ "WHERE SYNONYM_CATALOG LIKE ? ESCAPE ? "
+ "AND SYNONYM_SCHEMA LIKE ? ESCAPE ? "
+ "AND SYNONYM_NAME LIKE ? ESCAPE ? "
+ "AND (" + includeSynonyms + ") ";
PreparedStatement prep = conn.prepareAutoCloseStatement("SELECT "
+ "TABLE_CAT, "
+ "TABLE_SCHEM, "
+ "TABLE_NAME, "
+ "TABLE_TYPE, "
+ "REMARKS, "
+ "TYPE_CAT, "
+ "TYPE_SCHEM, "
+ "TYPE_NAME, "
+ "SELF_REFERENCING_COL_NAME, "
+ "REF_GENERATION, "
+ "SQL "
+ "FROM (" + synonymSelect + " UNION " + tableSelect + ") "
+ "ORDER BY TABLE_TYPE, TABLE_SCHEM, TABLE_NAME");
+ "WHERE TABLE_CATALOG LIKE ?1 ESCAPE ?4 "
+ "AND TABLE_SCHEMA LIKE ?2 ESCAPE ?4 "
+ "AND TABLE_NAME LIKE ?3 ESCAPE ?4");
if (typesLength > 0) {
select.append(" AND TABLE_TYPE IN(");
for (int i = 0; i < typesLength; i++) {
if (i > 0) {
select.append(", ");
}
select.append('?').append(i + 5);
}
select.append(')');
}
if (includeSynonyms) {
select.append(')');
}
PreparedStatement prep = conn.prepareAutoCloseStatement(
select.append(" ORDER BY TABLE_TYPE, TABLE_SCHEM, TABLE_NAME").toString());
prep.setString(1, getCatalogPattern(catalogPattern));
prep.setString(2, "\\");
prep.setString(3, getSchemaPattern(schemaPattern));
prep.setString(2, getSchemaPattern(schemaPattern));
prep.setString(3, getPattern(tableNamePattern));
prep.setString(4, "\\");
prep.setString(5, getPattern(tableNamePattern));
prep.setString(6, "\\");
prep.setString(7, getCatalogPattern(catalogPattern));
prep.setString(8, "\\");
prep.setString(9, getSchemaPattern(schemaPattern));
prep.setString(10, "\\");
prep.setString(11, getPattern(tableNamePattern));
prep.setString(12, "\\");
for (int i = 0; types != null && i < types.length; i++) {
prep.setString(13 + i, types[i]);
for (int i = 0; i < typesLength; i++) {
prep.setString(5 + i, types[i]);
}
return prep.executeQuery();
} catch (Exception e) {
......@@ -1494,8 +1491,7 @@ public class JdbcDatabaseMetaData extends TraceObject implements
+ "RADIX NUM_PREC_RADIX "
+ "FROM INFORMATION_SCHEMA.TYPE_INFO "
+ "ORDER BY DATA_TYPE, POS");
ResultSet rs = prep.executeQuery();
return rs;
return prep.executeQuery();
} catch (Exception e) {
throw logAndConvert(e);
}
......@@ -2319,9 +2315,7 @@ public class JdbcDatabaseMetaData extends TraceObject implements
"SELECT VALUE FROM INFORMATION_SCHEMA.SETTINGS WHERE NAME=?");
prep.setString(1, "MULTI_THREADED");
ResultSet rs = prep.executeQuery();
if (rs.next() && rs.getString(1).equals("1")) {
return false;
}
return !rs.next() || !rs.getString(1).equals("1");
}
return true;
}
......@@ -2563,10 +2557,7 @@ public class JdbcDatabaseMetaData extends TraceObject implements
public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException {
debugCodeCall("supportsMixedCaseQuotedIdentifiers");
String m = conn.getMode();
if (m.equals("MySQL")) {
return false;
}
return true;
return !m.equals("MySQL");
}
/**
......@@ -2579,10 +2570,7 @@ public class JdbcDatabaseMetaData extends TraceObject implements
public boolean storesUpperCaseIdentifiers() throws SQLException {
debugCodeCall("storesUpperCaseIdentifiers");
String m = conn.getMode();
if (m.equals("MySQL")) {
return false;
}
return true;
return !m.equals("MySQL");
}
/**
......@@ -2595,10 +2583,7 @@ public class JdbcDatabaseMetaData extends TraceObject implements
public boolean storesLowerCaseIdentifiers() throws SQLException {
debugCodeCall("storesLowerCaseIdentifiers");
String m = conn.getMode();
if (m.equals("MySQL")) {
return true;
}
return false;
return m.equals("MySQL");
}
/**
......@@ -2623,10 +2608,7 @@ public class JdbcDatabaseMetaData extends TraceObject implements
public boolean storesUpperCaseQuotedIdentifiers() throws SQLException {
debugCodeCall("storesUpperCaseQuotedIdentifiers");
String m = conn.getMode();
if (m.equals("MySQL")) {
return true;
}
return false;
return m.equals("MySQL");
}
/**
......@@ -2639,10 +2621,7 @@ public class JdbcDatabaseMetaData extends TraceObject implements
public boolean storesLowerCaseQuotedIdentifiers() throws SQLException {
debugCodeCall("storesLowerCaseQuotedIdentifiers");
String m = conn.getMode();
if (m.equals("MySQL")) {
return true;
}
return false;
return m.equals("MySQL");
}
/**
......@@ -2655,10 +2634,7 @@ public class JdbcDatabaseMetaData extends TraceObject implements
public boolean storesMixedCaseQuotedIdentifiers() throws SQLException {
debugCodeCall("storesMixedCaseQuotedIdentifiers");
String m = conn.getMode();
if (m.equals("MySQL")) {
return false;
}
return true;
return !m.equals("MySQL");
}
/**
......
......@@ -280,8 +280,7 @@ public class JdbcPreparedStatement extends JdbcStatement implements
debugCodeCall("clearParameters");
checkClosed();
ArrayList<? extends ParameterInterface> parameters = command.getParameters();
for (int i = 0, size = parameters.size(); i < size; i++) {
ParameterInterface param = parameters.get(i);
for (ParameterInterface param : parameters) {
// can only delete old temp files if they are not in the batch
param.setValue(null, batchParameters == null);
}
......@@ -1202,9 +1201,8 @@ public class JdbcPreparedStatement extends JdbcStatement implements
TraceObject.RESULT_SET_META_DATA, id, "getMetaData()");
}
String catalog = conn.getCatalog();
JdbcResultSetMetaData meta = new JdbcResultSetMetaData(
return new JdbcResultSetMetaData(
null, this, result, catalog, session.getTrace(), id);
return meta;
} catch (Exception e) {
throw logAndConvert(e);
}
......@@ -1252,7 +1250,6 @@ public class JdbcPreparedStatement extends JdbcStatement implements
@Override
public int[] executeBatch() throws SQLException {
try {
int id = getNextId(TraceObject.PREPARED_STATEMENT);
debugCodeCall("executeBatch");
if (batchParameters == null) {
// TODO batch: check what other database do if no parameters are
......@@ -1294,8 +1291,7 @@ public class JdbcPreparedStatement extends JdbcStatement implements
}
batchParameters = null;
if (error) {
JdbcBatchUpdateException e = new JdbcBatchUpdateException(next, result);
throw e;
throw new JdbcBatchUpdateException(next, result);
}
return result;
} finally {
......@@ -1546,9 +1542,8 @@ public class JdbcPreparedStatement extends JdbcStatement implements
TraceObject.PARAMETER_META_DATA, id, "getParameterMetaData()");
}
checkClosed();
JdbcParameterMetaData meta = new JdbcParameterMetaData(
return new JdbcParameterMetaData(
session.getTrace(), this, command, id);
return meta;
} catch (Exception e) {
throw logAndConvert(e);
}
......
......@@ -147,9 +147,7 @@ public class JdbcResultSet extends TraceObject implements ResultSet, JdbcResultS
}
checkClosed();
String catalog = conn.getCatalog();
JdbcResultSetMetaData meta = new JdbcResultSetMetaData(
this, null, result, catalog, conn.getSession().getTrace(), id);
return meta;
return new JdbcResultSetMetaData(this, null, result, catalog, conn.getSession().getTrace(), id);
} catch (Exception e) {
throw logAndConvert(e);
}
......
......@@ -170,9 +170,8 @@ public class JdbcConnectionPool implements DataSource, ConnectionEventListener,
return;
}
isDisposed = true;
ArrayList<PooledConnection> list = recycledConnections;
for (int i = 0, size = list.size(); i < size; i++) {
closeConnection(list.get(i));
for (PooledConnection aList : recycledConnections) {
closeConnection(aList);
}
}
......
......@@ -44,14 +44,8 @@ public class JdbcXid extends TraceObject implements Xid {
* INTERNAL
*/
public static String toString(Xid xid) {
StringBuilder buff = new StringBuilder(PREFIX);
buff.append('_').
append(xid.getFormatId()).
append('_').
append(StringUtils.convertBytesToHex(xid.getBranchQualifier())).
append('_').
append(StringUtils.convertBytesToHex(xid.getGlobalTransactionId()));
return buff.toString();
return PREFIX + '_' + xid.getFormatId() + '_' + StringUtils.convertBytesToHex(xid.getBranchQualifier()) + '_'
+ StringUtils.convertBytesToHex(xid.getGlobalTransactionId());
}
/**
......
......@@ -621,8 +621,9 @@ public final class MVStore {
// the following can fail for various reasons
try {
HashMap<String, String> m = DataUtils.parseChecksummedMap(buff);
if (m == null)
if (m == null) {
continue;
}
int blockSize = DataUtils.readHexInt(
m, "blockSize", BLOCK_SIZE);
if (blockSize != BLOCK_SIZE) {
......
......@@ -222,8 +222,7 @@ public class MVStoreTool {
if (mapId == 0 && details) {
ByteBuffer data;
if (compressed) {
boolean fast = !((type & DataUtils.PAGE_COMPRESSED_HIGH) ==
DataUtils.PAGE_COMPRESSED_HIGH);
boolean fast = (type & DataUtils.PAGE_COMPRESSED_HIGH) != DataUtils.PAGE_COMPRESSED_HIGH;
Compressor compressor = getCompressor(fast);
int lenAdd = DataUtils.readVarInt(chunk);
int compLen = pageSize + start - chunk.position();
......
......@@ -101,10 +101,7 @@ public class StreamStore {
ByteArrayOutputStream id = new ByteArrayOutputStream();
int level = 0;
try {
while (true) {
if (put(id, in, level)) {
break;
}
while (!put(id, in, level)) {
if (id.size() > maxBlockSize / 2) {
id = putIndirectId(id);
level++;
......
......@@ -468,8 +468,7 @@ public class MVTable extends TableBase {
database.getReferentialIntegrity()) {
ArrayList<Constraint> constraints = getConstraints();
if (constraints != null) {
for (int i = 0, size = constraints.size(); i < size; i++) {
Constraint c = constraints.get(i);
for (Constraint c : constraints) {
if (c.getConstraintType() != Constraint.Type.REFERENTIAL) {
continue;
}
......@@ -729,16 +728,14 @@ public class MVTable extends TableBase {
Transaction t = session.getTransaction();
long savepoint = t.setSavepoint();
try {
for (int i = 0, size = indexes.size(); i < size; i++) {
Index index = indexes.get(i);
for (Index index : indexes) {
index.add(session, row);
}
} catch (Throwable e) {
t.rollbackToSavepoint(savepoint);
DbException de = DbException.convert(e);
if (de.getErrorCode() == ErrorCode.DUPLICATE_KEY_1) {
for (int j = 0; j < indexes.size(); j++) {
Index index = indexes.get(j);
for (Index index : indexes) {
if (index.getIndexType().isUnique() &&
index instanceof MultiVersionIndex) {
MultiVersionIndex mv = (MultiVersionIndex) index;
......
......@@ -280,7 +280,7 @@ public class TransactionStore {
void log(Transaction t, long logId, int mapId,
Object key, Object oldValue) {
Long undoKey = getOperationId(t.getId(), logId);
Object[] log = new Object[] { mapId, key, oldValue };
Object[] log = { mapId, key, oldValue };
rwLock.writeLock().lock();
try {
if (logId == 0) {
......
......@@ -459,9 +459,9 @@ public class ValueDataType implements DataType {
case Value.NULL:
return ValueNull.INSTANCE;
case BOOLEAN_TRUE:
return ValueBoolean.get(true);
return ValueBoolean.TRUE;
case BOOLEAN_FALSE:
return ValueBoolean.get(false);
return ValueBoolean.FALSE;
case INT_NEG:
return ValueInt.get(-readVarInt(buff));
case Value.ENUM:
......@@ -558,9 +558,8 @@ public class ValueDataType implements DataType {
int tableId = readVarInt(buff);
long lobId = readVarLong(buff);
long precision = readVarLong(buff);
ValueLobDb lob = ValueLobDb.create(type,
return ValueLobDb.create(type,
handler, tableId, lobId, null, precision);
return lob;
} else {
throw DbException.get(ErrorCode.FILE_CORRUPTED_1,
"lob type: " + smallLen);
......@@ -584,10 +583,7 @@ public class ValueDataType implements DataType {
readVarInt(buff),
readVarInt(buff));
}
while (true) {
if (buff.get() == 0) {
break;
}
while (buff.get() != 0) {
Object[] o = new Object[columns];
for (int i = 0; i < columns; i++) {
o[i] = ((Value) readValue(buff)).getObject();
......
......@@ -315,8 +315,7 @@ public class SpatialDataType implements DataType {
boundsInner.setMin(i, boundsInner.max(i));
boundsInner.setMax(i, t);
}
for (int i = 0; i < list.size(); i++) {
Object o = list.get(i);
for (Object o : list) {
increaseBounds(bounds, o);
increaseMaxInnerBounds(boundsInner, o);
}
......
......@@ -601,7 +601,7 @@ public class ObjectDataType implements DataType {
@Override
public Object read(ByteBuffer buff, int tag) {
return Byte.valueOf(buff.get());
return buff.get();
}
}
......@@ -642,7 +642,7 @@ public class ObjectDataType implements DataType {
@Override
public Object read(ByteBuffer buff, int tag) {
return Character.valueOf(buff.getChar());
return buff.getChar();
}
}
......@@ -683,7 +683,7 @@ public class ObjectDataType implements DataType {
@Override
public Object read(ByteBuffer buff, int tag) {
return Short.valueOf(buff.getShort());
return buff.getShort();
}
}
......@@ -811,7 +811,7 @@ public class ObjectDataType implements DataType {
case TAG_LONG_FIXED:
return buff.getLong();
}
return Long.valueOf(tag - TAG_LONG_0_7);
return (long) (tag - TAG_LONG_0_7);
}
}
......
......@@ -119,8 +119,7 @@ public class RowImpl implements Row {
if (data != null) {
int len = data.length;
m += Constants.MEMORY_OBJECT + len * Constants.MEMORY_POINTER;
for (int i = 0; i < len; i++) {
Value v = data[i];
for (Value v : data) {
if (v != null) {
m += v.getMemory();
}
......
......@@ -79,8 +79,7 @@ public class SimpleRow implements SearchRow {
if (memory == 0) {
int len = data.length;
memory = Constants.MEMORY_OBJECT + len * Constants.MEMORY_POINTER;
for (int i = 0; i < len; i++) {
Value v = data[i];
for (Value v : data) {
if (v != null) {
memory += v.getMemory();
}
......
......@@ -389,10 +389,8 @@ public class CipherFactory {
private static String[] enableAnonymous(String[] enabled, String[] supported) {
LinkedHashSet<String> set = new LinkedHashSet<>();
for (String x : supported) {
if (!x.startsWith("SSL") &&
x.indexOf("_anon_") >= 0 &&
(x.indexOf("_AES_") >= 0 || x.indexOf("_3DES_") >= 0) &&
x.indexOf("_SHA") >= 0) {
if (!x.startsWith("SSL") && x.contains("_anon_") &&
(x.contains("_AES_") || x.contains("_3DES_")) && x.contains("_SHA")) {
set.add(x);
}
}
......
......@@ -653,8 +653,9 @@ public class PgServerThread implements Runnable {
case PgServer.PG_TYPE_TIME: {
// Strip timezone offset
int idx = str.indexOf('+');
if (idx <= 0)
if (idx <= 0) {
idx = str.indexOf('-');
}
if (idx > 0) {
str = str.substring(0, idx);
}
......
......@@ -830,14 +830,14 @@ public class WebApp {
try {
StringBuilder result = new StringBuilder(s.length());
int idx = s.indexOf("<br />");
result.append(s.substring(0, idx));
result.append(s, 0, idx);
while (true) {
int start = s.indexOf("org.h2.", idx);
if (start < 0) {
result.append(s.substring(idx));
break;
}
result.append(s.substring(idx, start));
result.append(s, idx, start);
int end = s.indexOf(')', start);
if (end < 0) {
result.append(s.substring(idx));
......@@ -1253,8 +1253,7 @@ public class WebApp {
private int getMaxrows() {
String r = (String) session.get("maxrows");
int maxrows = r == null ? 0 : Integer.parseInt(r);
return maxrows;
return r == null ? 0 : Integer.parseInt(r);
}
private String getResult(Connection conn, int id, String sql,
......@@ -1268,9 +1267,8 @@ public class WebApp {
sqlUpper.contains("ALTER") ||
sqlUpper.contains("RUNSCRIPT")) {
String sessionId = attributes.getProperty("jsessionid");
buff.append("<script type=\"text/javascript\">" +
"parent['h2menu'].location='tables.do?jsessionid="
+ sessionId + "';</script>");
buff.append("<script type=\"text/javascript\">parent['h2menu'].location='tables.do?jsessionid=")
.append(sessionId).append("';</script>");
}
Statement stat;
DbContents contents = session.getContents();
......
......@@ -198,7 +198,7 @@ class WebSession {
* @return a map containing the session meta data
*/
HashMap<String, Object> getInfo() {
HashMap<String, Object> m = new HashMap<>();
HashMap<String, Object> m = new HashMap<>(map.size() + 5);
m.putAll(map);
m.put("lastAccess", new Timestamp(lastAccess).toString());
try {
......
......@@ -716,9 +716,9 @@ public class Data {
case Value.NULL:
return ValueNull.INSTANCE;
case BOOLEAN_TRUE:
return ValueBoolean.get(true);
return ValueBoolean.TRUE;
case BOOLEAN_FALSE:
return ValueBoolean.get(false);
return ValueBoolean.FALSE;
case INT_NEG:
return ValueInt.get(-readVarInt());
case Value.ENUM:
......@@ -832,9 +832,8 @@ public class Data {
int tableId = readVarInt();
long lobId = readVarLong();
long precision = readVarLong();
ValueLobDb lob = ValueLobDb.create(type, handler, tableId,
return ValueLobDb.create(type, handler, tableId,
lobId, null, precision);
return lob;
} else {
int tableId = readVarInt();
int objectId = readVarInt();
......@@ -870,10 +869,7 @@ public class Data {
for (int i = 0; i < columns; i++) {
rs.addColumn(readString(), readVarInt(), readVarInt(), readVarInt());
}
while (true) {
if (readByte() == 0) {
break;
}
while (readByte() != 0) {
Object[] o = new Object[columns];
for (int i = 0; i < columns; i++) {
o[i] = readValue().getObject();
......
......@@ -113,8 +113,7 @@ public class FileLister {
}
if (ok) {
if (db == null || f.startsWith(start)) {
String fileName = f;
files.add(fileName);
files.add(f);
}
}
}
......
......@@ -31,5 +31,5 @@ public enum FileLockMethod {
/**
* Use the file system to lock the file; don't use a separate lock file.
*/
FS;
FS
}
......@@ -398,8 +398,7 @@ public class LobStorageBackend implements LobStorageInterface {
// For a CLOB, precision is length in chars
long precision = countingReaderForClob == null ?
small.length : countingReaderForClob.getLength();
ValueLobDb v = ValueLobDb.createSmallLob(type, small, precision);
return v;
return ValueLobDb.createSmallLob(type, small, precision);
}
// For a BLOB, precision is length in bytes.
// For a CLOB, precision is length in chars
......@@ -432,9 +431,8 @@ public class LobStorageBackend implements LobStorageInterface {
prep.setInt(3, tableId);
prep.execute();
reuse(sql, prep);
ValueLobDb v = ValueLobDb.create(type,
return ValueLobDb.create(type,
database, tableId, lobId, null, precision);
return v;
}
}
}
......@@ -589,8 +587,7 @@ public class LobStorageBackend implements LobStorageInterface {
init();
long max = maxLength == -1 ? Long.MAX_VALUE : maxLength;
CountingReaderInputStream in = new CountingReaderInputStream(reader, max);
ValueLobDb lob = addLob(in, Long.MAX_VALUE, Value.CLOB, in);
return lob;
return addLob(in, Long.MAX_VALUE, Value.CLOB, in);
}
private static void assertNotHolds(Object lock) {
......
......@@ -217,9 +217,9 @@ public class LobStorageMap implements LobStorageInterface {
long lobId = generateLobId();
long length = streamStore.length(streamStoreId);
int tableId = LobStorageFrontend.TABLE_TEMP;
Object[] value = new Object[] { streamStoreId, tableId, length, 0 };
Object[] value = { streamStoreId, tableId, length, 0 };
lobMap.put(lobId, value);
Object[] key = new Object[] { streamStoreId, lobId };
Object[] key = { streamStoreId, lobId };
refMap.put(key, Boolean.TRUE);
ValueLobDb lob = ValueLobDb.create(
type, database, tableId, lobId, null, length);
......@@ -259,7 +259,7 @@ public class LobStorageMap implements LobStorageInterface {
long lobId = generateLobId();
value[1] = tableId;
lobMap.put(lobId, value);
Object[] key = new Object[] { streamStoreId, lobId };
Object[] key = { streamStoreId, lobId };
refMap.put(key, Boolean.TRUE);
ValueLobDb lob = ValueLobDb.create(
type, database, tableId, lobId, null, length);
......@@ -332,7 +332,7 @@ public class LobStorageMap implements LobStorageInterface {
return;
}
byte[] streamStoreId = (byte[]) value[0];
Object[] key = new Object[] {streamStoreId, lobId };
Object[] key = {streamStoreId, lobId };
refMap.remove(key);
// check if there are more entries for this streamStoreId
key = new Object[] {streamStoreId, 0L };
......
......@@ -415,8 +415,8 @@ public class PageStore implements CacheWriter {
private void writeBack() {
ArrayList<CacheObject> list = cache.getAllChanged();
Collections.sort(list);
for (int i = 0, size = list.size(); i < size; i++) {
writeBack(list.get(i));
for (CacheObject cacheObject : list) {
writeBack(cacheObject);
}
}
......@@ -1722,8 +1722,7 @@ public class PageStore implements CacheWriter {
ic.sortType = Integer.parseInt(s);
c = c.substring(0, idx);
}
Column column = tableCols[Integer.parseInt(c)];
ic.column = column;
ic.column = tableCols[Integer.parseInt(c)];
cols[i] = ic;
}
IndexType indexType;
......@@ -1980,18 +1979,14 @@ public class PageStore implements CacheWriter {
* @return true if it is correct
*/
public static boolean checksumTest(byte[] d, int pageId, int pageSize) {
int ps = pageSize;
int s1 = 255 + (d[0] & 255), s2 = 255 + s1;
s2 += s1 += d[6] & 255;
s2 += s1 += d[(ps >> 1) - 1] & 255;
s2 += s1 += d[ps >> 1] & 255;
s2 += s1 += d[ps - 2] & 255;
s2 += s1 += d[ps - 1] & 255;
if (d[1] != (byte) (((s1 & 255) + (s1 >> 8)) ^ pageId)
|| d[2] != (byte) (((s2 & 255) + (s2 >> 8)) ^ (pageId >> 8))) {
return false;
}
return true;
s2 += s1 += d[(pageSize >> 1) - 1] & 255;
s2 += s1 += d[pageSize >> 1] & 255;
s2 += s1 += d[pageSize - 2] & 255;
s2 += s1 += d[pageSize - 1] & 255;
return d[1] == (byte) (((s1 & 255) + (s1 >> 8)) ^ pageId) && d[2] == (byte) (((s2 & 255) + (s2 >> 8)) ^ (pageId
>> 8));
}
/**
......
......@@ -49,8 +49,9 @@ public final class RangeInputStream extends FilterInputStream {
@Override
public int read(byte b[], int off, int len) throws IOException {
if (limit <= 0)
if (limit <= 0) {
return -1;
}
if (len > limit) {
len = (int) limit;
}
......
......@@ -50,8 +50,9 @@ public final class RangeReader extends Reader {
@Override
public int read(char cbuf[], int off, int len) throws IOException {
if (limit <= 0)
if (limit <= 0) {
return -1;
}
if (len > limit) {
len = (int) limit;
}
......
......@@ -98,12 +98,10 @@ public class FilePathDisk extends FilePath {
if (ok) {
return;
}
throw DbException.get(ErrorCode.FILE_RENAME_FAILED_2,
new String[]{name, newName.name});
throw DbException.get(ErrorCode.FILE_RENAME_FAILED_2, name, newName.name);
}
if (newFile.exists()) {
throw DbException.get(ErrorCode.FILE_RENAME_FAILED_2,
new String[] { name, newName + " (exists)" });
throw DbException.get(ErrorCode.FILE_RENAME_FAILED_2, name, newName + " (exists)");
}
for (int i = 0; i < SysProperties.MAX_FILE_RETRY; i++) {
IOUtils.trace("rename", name + " >" + newName, null);
......@@ -113,8 +111,7 @@ public class FilePathDisk extends FilePath {
}
wait(i);
}
throw DbException.get(ErrorCode.FILE_RENAME_FAILED_2,
new String[]{name, newName.name});
throw DbException.get(ErrorCode.FILE_RENAME_FAILED_2, name, newName.name);
}
private static void wait(int i) {
......@@ -174,8 +171,8 @@ public class FilePathDisk extends FilePath {
if (!base.endsWith(SysProperties.FILE_SEPARATOR)) {
base += SysProperties.FILE_SEPARATOR;
}
for (int i = 0, len = files.length; i < len; i++) {
list.add(getPath(base + files[i]));
for (String file : files) {
list.add(getPath(base + file));
}
}
return list;
......@@ -316,8 +313,7 @@ public class FilePathDisk extends FilePath {
}
// otherwise an URL is assumed
URL url = new URL(name);
InputStream in = url.openStream();
return in;
return url.openStream();
}
FileInputStream in = new FileInputStream(name);
IOUtils.trace("openFileInputStream", name, in);
......
......@@ -53,8 +53,7 @@ public class FilePathMem extends FilePath {
synchronized (MEMORY_FILES) {
if (!atomicReplace && !newName.name.equals(name) &&
MEMORY_FILES.containsKey(newName.name)) {
throw DbException.get(ErrorCode.FILE_RENAME_FAILED_2,
new String[] { name, newName + " (exists)" });
throw DbException.get(ErrorCode.FILE_RENAME_FAILED_2, name, newName + " (exists)");
}
FileMemData f = getMemoryFile();
f.setName(newName.name);
......@@ -392,7 +391,7 @@ class FileMem extends FileBase {
}
}
FileLock lock = new FileLock(new FakeFileChannel(), position, size, shared) {
return new FileLock(new FakeFileChannel(), position, size, shared) {
@Override
public boolean isValid() {
......@@ -404,7 +403,6 @@ class FileMem extends FileBase {
data.unlock();
}
};
return lock;
}
@Override
......
......@@ -223,7 +223,7 @@ class FileNioMapped extends FileBase {
file.setLength(newLength);
break;
} catch (IOException e) {
if (i > 16 || e.toString().indexOf("user-mapped section open") < 0) {
if (i > 16 || !e.toString().contains("user-mapped section open")) {
throw e;
}
}
......
......@@ -56,8 +56,7 @@ public class FilePathNioMem extends FilePath {
synchronized (MEMORY_FILES) {
if (!atomicReplace && !name.equals(newName.name) &&
MEMORY_FILES.containsKey(newName.name)) {
throw DbException.get(ErrorCode.FILE_RENAME_FAILED_2,
new String[] { name, newName + " (exists)" });
throw DbException.get(ErrorCode.FILE_RENAME_FAILED_2, name, newName + " (exists)");
}
FileNioMemData f = getMemoryFile();
f.setName(newName.name);
......@@ -386,7 +385,7 @@ class FileNioMem extends FileBase {
}
}
FileLock lock = new FileLock(new FakeFileChannel(), position, size, shared) {
return new FileLock(new FakeFileChannel(), position, size, shared) {
@Override
public boolean isValid() {
......@@ -398,7 +397,6 @@ class FileNioMem extends FileBase {
data.unlock();
}
};
return lock;
}
@Override
......
......@@ -95,8 +95,7 @@ public class FilePathSplit extends FilePathWrapper {
public ArrayList<FilePath> newDirectoryStream() {
List<FilePath> list = getBase().newDirectoryStream();
ArrayList<FilePath> newList = New.arrayList();
for (int i = 0, size = list.size(); i < size; i++) {
FilePath f = list.get(i);
for (FilePath f : list) {
if (!f.getName().endsWith(PART_SUFFIX)) {
newList.add(wrap(f));
}
......
......@@ -150,8 +150,8 @@ public class FileUtils {
List<FilePath> list = FilePath.get(path).newDirectoryStream();
int len = list.size();
List<String> result = new ArrayList<>(len);
for (int i = 0; i < len; i++) {
result.add(list.get(i).toString());
for (FilePath filePath : list) {
result.add(filePath.toString());
}
return result;
}
......
......@@ -339,7 +339,9 @@ public class Column {
value = ValueNull.INSTANCE;
} else {
value = localDefaultExpression.getValue(session).convertTo(type);
session.getGeneratedKeys().add(this);
if (!localDefaultExpression.isConstant()) {
session.getGeneratedKeys().add(this);
}
if (primaryKey) {
session.setLastIdentity(value);
}
......@@ -349,7 +351,9 @@ public class Column {
if (value == ValueNull.INSTANCE) {
if (convertNullToDefault) {
value = localDefaultExpression.getValue(session).convertTo(type);
session.getGeneratedKeys().add(this);
if (!localDefaultExpression.isConstant()) {
session.getGeneratedKeys().add(this);
}
}
if (value == ValueNull.INSTANCE && !nullable) {
if (mode.convertInsertNullToZero) {
......@@ -455,15 +459,12 @@ public class Column {
originalSQL = "INT";
}
String sequenceName;
while (true) {
do {
ValueUuid uuid = ValueUuid.getNewRandom();
String s = uuid.getString();
s = StringUtils.toUpperEnglish(s.replace('-', '_'));
sequenceName = "SYSTEM_SEQUENCE_" + s;
if (schema.findSequence(sequenceName) == null) {
break;
}
}
} while (schema.findSequence(sequenceName) != null);
Sequence seq = new Sequence(schema, id, sequenceName, start, increment);
seq.setTemporary(temporary);
session.getDatabase().addSchemaObject(session, seq);
......@@ -720,8 +721,7 @@ public class Column {
sql = checkConstraint.getSQL();
name = oldName;
}
Expression expr = parser.parseExpression(sql);
return expr;
return parser.parseExpression(sql);
}
String getDefaultSQL() {
......
......@@ -224,7 +224,7 @@ public final class JoinBatch {
}
return false;
}
for (;;) {
while (true) {
if (!found) {
if (!batchedNext()) {
return false;
......@@ -272,7 +272,7 @@ public final class JoinBatch {
jfId--;
}
for (;;) {
while (true) {
fetchCurrent(jfId);
if (!current.isDropped()) {
......@@ -359,7 +359,7 @@ public final class JoinBatch {
assert c != null;
JoinFilter join = jf.join;
for (;;) {
while (true) {
if (c == null || !c.next()) {
if (newCursor && jf.isOuterJoin()) {
// replace cursor with null-row
......@@ -1026,8 +1026,8 @@ public final class JoinBatch {
@Override
public boolean isBatchFull() {
// if at least one is full
for (int i = 0; i < filters.size(); i++) {
if (filters.get(i).isBatchFull()) {
for (JoinFilter filter : filters) {
if (filter.isBatchFull()) {
return true;
}
}
......@@ -1118,8 +1118,8 @@ public final class JoinBatch {
if (joinBatches == null) {
return;
}
for (int i = 0, size = joinBatches.size(); i < size; i++) {
joinBatches.get(i).viewTopFutureCursor = null;
for (JoinBatch joinBatch : joinBatches) {
joinBatch.viewTopFutureCursor = null;
}
}
}
......
......@@ -814,7 +814,7 @@ public class MetaTable extends Table {
// reduce the number of tables to scan - makes some metadata queries
// 10x faster
final ArrayList<Table> tablesToList;
if (indexFrom != null && indexTo != null && indexFrom.equals(indexTo)) {
if (indexFrom != null && indexFrom.equals(indexTo)) {
String tableName = identifier(indexFrom.getString());
tablesToList = getTablesByName(session, tableName);
} else {
......@@ -895,7 +895,7 @@ public class MetaTable extends Table {
// reduce the number of tables to scan - makes some metadata queries
// 10x faster
final ArrayList<Table> tablesToList;
if (indexFrom != null && indexTo != null && indexFrom.equals(indexTo)) {
if (indexFrom != null && indexFrom.equals(indexTo)) {
String tableName = identifier(indexFrom.getString());
tablesToList = getTablesByName(session, tableName);
} else {
......@@ -1045,9 +1045,7 @@ public class MetaTable extends Table {
// database settings
ArrayList<String> settingNames = New.arrayList();
HashMap<String, String> s = database.getSettings().getSettings();
for (String k : s.keySet()) {
settingNames.add(k);
}
settingNames.addAll(s.keySet());
Collections.sort(settingNames);
for (String k : settingNames) {
add(rows, k, s.get(k));
......
......@@ -139,7 +139,19 @@ public class RangeTable extends Table {
@Override
public long getRowCount(Session session) {
return Math.max(0, getMax(session) - getMin(session) + 1);
long step = getStep(session);
if (step == 0L) {
throw DbException.get(ErrorCode.STEP_SIZE_MUST_NOT_BE_ZERO);
}
long delta = getMax(session) - getMin(session);
if (step > 0) {
if (delta < 0) {
return 0;
}
} else if (delta > 0) {
return 0;
}
return delta / step + 1;
}
@Override
......
......@@ -139,8 +139,7 @@ public class RegularTable extends TableBase {
}
DbException de = DbException.convert(e);
if (de.getErrorCode() == ErrorCode.DUPLICATE_KEY_1) {
for (int j = 0; j < indexes.size(); j++) {
Index index = indexes.get(j);
for (Index index : indexes) {
if (index.getIndexType().isUnique() && index instanceof MultiVersionIndex) {
MultiVersionIndex mv = (MultiVersionIndex) index;
if (mv.isUncommittedFromOtherSession(session, row)) {
......@@ -158,8 +157,7 @@ public class RegularTable extends TableBase {
@Override
public void commit(short operation, Row row) {
lastModificationId = database.getNextModificationDataId();
for (int i = 0, size = indexes.size(); i < size; i++) {
Index index = indexes.get(i);
for (Index index : indexes) {
index.commit(operation, row);
}
}
......@@ -747,8 +745,7 @@ public class RegularTable extends TableBase {
if (getCheckForeignKeyConstraints() && database.getReferentialIntegrity()) {
ArrayList<Constraint> constraints = getConstraints();
if (constraints != null) {
for (int i = 0, size = constraints.size(); i < size; i++) {
Constraint c = constraints.get(i);
for (Constraint c : constraints) {
if (c.getConstraintType() != Constraint.Type.REFERENTIAL) {
continue;
}
......
......@@ -101,8 +101,7 @@ public abstract class Table extends SchemaObjectBase {
public void rename(String newName) {
super.rename(newName);
if (constraints != null) {
for (int i = 0, size = constraints.size(); i < size; i++) {
Constraint constraint = constraints.get(i);
for (Constraint constraint : constraints) {
constraint.rebuild();
}
}
......@@ -264,8 +263,7 @@ public abstract class Table extends SchemaObjectBase {
public Index getIndex(String indexName) {
ArrayList<Index> indexes = getIndexes();
if (indexes != null) {
for (int i = 0; i < indexes.size(); i++) {
Index index = indexes.get(i);
for (Index index : indexes) {
if (index.getName().equals(indexName)) {
return index;
}
......@@ -371,9 +369,7 @@ public abstract class Table extends SchemaObjectBase {
return;
}
if (sequences != null) {
for (Sequence s : sequences) {
dependencies.add(s);
}
dependencies.addAll(sequences);
}
ExpressionVisitor visitor = ExpressionVisitor.getDependenciesVisitor(
dependencies);
......@@ -579,8 +575,7 @@ public abstract class Table extends SchemaObjectBase {
HashSet<Constraint> constraintsToDrop = new HashSet<>();
if (constraints != null) {
for (Column col : columnsToDrop) {
for (int i = 0, size = constraints.size(); i < size; i++) {
Constraint constraint = constraints.get(i);
for (Constraint constraint : constraints) {
HashSet<Column> columns = constraint.getReferencedColumns(this);
if (!columns.contains(col)) {
continue;
......@@ -598,8 +593,7 @@ public abstract class Table extends SchemaObjectBase {
ArrayList<Index> indexes = getIndexes();
if (indexes != null) {
for (Column col : columnsToDrop) {
for (int i = 0, size = indexes.size(); i < size; i++) {
Index index = indexes.get(i);
for (Index index : indexes) {
if (index.getCreateSQL() == null) {
continue;
}
......@@ -765,8 +759,7 @@ public abstract class Table extends SchemaObjectBase {
public Index findPrimaryKey() {
ArrayList<Index> indexes = getIndexes();
if (indexes != null) {
for (int i = 0, size = indexes.size(); i < size; i++) {
Index idx = indexes.get(i);
for (Index idx : indexes) {
if (idx.getIndexType().isPrimaryKey()) {
return idx;
}
......@@ -901,7 +894,7 @@ public abstract class Table extends SchemaObjectBase {
* @param constraint the constraint to add
*/
public void addConstraint(Constraint constraint) {
if (constraints == null || constraints.indexOf(constraint) < 0) {
if (constraints == null || !constraints.contains(constraint)) {
constraints = add(constraints, constraint);
}
}
......@@ -997,8 +990,7 @@ public abstract class Table extends SchemaObjectBase {
boolean before) {
if (constraints != null) {
// don't use enhanced for loop to avoid creating objects
for (int i = 0, size = constraints.size(); i < size; i++) {
Constraint constraint = constraints.get(i);
for (Constraint constraint : constraints) {
if (constraint.isBefore() == before) {
constraint.checkRow(session, this, oldRow, newRow);
}
......
......@@ -376,7 +376,7 @@ public class TableFilter implements ColumnResolver {
}
// check if we are at the top table filters all the way up
SubQueryInfo info = session.getSubQueryInfo();
for (;;) {
while (true) {
if (info == null) {
return true;
}
......
......@@ -677,10 +677,7 @@ public class TableView extends Table {
if (view != other.view) {
return false;
}
if (!Arrays.equals(masks, other.masks)) {
return false;
}
return true;
return Arrays.equals(masks, other.masks);
}
}
......@@ -703,10 +700,7 @@ public class TableView extends Table {
if (exception.getErrorCode() != ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1) {
return false;
}
if (!exception.getMessage().contains("\"" + this.getName() + "\"")) {
return false;
}
return true;
return exception.getMessage().contains("\"" + this.getName() + "\"");
}
public List<Table> getTables() {
......@@ -742,7 +736,7 @@ public class TableView extends Table {
schema, Arrays.asList(columnTemplates), db);
List<Column> columnTemplateList;
String[] querySQLOutput = new String[]{null};
String[] querySQLOutput = {null};
ArrayList<String> columnNames = new ArrayList<>();
for (Column columnTemplate: columnTemplates) {
columnNames.add(columnTemplate.getName());
......
......@@ -123,7 +123,6 @@ ShutdownHandler {
for (int i = 0; args != null && i < args.length; i++) {
String arg = args[i];
if (arg == null) {
continue;
} else if ("-?".equals(arg) || "-help".equals(arg)) {
showUsage();
return;
......@@ -356,7 +355,7 @@ ShutdownHandler {
System.gc();
// Mac OS X: Console tool process did not stop on exit
String os = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
if (os.indexOf("mac") >= 0) {
if (os.contains("mac")) {
for (Thread t : Thread.getAllStackTraces().keySet()) {
if (t.getName().startsWith("AWT-")) {
t.interrupt();
......
......@@ -378,10 +378,7 @@ public class Csv implements SimpleRowSource {
}
}
}
if (columnName.length() == 0) {
return false;
}
return true;
return columnName.length() != 0;
}
private void pushBack() {
......@@ -489,16 +486,12 @@ public class Csv implements SimpleRowSource {
return null;
} else if (ch <= ' ') {
// ignore spaces
continue;
} else if (lineComment != 0 && ch == lineComment) {
// comment until end of line
inputBufferStart = -1;
while (true) {
do {
ch = readChar();
if (ch == '\n' || ch < 0 || ch == '\r') {
break;
}
}
} while (ch != '\n' && ch >= 0 && ch != '\r');
endOfLine = true;
return null;
} else {
......
......@@ -183,8 +183,8 @@ public class MultiDimension implements Comparator<long[]> {
Long[] from = new Long[len];
Long[] to = new Long[len];
for (int i = 0; i < len; i++) {
from[i] = Long.valueOf(ranges[i][0]);
to[i] = Long.valueOf(ranges[i][1]);
from[i] = ranges[i][0];
to[i] = ranges[i][1];
}
prep.setObject(1, from);
prep.setObject(2, to);
......
......@@ -369,8 +369,8 @@ public class Recover extends Tool implements DataHandler {
writer.println("-- ERROR: " + error + " storageId: "
+ storageId + " recordLength: " + recordLength + " valueId: " + valueId);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.length; i++) {
int x = data[i] & 0xff;
for (byte aData1 : data) {
int x = aData1 & 0xff;
if (x >= ' ' && x < 128) {
sb.append((char) x);
} else {
......@@ -379,8 +379,8 @@ public class Recover extends Tool implements DataHandler {
}
writer.println("-- dump: " + sb.toString());
sb = new StringBuilder();
for (int i = 0; i < data.length; i++) {
int x = data[i] & 0xff;
for (byte aData : data) {
int x = aData & 0xff;
sb.append(' ');
if (x < 16) {
sb.append('0');
......@@ -1489,10 +1489,8 @@ public class Recover extends Tool implements DataHandler {
sb.append(getSQL(columnName, v));
} catch (Exception e) {
writeDataError(writer, "exception " + e, s.getBytes());
continue;
} catch (OutOfMemoryError e) {
writeDataError(writer, "out of memory", s.getBytes());
continue;
}
}
sb.append(");");
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论