提交 a7b6996b authored 作者: Owner's avatar Owner

Checkstyle and codeStyle fixes

上级 ee84407d
...@@ -73,7 +73,7 @@ public class CreateView extends SchemaCommand { ...@@ -73,7 +73,7 @@ public class CreateView extends SchemaCommand {
} }
public void setTableExpression(boolean isTableExpression) { public void setTableExpression(boolean isTableExpression) {
this.isTableExpression=isTableExpression; this.isTableExpression = isTableExpression;
} }
@Override @Override
...@@ -116,11 +116,9 @@ public class CreateView extends SchemaCommand { ...@@ -116,11 +116,9 @@ public class CreateView extends SchemaCommand {
} }
} }
if (view == null) { if (view == null) {
if(isTableExpression){ if (isTableExpression) {
view = TableView.createTableViewMaybeRecursive(getSchema(), id, viewName, querySQL, null, columnTemplatesAsStrings, session, false /* literalsChecked */, isTableExpression, true /*isPersistent*/ , db); view = TableView.createTableViewMaybeRecursive(getSchema(), id, viewName, querySQL, null, columnTemplatesAsStrings, session, false /* literalsChecked */, isTableExpression, true /*isPersistent*/, db);
} } else {
else
{
view = new TableView(getSchema(), id, viewName, querySQL, null, columnTemplatesAsUnknowns, session, false/* allow recursive */, false/* literalsChecked */, isTableExpression, true); view = new TableView(getSchema(), id, viewName, querySQL, null, columnTemplatesAsUnknowns, session, false/* allow recursive */, false/* literalsChecked */, isTableExpression, true);
} }
} else { } else {
......
...@@ -79,10 +79,10 @@ public class DropView extends SchemaCommand { ...@@ -79,10 +79,10 @@ public class DropView extends SchemaCommand {
session.getDatabase().removeSchemaObject(session, view); session.getDatabase().removeSchemaObject(session, view);
// remove dependent table expressions // remove dependent table expressions
for( Table childTable: copyOfDependencies){ for (Table childTable: copyOfDependencies) {
if(TableType.VIEW == childTable.getTableType()){ if (TableType.VIEW == childTable.getTableType()) {
TableView childTableView = (TableView) childTable; TableView childTableView = (TableView) childTable;
if(childTableView.isTableExpression() && childTableView.getName()!=null){ if (childTableView.isTableExpression() && childTableView.getName() != null) {
session.getDatabase().removeSchemaObject(session, childTableView); session.getDatabase().removeSchemaObject(session, childTableView);
} }
} }
......
...@@ -53,7 +53,7 @@ public class Delete extends Prepared { ...@@ -53,7 +53,7 @@ public class Delete extends Prepared {
this.condition = condition; this.condition = condition;
} }
public Expression getCondition( ) { public Expression getCondition() {
return this.condition; return this.condition;
} }
...@@ -136,17 +136,16 @@ public class Delete extends Prepared { ...@@ -136,17 +136,16 @@ public class Delete extends Prepared {
public void prepare() { public void prepare() {
if (condition != null) { if (condition != null) {
condition.mapColumns(targetTableFilter, 0); condition.mapColumns(targetTableFilter, 0);
if(sourceTableFilter!=null){ if (sourceTableFilter != null) {
condition.mapColumns(sourceTableFilter, 0); condition.mapColumns(sourceTableFilter, 0);
} }
condition = condition.optimize(session); condition = condition.optimize(session);
condition.createIndexConditions(session, targetTableFilter); condition.createIndexConditions(session, targetTableFilter);
} }
TableFilter[] filters; TableFilter[] filters;
if(sourceTableFilter==null){ if (sourceTableFilter == null) {
filters = new TableFilter[] { targetTableFilter }; filters = new TableFilter[] { targetTableFilter };
} } else {
else{
filters = new TableFilter[] { targetTableFilter, sourceTableFilter }; filters = new TableFilter[] { targetTableFilter, sourceTableFilter };
} }
PlanItem item = targetTableFilter.getBestPlanItem(session, filters, 0, PlanItem item = targetTableFilter.getBestPlanItem(session, filters, 0,
......
...@@ -112,11 +112,11 @@ public class MergeUsing extends Prepared { ...@@ -112,11 +112,11 @@ public class MergeUsing extends Prepared {
private Delete deleteCommand; private Delete deleteCommand;
private Insert insertCommand; private Insert insertCommand;
private String queryAlias; private String queryAlias;
private int countUpdatedRows = 0; private int countUpdatedRows;
private Column[] sourceKeys; private Column[] sourceKeys;
private Select targetMatchQuery; private Select targetMatchQuery;
private HashMap<Value, Integer> targetRowidsRemembered = new HashMap<>(); private HashMap<Value, Integer> targetRowidsRemembered = new HashMap<>();
private int sourceQueryRowNumber = 0; private int sourceQueryRowNumber;
public MergeUsing(Merge merge) { public MergeUsing(Merge merge) {
super(merge.getSession()); super(merge.getSession());
......
...@@ -840,14 +840,14 @@ public class Select extends Query { ...@@ -840,14 +840,14 @@ public class Select extends Query {
sort = prepareOrder(orderList, expressions.size()); sort = prepareOrder(orderList, expressions.size());
orderList = null; orderList = null;
} }
ColumnNamer columnNamer= new ColumnNamer(session); ColumnNamer columnNamer = new ColumnNamer(session);
for (int i = 0; i < expressions.size(); i++) { for (int i = 0; i < expressions.size(); i++) {
Expression e = expressions.get(i); Expression e = expressions.get(i);
String proposedColumnName = e.getAlias(); String proposedColumnName = e.getAlias();
String columnName = columnNamer.getColumnName(e,i,proposedColumnName); String columnName = columnNamer.getColumnName(e, i, proposedColumnName);
// if the name changed, create an alias // if the name changed, create an alias
if(!columnName.equals(proposedColumnName)){ if (!columnName.equals(proposedColumnName)) {
e = new Alias(e,columnName,true); e = new Alias(e, columnName, true);
} }
expressions.set(i, e.optimize(session)); expressions.set(i, e.optimize(session));
} }
...@@ -1087,14 +1087,13 @@ public class Select extends Query { ...@@ -1087,14 +1087,13 @@ public class Select extends Query {
for (TableFilter f : topFilters) { for (TableFilter f : topFilters) {
Table t = f.getTable(); Table t = f.getTable();
TableView tableView = (t instanceof TableView) ? (TableView) t : null; TableView tableView = (t instanceof TableView) ? (TableView) t : null;
if (tableView!=null && tableView.isRecursive() && tableView.isTableExpression()) { if (tableView != null && tableView.isRecursive() && tableView.isTableExpression()) {
if(tableView.isPersistent()){ if (tableView.isPersistent()) {
// skip the generation of plan SQL for this already recursive persistent ctes, since using a with // 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. // statement will re-create the common table expression views.
continue; continue;
} } else {
else {
buff.append("WITH RECURSIVE ").append(t.getName()).append('('); buff.append("WITH RECURSIVE ").append(t.getName()).append('(');
buff.resetCount(); buff.resetCount();
for (Column c : t.getColumns()) { for (Column c : t.getColumns()) {
......
...@@ -91,6 +91,9 @@ public class Database implements DataHandler { ...@@ -91,6 +91,9 @@ public class Database implements DataHandler {
private static int initialPowerOffCount; private static int initialPowerOffCount;
private static final ThreadLocal<Session> META_LOCK_DEBUGGING = new ThreadLocal<Session>();
private static final ThreadLocal<Throwable> META_LOCK_DEBUGGING_STACK = new ThreadLocal<Throwable>();
/** /**
* The default name of the system user. This name is only used as long as * The default name of the system user. This name is only used as long as
* there is no administrator user registered. * there is no administrator user registered.
...@@ -296,7 +299,7 @@ public class Database implements DataHandler { ...@@ -296,7 +299,7 @@ public class Database implements DataHandler {
e.fillInStackTrace(); e.fillInStackTrace();
} }
boolean alreadyOpen = e instanceof DbException boolean alreadyOpen = e instanceof DbException
&& ((DbException)e).getErrorCode() == ErrorCode.DATABASE_ALREADY_OPEN_1; && ((DbException) e).getErrorCode() == ErrorCode.DATABASE_ALREADY_OPEN_1;
if (alreadyOpen) { if (alreadyOpen) {
stopServer(); stopServer();
} }
...@@ -899,9 +902,6 @@ public class Database implements DataHandler { ...@@ -899,9 +902,6 @@ public class Database implements DataHandler {
} }
} }
private static final ThreadLocal<Session> metaLockDebugging = new ThreadLocal<Session>();
private static final ThreadLocal<Throwable> metaLockDebuggingStack = new ThreadLocal<Throwable>();
/** /**
* Lock the metadata table for updates. * Lock the metadata table for updates.
* *
...@@ -917,13 +917,13 @@ public class Database implements DataHandler { ...@@ -917,13 +917,13 @@ public class Database implements DataHandler {
return true; return true;
} }
if (SysProperties.CHECK2) { if (SysProperties.CHECK2) {
final Session prev = metaLockDebugging.get(); final Session prev = META_LOCK_DEBUGGING.get();
if (prev == null) { if (prev == null) {
metaLockDebugging.set(session); META_LOCK_DEBUGGING.set(session);
metaLockDebuggingStack.set(new Throwable("Last meta lock granted in this stack trace, "+ META_LOCK_DEBUGGING_STACK.set(new Throwable("Last meta lock granted in this stack trace, "+
"this is debug information for following IllegalStateException")); "this is debug information for following IllegalStateException"));
} else if (prev != session) { } else if (prev != session) {
metaLockDebuggingStack.get().printStackTrace(); META_LOCK_DEBUGGING_STACK.get().printStackTrace();
throw new IllegalStateException("meta currently locked by " throw new IllegalStateException("meta currently locked by "
+ prev +", sessionid="+ prev.getId() + prev +", sessionid="+ prev.getId()
+ " and trying to be locked by different session, " + " and trying to be locked by different session, "
...@@ -953,9 +953,9 @@ public class Database implements DataHandler { ...@@ -953,9 +953,9 @@ public class Database implements DataHandler {
*/ */
public void unlockMetaDebug(Session session) { public void unlockMetaDebug(Session session) {
if (SysProperties.CHECK2) { if (SysProperties.CHECK2) {
if (metaLockDebugging.get() == session) { if (META_LOCK_DEBUGGING.get() == session) {
metaLockDebugging.set(null); META_LOCK_DEBUGGING.set(null);
metaLockDebuggingStack.set(null); META_LOCK_DEBUGGING_STACK.set(null);
} }
} }
} }
......
...@@ -232,16 +232,15 @@ public class Session extends SessionWithState { ...@@ -232,16 +232,15 @@ public class Session extends SessionWithState {
// It can be recursive, thus implemented as counter. // It can be recursive, thus implemented as counter.
this.parsingView += parsingView ? 1 : -1; this.parsingView += parsingView ? 1 : -1;
assert this.parsingView >= 0; assert this.parsingView >= 0;
if(parsingView){ if (parsingView) {
viewNameStack.push(viewName); viewNameStack.push(viewName);
}else } else {
{
assert viewName.equals(viewNameStack.peek()); assert viewName.equals(viewNameStack.peek());
viewNameStack.pop(); viewNameStack.pop();
} }
} }
public String getParsingCreateViewName() { public String getParsingCreateViewName() {
if(viewNameStack.size()==0){ if (viewNameStack.size() == 0) {
return null; return null;
} }
return viewNameStack.peek(); return viewNameStack.peek();
...@@ -694,7 +693,8 @@ public class Session extends SessionWithState { ...@@ -694,7 +693,8 @@ public class Session extends SessionWithState {
for (Table table : tablesToAnalyze) { for (Table table : tablesToAnalyze) {
Analyze.analyzeTable(this, table, rows, false); Analyze.analyzeTable(this, table, rows, false);
} }
database.unlockMeta(this); // analyze can lock the meta // analyze can lock the meta
database.unlockMeta(this);
} }
tablesToAnalyze = null; tablesToAnalyze = null;
} }
......
...@@ -6,7 +6,6 @@ ...@@ -6,7 +6,6 @@
package org.h2.index; package org.h2.index;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.h2.api.ErrorCode; import org.h2.api.ErrorCode;
......
...@@ -48,11 +48,24 @@ import org.h2.value.Value; ...@@ -48,11 +48,24 @@ import org.h2.value.Value;
* A table stored in a MVStore. * A table stored in a MVStore.
*/ */
public class MVTable extends TableBase { public class MVTable extends TableBase {
/**
* The table name this thread is waiting to lock.
*/
public static final DebuggingThreadLocal<String> WAITING_FOR_LOCK;
private static final String NO_EXTRA_INFO = ""; /**
* The table names this thread has exclusively locked.
*/
public static final DebuggingThreadLocal<ArrayList<String>> EXCLUSIVE_LOCKS;
// lock event types for tracing... /**
* The tables names this thread has a shared lock on.
*/
public static final DebuggingThreadLocal<ArrayList<String>> SHARED_LOCKS;
/**
* The type of trace lock events
*/
private enum TraceLockEvent{ private enum TraceLockEvent{
TRACE_LOCK_OK("ok"), TRACE_LOCK_OK("ok"),
...@@ -63,31 +76,17 @@ public class MVTable extends TableBase { ...@@ -63,31 +76,17 @@ public class MVTable extends TableBase {
TRACE_LOCK_ADDED_FOR("added for"), TRACE_LOCK_ADDED_FOR("added for"),
TRACE_LOCK_ADD_UPGRADED_FOR("add (upgraded) for "); TRACE_LOCK_ADD_UPGRADED_FOR("add (upgraded) for ");
private TraceLockEvent(String eventText){ private final String eventText;
TraceLockEvent(String eventText) {
this.eventText = eventText; this.eventText = eventText;
} }
private final String eventText; public String getEventText() {
public String getEventText(){
return eventText; return eventText;
} }
} }
private static final String NO_EXTRA_INFO = "";
/**
* The table name this thread is waiting to lock.
*/
public static final DebuggingThreadLocal<String> WAITING_FOR_LOCK;
/**
* The table names this thread has exclusively locked.
*/
public static final DebuggingThreadLocal<ArrayList<String>> EXCLUSIVE_LOCKS;
/**
* The tables names this thread has a shared lock on.
*/
public static final DebuggingThreadLocal<ArrayList<String>> SHARED_LOCKS;
static { static {
if (SysProperties.THREAD_DEADLOCK_DETECTOR) { if (SysProperties.THREAD_DEADLOCK_DETECTOR) {
......
...@@ -112,18 +112,18 @@ public class TableView extends Table { ...@@ -112,18 +112,18 @@ public class TableView extends Table {
private Query compileViewQuery(Session session, String sql, boolean literalsChecked, String viewName) { private Query compileViewQuery(Session session, String sql, boolean literalsChecked, String viewName) {
Prepared p; Prepared p;
session.setParsingCreateView(true,viewName); session.setParsingCreateView(true, viewName);
try { try {
p = session.prepare(sql, false, literalsChecked); p = session.prepare(sql, false, literalsChecked);
} finally { } finally {
session.setParsingCreateView(false,viewName); session.setParsingCreateView(false, viewName);
} }
if (!(p instanceof Query)) { if (!(p instanceof Query)) {
throw DbException.getSyntaxError(sql, 0); throw DbException.getSyntaxError(sql, 0);
} }
Query q = (Query) p; Query q = (Query) p;
// only potentially recursive cte queries need to be non-lazy // only potentially recursive cte queries need to be non-lazy
if(isTableExpression && allowRecursive){ if (isTableExpression && allowRecursive) {
q.setNeverLazy(true); q.setNeverLazy(true);
} }
return q; return q;
...@@ -183,7 +183,7 @@ public class TableView extends Table { ...@@ -183,7 +183,7 @@ public class TableView extends Table {
if (name == null) { if (name == null) {
name = expr.getAlias(); name = expr.getAlias();
} }
name = columnNamer.getColumnName(expr,i,name); name = columnNamer.getColumnName(expr, i, name);
if (type == Value.UNKNOWN) { if (type == Value.UNKNOWN) {
type = expr.getType(); type = expr.getType();
} }
...@@ -455,7 +455,7 @@ public class TableView extends Table { ...@@ -455,7 +455,7 @@ public class TableView extends Table {
@Override @Override
public String getSQL() { public String getSQL() {
if (isTemporary() && querySQL!=null) { if (isTemporary() && querySQL != null) {
return "(\n" + StringUtils.indent(querySQL) + ")"; return "(\n" + StringUtils.indent(querySQL) + ")";
} }
return super.getSQL(); return super.getSQL();
...@@ -707,7 +707,7 @@ public class TableView extends Table { ...@@ -707,7 +707,7 @@ public class TableView extends Table {
return true; return true;
} }
public List<Table> getTables(){ public List<Table> getTables() {
return tables; return tables;
} }
...@@ -717,7 +717,7 @@ public class TableView extends Table { ...@@ -717,7 +717,7 @@ public class TableView extends Table {
public static TableView createTableViewMaybeRecursive(Schema schema, int id, String name, String querySQL, public static TableView createTableViewMaybeRecursive(Schema schema, int id, String name, String querySQL,
ArrayList<Parameter> parameters, Column[] columnTemplates, Session session, ArrayList<Parameter> parameters, Column[] columnTemplates, Session session,
boolean literalsChecked, boolean isTableExpression, boolean isPersistent, Database db){ boolean literalsChecked, boolean isTableExpression, boolean isPersistent, Database db) {
Table recursiveTable = TableView.createShadowTableForRecursiveTableExpression(isPersistent, session, name, Table recursiveTable = TableView.createShadowTableForRecursiveTableExpression(isPersistent, session, name,
...@@ -726,13 +726,13 @@ public class TableView extends Table { ...@@ -726,13 +726,13 @@ public class TableView extends Table {
List<Column> columnTemplateList; List<Column> columnTemplateList;
String[] querySQLOutput = new String[]{null}; String[] querySQLOutput = new String[]{null};
ArrayList<String> columnNames = new ArrayList<String>(); ArrayList<String> columnNames = new ArrayList<String>();
for(Column columnTemplate: columnTemplates){ for (Column columnTemplate: columnTemplates) {
columnNames.add(columnTemplate.getName()); columnNames.add(columnTemplate.getName());
} }
try { try {
Prepared withQuery = session.prepare(querySQL, false, false); Prepared withQuery = session.prepare(querySQL, false, false);
if(isPersistent){ if (isPersistent) {
withQuery.setSession(session); withQuery.setSession(session);
} }
columnTemplateList = TableView.createQueryColumnTemplateList(columnNames.toArray(new String[1]), columnTemplateList = TableView.createQueryColumnTemplateList(columnNames.toArray(new String[1]),
...@@ -745,11 +745,11 @@ public class TableView extends Table { ...@@ -745,11 +745,11 @@ public class TableView extends Table {
// build with recursion turned on // build with recursion turned on
TableView view = new TableView(schema, id, name, querySQL, TableView view = new TableView(schema, id, name, querySQL,
parameters, columnTemplateList.toArray(columnTemplates), session, parameters, columnTemplateList.toArray(columnTemplates), session,
true/* try recursive */, literalsChecked, isTableExpression, isPersistent ); true/* try recursive */, literalsChecked, isTableExpression, isPersistent);
// is recursion really detected ? if not - recreate it without recursion flag and no recursive index // is recursion really detected ? if not - recreate it without recursion flag and no recursive index
if (!view.isRecursiveQueryDetected()) { if (!view.isRecursiveQueryDetected()) {
if(isPersistent){ if (isPersistent) {
db.addSchemaObject(session, view); db.addSchemaObject(session, view);
view.lock(session, true, true); view.lock(session, true, true);
session.getDatabase().removeSchemaObject(session, view); session.getDatabase().removeSchemaObject(session, view);
...@@ -757,7 +757,7 @@ public class TableView extends Table { ...@@ -757,7 +757,7 @@ public class TableView extends Table {
// during database startup - this method does not normally get called - and it needs to be // during database startup - this method does not normally get called - and it needs to be
// to correctly un-register the table which the table expression uses... // to correctly un-register the table which the table expression uses...
view.removeChildrenAndResources(session); view.removeChildrenAndResources(session);
}else{ } else {
session.removeLocalTempTable(view); session.removeLocalTempTable(view);
} }
view = new TableView(schema, id, name, querySQL, parameters, view = new TableView(schema, id, name, querySQL, parameters,
...@@ -795,7 +795,7 @@ public class TableView extends Table { ...@@ -795,7 +795,7 @@ public class TableView extends Table {
// use the passed in column name if supplied, otherwise use alias // use the passed in column name if supplied, otherwise use alias
// (if found) otherwise use column name derived from column // (if found) otherwise use column name derived from column
// expression // expression
String columnName = columnNamer.getColumnName(columnExp,i,cols); String columnName = columnNamer.getColumnName(columnExp, i, cols);
columnTemplateList.add(new Column(columnName, columnTemplateList.add(new Column(columnName,
columnExp.getType())); columnExp.getType()));
...@@ -820,13 +820,13 @@ public class TableView extends Table { ...@@ -820,13 +820,13 @@ public class TableView extends Table {
// this gets a meta table lock that is not released // this gets a meta table lock that is not released
Table recursiveTable = schema.createTable(recursiveTableData); Table recursiveTable = schema.createTable(recursiveTableData);
if(isPersistent){ if (isPersistent) {
// this unlock is to prevent lock leak from schema.createTable() // this unlock is to prevent lock leak from schema.createTable()
db.unlockMeta(targetSession); db.unlockMeta(targetSession);
synchronized (targetSession) { synchronized (targetSession) {
db.addSchemaObject(targetSession, recursiveTable); db.addSchemaObject(targetSession, recursiveTable);
} }
}else{ } else {
targetSession.addLocalTempTable(recursiveTable); targetSession.addLocalTempTable(recursiveTable);
} }
return recursiveTable; return recursiveTable;
...@@ -834,12 +834,12 @@ public class TableView extends Table { ...@@ -834,12 +834,12 @@ public class TableView extends Table {
public static void destroyShadowTableForRecursiveExpression(boolean isPersistent, Session targetSession, public static void destroyShadowTableForRecursiveExpression(boolean isPersistent, Session targetSession,
Table recursiveTable) { Table recursiveTable) {
if(recursiveTable!=null){ if (recursiveTable != null) {
if(isPersistent){ if (isPersistent) {
recursiveTable.lock(targetSession, true, true); recursiveTable.lock(targetSession, true, true);
targetSession.getDatabase().removeSchemaObject(targetSession, recursiveTable); targetSession.getDatabase().removeSchemaObject(targetSession, recursiveTable);
}else{ } else {
targetSession.removeLocalTempTable(recursiveTable); targetSession.removeLocalTempTable(recursiveTable);
} }
......
...@@ -763,7 +763,7 @@ kill -9 `jps -l | grep "org.h2.test." | cut -d " " -f 1` ...@@ -763,7 +763,7 @@ kill -9 `jps -l | grep "org.h2.test." | cut -d " " -f 1`
addTest(new TestReadOnly()); addTest(new TestReadOnly());
addTest(new TestRecursiveQueries()); addTest(new TestRecursiveQueries());
addTest(new TestGeneralCommonTableQueries()); addTest(new TestGeneralCommonTableQueries());
if(!memory){ if (!memory) {
// requires persistent store for reconnection tests // requires persistent store for reconnection tests
addTest(new TestPersistentCommonTableExpressions()); addTest(new TestPersistentCommonTableExpressions());
} }
......
...@@ -6,11 +6,13 @@ import java.sql.ResultSet; ...@@ -6,11 +6,13 @@ import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import org.h2.test.TestBase; import org.h2.test.TestBase;
/**
* Base class for common table expression tests
*/
public abstract class AbstractBaseForCommonTableExpressions extends TestBase { public abstract class AbstractBaseForCommonTableExpressions extends TestBase {
protected void testRepeatedQueryWithSetup(int maxRetries, String[] expectedRowData, String[] expectedColumnNames, int expectedNumbeOfRows, String SETUP_SQL, protected void testRepeatedQueryWithSetup(int maxRetries, String[] expectedRowData, String[] expectedColumnNames, int expectedNumbeOfRows, String setupSQL,
String WITH_QUERY, int closeAndReopenDatabaseConnectionOnIteration, String[] expectedColumnTypes) throws SQLException { String withQuery, int closeAndReopenDatabaseConnectionOnIteration, String[] expectedColumnTypes) throws SQLException {
deleteDb("commonTableExpressionQueries"); deleteDb("commonTableExpressionQueries");
Connection conn = getConnection("commonTableExpressionQueries"); Connection conn = getConnection("commonTableExpressionQueries");
...@@ -18,40 +20,40 @@ public abstract class AbstractBaseForCommonTableExpressions extends TestBase { ...@@ -18,40 +20,40 @@ public abstract class AbstractBaseForCommonTableExpressions extends TestBase {
ResultSet rs; ResultSet rs;
for(int queryRunTries=1;queryRunTries<=maxRetries;queryRunTries++){ for (int queryRunTries = 1; queryRunTries <= maxRetries; queryRunTries++) {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute(SETUP_SQL); stat.execute(setupSQL);
stat.close(); stat.close();
// close and re-open connection for one iteration to make sure the query work between connections // close and re-open connection for one iteration to make sure the query work between connections
if(queryRunTries==closeAndReopenDatabaseConnectionOnIteration){ if (queryRunTries == closeAndReopenDatabaseConnectionOnIteration) {
conn.close(); conn.close();
conn = getConnection("commonTableExpressionQueries"); conn = getConnection("commonTableExpressionQueries");
} }
prep = conn.prepareStatement(WITH_QUERY); prep = conn.prepareStatement(withQuery);
rs = prep.executeQuery(); rs = prep.executeQuery();
for(int columnIndex = 1; columnIndex <= rs.getMetaData().getColumnCount(); columnIndex++){ for (int columnIndex = 1; columnIndex <= rs.getMetaData().getColumnCount(); columnIndex++) {
assertTrue(rs.getMetaData().getColumnLabel(columnIndex)!=null); assertTrue(rs.getMetaData().getColumnLabel(columnIndex) != null);
assertEquals(expectedColumnNames[columnIndex-1],rs.getMetaData().getColumnLabel(columnIndex)); assertEquals(expectedColumnNames[columnIndex - 1], rs.getMetaData().getColumnLabel(columnIndex));
assertEquals("wrongly type column "+rs.getMetaData().getColumnLabel(columnIndex)+" on iteration#"+queryRunTries, assertEquals("wrongly type column "+rs.getMetaData().getColumnLabel(columnIndex)+" on iteration#"+queryRunTries,
expectedColumnTypes[columnIndex-1],rs.getMetaData().getColumnTypeName(columnIndex)); expectedColumnTypes[columnIndex - 1], rs.getMetaData().getColumnTypeName(columnIndex));
} }
int rowNdx=0; int rowNdx = 0;
while (rs.next()) { while (rs.next()) {
StringBuffer buf = new StringBuffer(); StringBuffer buf = new StringBuffer();
for(int columnIndex = 1; columnIndex <= rs.getMetaData().getColumnCount(); columnIndex++){ for (int columnIndex = 1; columnIndex <= rs.getMetaData().getColumnCount(); columnIndex++) {
buf.append("|"+rs.getString(columnIndex)); buf.append("|"+rs.getString(columnIndex));
} }
assertEquals(expectedRowData[rowNdx], buf.toString()); assertEquals(expectedRowData[rowNdx], buf.toString());
rowNdx++; rowNdx++;
} }
assertEquals(expectedNumbeOfRows,rowNdx); assertEquals(expectedNumbeOfRows, rowNdx);
rs.close(); rs.close();
prep.close(); prep.close();
......
...@@ -30,9 +30,9 @@ public class TestPersistentCommonTableExpressions extends AbstractBaseForCommonT ...@@ -30,9 +30,9 @@ public class TestPersistentCommonTableExpressions extends AbstractBaseForCommonT
} }
private void testRecursiveTable() throws Exception { private void testRecursiveTable() throws Exception {
String[] expectedRowData =new String[]{"|meat|null","|fruit|3","|veg|2"}; String[] expectedRowData = new String[]{"|meat|null", "|fruit|3", "|veg|2"};
String[] expectedColumnTypes =new String[]{"VARCHAR","DECIMAL"}; String[] expectedColumnTypes = new String[]{"VARCHAR", "DECIMAL"};
String[] expectedColumnNames =new String[]{"VAL", String[] expectedColumnNames = new String[]{"VAL",
"SUM(SELECT\n" + "SUM(SELECT\n" +
" X\n" + " X\n" +
"FROM PUBLIC.\"\" BB\n" + "FROM PUBLIC.\"\" BB\n" +
...@@ -54,7 +54,7 @@ public class TestPersistentCommonTableExpressions extends AbstractBaseForCommonT ...@@ -54,7 +54,7 @@ public class TestPersistentCommonTableExpressions extends AbstractBaseForCommonT
" /* scanCount: 1 */\n" + " /* scanCount: 1 */\n" +
"WHERE BB.A IS A.VAL)"}; "WHERE BB.A IS A.VAL)"};
String SETUP_SQL = String setupSQL =
"DROP TABLE IF EXISTS A; " "DROP TABLE IF EXISTS A; "
+"DROP TABLE IF EXISTS B; " +"DROP TABLE IF EXISTS B; "
+"DROP TABLE IF EXISTS C; " +"DROP TABLE IF EXISTS C; "
...@@ -73,9 +73,9 @@ public class TestPersistentCommonTableExpressions extends AbstractBaseForCommonT ...@@ -73,9 +73,9 @@ public class TestPersistentCommonTableExpressions extends AbstractBaseForCommonT
+"INSERT INTO C VALUES('carrot', 'nantes'); " +"INSERT INTO C VALUES('carrot', 'nantes'); "
+"INSERT INTO C VALUES('carrot', 'imperator'); " +"INSERT INTO C VALUES('carrot', 'imperator'); "
+"INSERT INTO C VALUES(null, 'banapple'); " +"INSERT INTO C VALUES(null, 'banapple'); "
+"INSERT INTO A VALUES('meat'); " +"INSERT INTO A VALUES('meat'); ";
;
String WITH_QUERY = "WITH BB as (SELECT \n" + String withQuery = "WITH BB as (SELECT \n" +
"sum(1) as X, \n" + "sum(1) as X, \n" +
"a \n" + "a \n" +
"FROM B \n" + "FROM B \n" +
...@@ -88,13 +88,13 @@ public class TestPersistentCommonTableExpressions extends AbstractBaseForCommonT ...@@ -88,13 +88,13 @@ public class TestPersistentCommonTableExpressions extends AbstractBaseForCommonT
int maxRetries = 3; int maxRetries = 3;
int expectedNumberOfRows = expectedRowData.length; int expectedNumberOfRows = expectedRowData.length;
testRepeatedQueryWithSetup(maxRetries, expectedRowData, expectedColumnNames, expectedNumberOfRows, SETUP_SQL, testRepeatedQueryWithSetup(maxRetries, expectedRowData, expectedColumnNames, expectedNumberOfRows, setupSQL,
WITH_QUERY, maxRetries-1, expectedColumnTypes); withQuery, maxRetries - 1, expectedColumnTypes);
} }
private void testPersistentRecursiveTableInCreateView() throws Exception { private void testPersistentRecursiveTableInCreateView() throws Exception {
String SETUP_SQL = "--SET TRACE_LEVEL_SYSTEM_OUT 3;\n" String setuoSQL = "--SET TRACE_LEVEL_SYSTEM_OUT 3;\n"
+"DROP TABLE IF EXISTS my_tree; \n" +"DROP TABLE IF EXISTS my_tree; \n"
+"DROP VIEW IF EXISTS v_my_tree; \n" +"DROP VIEW IF EXISTS v_my_tree; \n"
+"CREATE TABLE my_tree ( \n" +"CREATE TABLE my_tree ( \n"
...@@ -118,12 +118,11 @@ public class TestPersistentCommonTableExpressions extends AbstractBaseForCommonT ...@@ -118,12 +118,11 @@ public class TestPersistentCommonTableExpressions extends AbstractBaseForCommonT
+"INNER JOIN tree_cte mtc ON mtc.child_fk = mt.parent_fk \n" +"INNER JOIN tree_cte mtc ON mtc.child_fk = mt.parent_fk \n"
+"), \n" +"), \n"
+"unused_cte AS ( SELECT 1 AS unUsedColumn ) \n" +"unused_cte AS ( SELECT 1 AS unUsedColumn ) \n"
+"SELECT sub_tree_root_id, tree_level, parent_fk, child_fk FROM tree_cte; \n" +"SELECT sub_tree_root_id, tree_level, parent_fk, child_fk FROM tree_cte; \n";
;
String WITH_QUERY = "SELECT * FROM v_my_tree"; String withQuery = "SELECT * FROM v_my_tree";
int maxRetries = 4; int maxRetries = 4;
String[] expectedRowData =new String[]{"|1|0|null|1", String[] expectedRowData = new String[]{"|1|0|null|1",
"|11|0|1|11", "|11|0|1|11",
"|111|0|11|111", "|111|0|11|111",
"|12|0|1|12", "|12|0|1|12",
...@@ -135,15 +134,15 @@ public class TestPersistentCommonTableExpressions extends AbstractBaseForCommonT ...@@ -135,15 +134,15 @@ public class TestPersistentCommonTableExpressions extends AbstractBaseForCommonT
"|1|2|null|111", "|1|2|null|111",
"|1|2|null|121" "|1|2|null|121"
}; };
String[] expectedColumnNames =new String[]{"SUB_TREE_ROOT_ID","TREE_LEVEL","PARENT_FK","CHILD_FK"}; String[] expectedColumnNames = new String[]{"SUB_TREE_ROOT_ID", "TREE_LEVEL", "PARENT_FK", "CHILD_FK"};
String[] expectedColumnTypes =new String[]{"INTEGER","INTEGER","INTEGER","INTEGER"}; String[] expectedColumnTypes = new String[]{"INTEGER", "INTEGER", "INTEGER", "INTEGER"};
int expectedNumberOfRows = 11; int expectedNumberOfRows = 11;
testRepeatedQueryWithSetup(maxRetries, expectedRowData, expectedColumnNames, expectedNumberOfRows, SETUP_SQL, testRepeatedQueryWithSetup(maxRetries, expectedRowData, expectedColumnNames, expectedNumberOfRows, setuoSQL,
WITH_QUERY, maxRetries-1,expectedColumnTypes); withQuery, maxRetries - 1, expectedColumnTypes);
} }
private void testPersistentNonRecursiveTableInCreateView() throws Exception { private void testPersistentNonRecursiveTableInCreateView() throws Exception {
String SETUP_SQL = "" String setupSQL = ""
+"DROP VIEW IF EXISTS v_my_nr_tree; \n" +"DROP VIEW IF EXISTS v_my_nr_tree; \n"
+"DROP TABLE IF EXISTS my_table; \n" +"DROP TABLE IF EXISTS my_table; \n"
+"CREATE TABLE my_table ( \n" +"CREATE TABLE my_table ( \n"
...@@ -163,22 +162,21 @@ public class TestPersistentCommonTableExpressions extends AbstractBaseForCommonT ...@@ -163,22 +162,21 @@ public class TestPersistentCommonTableExpressions extends AbstractBaseForCommonT
+" FROM my_table mt \n" +" FROM my_table mt \n"
+"), \n" +"), \n"
+"unused_cte AS ( SELECT 1 AS unUsedColumn ) \n" +"unused_cte AS ( SELECT 1 AS unUsedColumn ) \n"
+"SELECT sub_tree_root_id, tree_level, parent_fk, child_fk FROM tree_cte_nr; \n" +"SELECT sub_tree_root_id, tree_level, parent_fk, child_fk FROM tree_cte_nr; \n";
;
String WITH_QUERY = "SELECT * FROM v_my_nr_tree"; String withQuery = "SELECT * FROM v_my_nr_tree";
int maxRetries = 6; int maxRetries = 6;
String[] expectedRowData =new String[]{ String[] expectedRowData = new String[]{
"|1|0|null|1", "|1|0|null|1",
"|11|0|1|11", "|11|0|1|11",
"|111|0|11|111", "|111|0|11|111",
"|12|0|1|12", "|12|0|1|12",
"|121|0|12|121", "|121|0|12|121",
}; };
String[] expectedColumnNames =new String[]{"SUB_TREE_ROOT_ID","TREE_LEVEL","PARENT_FK","CHILD_FK"}; String[] expectedColumnNames = new String[]{"SUB_TREE_ROOT_ID", "TREE_LEVEL", "PARENT_FK", "CHILD_FK"};
String[] expectedColumnTypes =new String[]{"INTEGER","INTEGER","INTEGER","INTEGER"}; String[] expectedColumnTypes = new String[]{"INTEGER", "INTEGER", "INTEGER", "INTEGER"};
int expectedNumberOfRows = 5; int expectedNumberOfRows = 5;
testRepeatedQueryWithSetup(maxRetries, expectedRowData, expectedColumnNames, expectedNumberOfRows, SETUP_SQL, testRepeatedQueryWithSetup(maxRetries, expectedRowData, expectedColumnNames, expectedNumberOfRows, setupSQL,
WITH_QUERY, maxRetries-1, expectedColumnTypes); withQuery, maxRetries - 1, expectedColumnTypes);
} }
} }
...@@ -78,34 +78,37 @@ public class TestMvccMultiThreaded2 extends TestBase { ...@@ -78,34 +78,37 @@ public class TestMvccMultiThreaded2 extends TestBase {
// gather stats on threads after they finished // gather stats on threads after they finished
@SuppressWarnings("unused") @SuppressWarnings("unused")
int minProcessed=Integer.MAX_VALUE, maxProcessed=0, totalProcessed=0; int minProcessed = Integer.MAX_VALUE, maxProcessed = 0, totalProcessed = 0;
for (SelectForUpdate sfu : threads) { for (SelectForUpdate sfu : threads) {
// make sure all threads have stopped by joining with them // make sure all threads have stopped by joining with them
sfu.join(); sfu.join();
totalProcessed+=sfu.iterationsProcessed; totalProcessed += sfu.iterationsProcessed;
if(sfu.iterationsProcessed>maxProcessed){ if (sfu.iterationsProcessed > maxProcessed) {
maxProcessed = sfu.iterationsProcessed; maxProcessed = sfu.iterationsProcessed;
} }
if(sfu.iterationsProcessed<minProcessed){ if (sfu.iterationsProcessed < minProcessed) {
minProcessed = sfu.iterationsProcessed; minProcessed = sfu.iterationsProcessed;
} }
} }
if(DISPLAY_STATS){ if (DISPLAY_STATS) {
System.out.println(String.format("+ INFO: TestMvccMultiThreaded2 RUN STATS threads=%d, minProcessed=%d, maxProcessed=%d, "+ System.out.println(String.format("+ INFO: TestMvccMultiThreaded2 RUN STATS threads=%d, minProcessed=%d, maxProcessed=%d, "+
"totalProcessed=%d, averagePerThread=%d, averagePerThreadPerSecond=%d\n", "totalProcessed=%d, averagePerThread=%d, averagePerThreadPerSecond=%d\n",
TEST_THREAD_COUNT, minProcessed, maxProcessed, totalProcessed, totalProcessed/TEST_THREAD_COUNT, TEST_THREAD_COUNT, minProcessed, maxProcessed, totalProcessed, totalProcessed/TEST_THREAD_COUNT,
totalProcessed/(TEST_THREAD_COUNT*TEST_TIME_SECONDS))); totalProcessed/(TEST_THREAD_COUNT * TEST_TIME_SECONDS)));
} }
IOUtils.closeSilently(conn); IOUtils.closeSilently(conn);
deleteDb(getTestName()); deleteDb(getTestName());
} }
/**
* Worker test thread selecting for update
*/
private class SelectForUpdate extends Thread { private class SelectForUpdate extends Thread {
public int iterationsProcessed = 0; public int iterationsProcessed;
@Override @Override
public void run() { public void run() {
...@@ -133,7 +136,7 @@ public class TestMvccMultiThreaded2 extends TestBase { ...@@ -133,7 +136,7 @@ public class TestMvccMultiThreaded2 extends TestBase {
iterationsProcessed++; iterationsProcessed++;
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
if (now - start > 1000 * TEST_TIME_SECONDS){ if (now - start > 1000 * TEST_TIME_SECONDS) {
done = true; done = true;
} }
} catch (JdbcSQLException e1) { } catch (JdbcSQLException e1) {
...@@ -142,8 +145,7 @@ public class TestMvccMultiThreaded2 extends TestBase { ...@@ -142,8 +145,7 @@ public class TestMvccMultiThreaded2 extends TestBase {
} }
} catch (SQLException e) { } catch (SQLException e) {
TestBase.logError("SQL error from thread "+getName(), e); TestBase.logError("SQL error from thread "+getName(), e);
} } catch (Exception e) {
catch (Exception e) {
TestBase.logError("General error from thread "+getName(), e); TestBase.logError("General error from thread "+getName(), e);
throw e; throw e;
} }
......
...@@ -51,11 +51,11 @@ public class TestMathUtils extends TestBase { ...@@ -51,11 +51,11 @@ public class TestMathUtils extends TestBase {
private void testNextPowerOf2Int() { private void testNextPowerOf2Int() {
// the largest power of two that fits into an integer // the largest power of two that fits into an integer
final int LARGEST_POW2 = 0x40000000; final int largestPower2 = 0x40000000;
int[] testValues = { 0, 1, 2, 3, 4, 12, 17, 500, 1023, int[] testValues = { 0, 1, 2, 3, 4, 12, 17, 500, 1023,
LARGEST_POW2-500, LARGEST_POW2 }; largestPower2 - 500, largestPower2 };
int[] resultValues = { 1, 1, 2, 4, 4, 16, 32, 512, 1024, int[] resultValues = { 1, 1, 2, 4, 4, 16, 32, 512, 1024,
LARGEST_POW2, LARGEST_POW2 }; largestPower2, largestPower2 };
for (int i = 0; i < testValues.length; i++) { for (int i = 0; i < testValues.length; i++) {
assertEquals(resultValues[i], MathUtils.nextPowerOf2(testValues[i])); assertEquals(resultValues[i], MathUtils.nextPowerOf2(testValues[i]));
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论