// maxRows is set (maxRows 0 means no limit)
int l;
if (limitExpr == null) {
l = -1;
} else {
Value v = limitExpr.getValue(session);
l = v == ValueNull.INSTANCE ? -1 : v.getInt();
}
if (l < 0) {
// for limitExpr, 0 means no rows, and -1 means no limit
l = maxRows;
} else {
l = Math.min(l, maxRows);
}
limitExpr = ValueExpression.get(ValueInt.get(l));
}
if (session.getDatabase().getSettings().optimizeInsertFromSelect) {
if (unionType == UNION_ALL && target != null) {
if (sort == null && !distinct && maxRows == 0 && offsetExpr == null && limitExpr == null) {
left.query(0, target);
right.query(0, target);
return null;
}
}
}
int columnCount = left.getColumnCount();
LocalResult result = new LocalResult(session, expressionArray, columnCount);
if (sort != null) {
result.setSortOrder(sort);
}
if (distinct) {
left.setDistinct(true);
right.setDistinct(true);
result.setDistinct();
}
if (randomAccessResult) {
result.setRandomAccess();
}
switch (unionType) {
case UNION:
case EXCEPT:
left.setDistinct(true);
right.setDistinct(true);
result.setDistinct();
break;
case UNION_ALL:
break;
case INTERSECT:
left.setDistinct(true);
right.setDistinct(true);
break;
default:
DbException.throwInternalError("type=" + unionType);
}
ResultInterface l = left.query(0);
ResultInterface r = right.query(0);
l.reset();
r.reset();
switch (unionType) {
case UNION_ALL:
case UNION: {
while (l.next()) {
result.addRow(convert(l.currentRow(), columnCount));
}
while (r.next()) {
result.addRow(convert(r.currentRow(), columnCount));
}
break;
}
case EXCEPT: {
while (l.next()) {
result.addRow(convert(l.currentRow(), columnCount));
}
while (r.next()) {
result.removeDistinct(convert(r.currentRow(), columnCount));
}
break;
}
case INTERSECT: {
LocalResult temp = new LocalResult(session, expressionArray, columnCount);
temp.setDistinct();
temp.setRandomAccess();
while (l.next()) {
temp.addRow(convert(l.currentRow(), columnCount));
}
while (r.next()) {
Value[] values = convert(r.currentRow(), columnCount);
if (temp.containsDistinct(values)) {
result.addRow(values);
}
}
break;
}
default:
DbException.throwInternalError("type=" + unionType);
}
if (offsetExpr != null) {
result.setOffset(offsetExpr.getValue(session).getInt());
}
if (limitExpr != null) {
Value v = limitExpr.getValue(session);
if (v != ValueNull.INSTANCE) {
result.setLimit(v.getInt());
}
}
result.done();
if (target != null) {
while (result.next()) {