| 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.expression.function.table; |
| 7 |
|
| 8 |
import java.util.Arrays; |
| 9 |
|
| 10 |
import org.h2.engine.SessionLocal; |
| 11 |
import org.h2.expression.Expression; |
| 12 |
import org.h2.expression.ExpressionWithVariableParameters; |
| 13 |
import org.h2.expression.function.NamedExpression; |
| 14 |
import org.h2.message.DbException; |
| 15 |
import org.h2.result.ResultInterface; |
| 16 |
import org.h2.util.HasSQL; |
| 17 |
|
| 18 |
/** |
| 19 |
* A table value function. |
| 20 |
*/ |
| 21 |
public abstract class TableFunction implements HasSQL, NamedExpression, ExpressionWithVariableParameters { |
| 22 |
|
| 23 |
protected Expression[] args; |
| 24 |
|
| 25 |
private int argsCount; |
| 26 |
|
| 27 |
protected TableFunction(Expression[] args) { |
| 28 |
this.args = args; |
| 29 |
} |
| 30 |
|
| 31 |
@Override |
| 32 |
public void addParameter(Expression param) { |
| 33 |
int capacity = args.length; |
| 34 |
if (argsCount >= capacity) { |
| 35 |
args = Arrays.copyOf(args, capacity * 2); |
| 36 |
} |
| 37 |
args[argsCount++] = param; |
| 38 |
} |
| 39 |
|
| 40 |
@Override |
| 41 |
public void doneWithParameters() throws DbException { |
| 42 |
if (args.length != argsCount) { |
| 43 |
args = Arrays.copyOf(args, argsCount); |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Get a result with. |
| 49 |
* |
| 50 |
* @param session |
| 51 |
* the session |
| 52 |
* @return the result |
| 53 |
*/ |
| 54 |
public abstract ResultInterface getValue(SessionLocal session); |
| 55 |
|
| 56 |
/** |
| 57 |
* Get an empty result with the column names set. |
| 58 |
* |
| 59 |
* @param session |
| 60 |
* the session |
| 61 |
* @return the empty result |
| 62 |
*/ |
| 63 |
public abstract ResultInterface getValueTemplate(SessionLocal session); |
| 64 |
|
| 65 |
/** |
| 66 |
* Try to optimize this table function |
| 67 |
* |
| 68 |
* @param session |
| 69 |
* the session |
| 70 |
*/ |
| 71 |
public void optimize(SessionLocal session) { |
| 72 |
for (int i = 0, l = args.length; i < l; i++) { |
| 73 |
args[i] = args[i].optimize(session); |
| 74 |
} |
| 75 |
} |
| 76 |
|
| 77 |
/** |
| 78 |
* Whether the function always returns the same result for the same |
| 79 |
* parameters. |
| 80 |
* |
| 81 |
* @return true if it does |
| 82 |
*/ |
| 83 |
public abstract boolean isDeterministic(); |
| 84 |
|
| 85 |
@Override |
| 86 |
public StringBuilder getSQL(StringBuilder builder, int sqlFlags) { |
| 87 |
return Expression.writeExpressions(builder.append(getName()).append('('), args, sqlFlags).append(')'); |
| 88 |
} |
| 89 |
|
| 90 |
} |