| 1 |
/* |
| 2 |
* Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, |
| 3 |
* and the EPL 1.0 (https://h2database.com/html/license.html). |
| 4 |
* Initial Developer: H2 Group |
| 5 |
*/ |
| 6 |
package org.h2.command.query; |
| 7 |
|
| 8 |
import java.util.ArrayList; |
| 9 |
|
| 10 |
import org.h2.engine.Database; |
| 11 |
import org.h2.engine.SessionLocal; |
| 12 |
import org.h2.expression.Expression; |
| 13 |
import org.h2.expression.ExpressionColumn; |
| 14 |
import org.h2.table.Column; |
| 15 |
import org.h2.table.ColumnResolver; |
| 16 |
import org.h2.value.TypeInfo; |
| 17 |
import org.h2.value.Value; |
| 18 |
|
| 19 |
/** |
| 20 |
* This class represents a column resolver for the column list of a SELECT |
| 21 |
* statement. It is used to resolve select column aliases in the HAVING clause. |
| 22 |
* Example: |
| 23 |
* <p> |
| 24 |
* SELECT X/3 AS A, COUNT(*) FROM SYSTEM_RANGE(1, 10) GROUP BY A HAVING A > 2; |
| 25 |
* </p> |
| 26 |
* |
| 27 |
* @author Thomas Mueller |
| 28 |
*/ |
| 29 |
public class SelectListColumnResolver implements ColumnResolver { |
| 30 |
|
| 31 |
private final Select select; |
| 32 |
private final Expression[] expressions; |
| 33 |
private final Column[] columns; |
| 34 |
|
| 35 |
SelectListColumnResolver(Select select) { |
| 36 |
this.select = select; |
| 37 |
int columnCount = select.getColumnCount(); |
| 38 |
columns = new Column[columnCount]; |
| 39 |
expressions = new Expression[columnCount]; |
| 40 |
ArrayList<Expression> columnList = select.getExpressions(); |
| 41 |
SessionLocal session = select.getSession(); |
| 42 |
for (int i = 0; i < columnCount; i++) { |
| 43 |
Expression expr = columnList.get(i); |
| 44 |
columns[i] = new Column(expr.getAlias(session, i), TypeInfo.TYPE_NULL, null, i); |
| 45 |
expressions[i] = expr.getNonAliasExpression(); |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
@Override |
| 50 |
public Column[] getColumns() { |
| 51 |
return columns; |
| 52 |
} |
| 53 |
|
| 54 |
@Override |
| 55 |
public Column findColumn(String name) { |
| 56 |
Database db = select.getSession().getDatabase(); |
| 57 |
for (Column column : columns) { |
| 58 |
if (db.equalsIdentifiers(column.getName(), name)) { |
| 59 |
return column; |
| 60 |
} |
| 61 |
} |
| 62 |
return null; |
| 63 |
} |
| 64 |
|
| 65 |
@Override |
| 66 |
public Select getSelect() { |
| 67 |
return select; |
| 68 |
} |
| 69 |
|
| 70 |
@Override |
| 71 |
public Value getValue(Column column) { |
| 72 |
return null; |
| 73 |
} |
| 74 |
|
| 75 |
@Override |
| 76 |
public Expression optimize(ExpressionColumn expressionColumn, Column column) { |
| 77 |
return expressions[column.getColumnId()]; |
| 78 |
} |
| 79 |
|
| 80 |
} |