Debian Codegraph @

src/main/org/h2/schema/FunctionAlias.java

raw
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.schema;
7
8 import java.lang.reflect.Array;
9 import java.lang.reflect.InvocationTargetException;
10 import java.lang.reflect.Method;
11 import java.lang.reflect.Modifier;
12 import java.sql.Connection;
13 import java.sql.ResultSet;
14 import java.sql.ResultSetMetaData;
15 import java.sql.SQLException;
16 import java.util.ArrayList;
17 import java.util.Arrays;
18
19 import org.h2.Driver;
20 import org.h2.api.ErrorCode;
21 import org.h2.engine.Constants;
22 import org.h2.engine.DbObject;
23 import org.h2.engine.SessionLocal;
24 import org.h2.expression.Alias;
25 import org.h2.expression.Expression;
26 import org.h2.expression.ExpressionColumn;
27 import org.h2.jdbc.JdbcConnection;
28 import org.h2.message.DbException;
29 import org.h2.message.Trace;
30 import org.h2.result.LocalResult;
31 import org.h2.result.ResultInterface;
32 import org.h2.table.Column;
33 import org.h2.util.JdbcUtils;
34 import org.h2.util.SourceCompiler;
35 import org.h2.util.StringUtils;
36 import org.h2.util.Utils;
37 import org.h2.value.DataType;
38 import org.h2.value.TypeInfo;
39 import org.h2.value.Value;
40 import org.h2.value.ValueNull;
41 import org.h2.value.ValueToObjectConverter;
42 import org.h2.value.ValueToObjectConverter2;
43
44 /**
45 * Represents a user-defined function, or alias.
46 *
47 * @author Thomas Mueller
48 * @author Gary Tong
49 */
50 public final class FunctionAlias extends UserDefinedFunction {
51
52 private String methodName;
53 private String source;
54 private JavaMethod[] javaMethods;
55 private boolean deterministic;
56
57 private FunctionAlias(Schema schema, int id, String name) {
58 super(schema, id, name, Trace.FUNCTION);
59 }
60
61 /**
62 * Create a new alias based on a method name.
63 *
64 * @param schema the schema
65 * @param id the id
66 * @param name the name
67 * @param javaClassMethod the class and method name
68 * @param force create the object even if the class or method does not exist
69 * @return the database object
70 */
71 public static FunctionAlias newInstance(
72 Schema schema, int id, String name, String javaClassMethod,
73 boolean force) {
74 FunctionAlias alias = new FunctionAlias(schema, id, name);
75 int paren = javaClassMethod.indexOf('(');
76 int lastDot = javaClassMethod.lastIndexOf('.', paren < 0 ?
77 javaClassMethod.length() : paren);
78 if (lastDot < 0) {
79 throw DbException.get(ErrorCode.SYNTAX_ERROR_1, javaClassMethod);
80 }
81 alias.className = javaClassMethod.substring(0, lastDot);
82 alias.methodName = javaClassMethod.substring(lastDot + 1);
83 alias.init(force);
84 return alias;
85 }
86
87 /**
88 * Create a new alias based on source code.
89 *
90 * @param schema the schema
91 * @param id the id
92 * @param name the name
93 * @param source the source code
94 * @param force create the object even if the class or method does not exist
95 * @return the database object
96 */
97 public static FunctionAlias newInstanceFromSource(
98 Schema schema, int id, String name, String source, boolean force) {
99 FunctionAlias alias = new FunctionAlias(schema, id, name);
100 alias.source = source;
101 alias.init(force);
102 return alias;
103 }
104
105 private void init(boolean force) {
106 try {
107 // at least try to compile the class, otherwise the data type is not
108 // initialized if it could be
109 load();
110 } catch (DbException e) {
111 if (!force) {
112 throw e;
113 }
114 }
115 }
116
117 private synchronized void load() {
118 if (javaMethods != null) {
119 return;
120 }
121 if (source != null) {
122 loadFromSource();
123 } else {
124 loadClass();
125 }
126 }
127
128 private void loadFromSource() {
129 SourceCompiler compiler = database.getCompiler();
130 synchronized (compiler) {
131 String fullClassName = Constants.USER_PACKAGE + "." + getName();
132 compiler.setSource(fullClassName, source);
133 try {
134 Method m = compiler.getMethod(fullClassName);
135 JavaMethod method = new JavaMethod(m, 0);
136 javaMethods = new JavaMethod[] {
137 method
138 };
139 } catch (DbException e) {
140 throw e;
141 } catch (Exception e) {
142 throw DbException.get(ErrorCode.SYNTAX_ERROR_1, e, source);
143 }
144 }
145 }
146
147 private void loadClass() {
148 Class<?> javaClass = JdbcUtils.loadUserClass(className);
149 Method[] methods = javaClass.getMethods();
150 ArrayList<JavaMethod> list = new ArrayList<>(1);
151 for (int i = 0, len = methods.length; i < len; i++) {
152 Method m = methods[i];
153 if (!Modifier.isStatic(m.getModifiers())) {
154 continue;
155 }
156 if (m.getName().equals(methodName) ||
157 getMethodSignature(m).equals(methodName)) {
158 JavaMethod javaMethod = new JavaMethod(m, i);
159 for (JavaMethod old : list) {
160 if (old.getParameterCount() == javaMethod.getParameterCount()) {
161 throw DbException.get(ErrorCode.
162 METHODS_MUST_HAVE_DIFFERENT_PARAMETER_COUNTS_2,
163 old.toString(), javaMethod.toString());
164 }
165 }
166 list.add(javaMethod);
167 }
168 }
169 if (list.isEmpty()) {
170 throw DbException.get(
171 ErrorCode.PUBLIC_STATIC_JAVA_METHOD_NOT_FOUND_1,
172 methodName + " (" + className + ")");
173 }
174 javaMethods = list.toArray(new JavaMethod[0]);
175 // Sort elements. Methods with a variable number of arguments must be at
176 // the end. Reason: there could be one method without parameters and one
177 // with a variable number. The one without parameters needs to be used
178 // if no parameters are given.
179 Arrays.sort(javaMethods);
180 }
181
182 private static String getMethodSignature(Method m) {
183 StringBuilder buff = new StringBuilder(m.getName());
184 buff.append('(');
185 Class<?>[] parameterTypes = m.getParameterTypes();
186 for (int i = 0, length = parameterTypes.length; i < length; i++) {
187 if (i > 0) {
188 // do not use a space here, because spaces are removed
189 // in CreateFunctionAlias.setJavaClassMethod()
190 buff.append(',');
191 }
192 Class<?> p = parameterTypes[i];
193 if (p.isArray()) {
194 buff.append(p.getComponentType().getName()).append("[]");
195 } else {
196 buff.append(p.getName());
197 }
198 }
199 return buff.append(')').toString();
200 }
201
202 @Override
203 public String getDropSQL() {
204 return getSQL(new StringBuilder("DROP ALIAS IF EXISTS "), DEFAULT_SQL_FLAGS).toString();
205 }
206
207 @Override
208 public String getCreateSQL() {
209 StringBuilder builder = new StringBuilder("CREATE FORCE ALIAS ");
210 getSQL(builder, DEFAULT_SQL_FLAGS);
211 if (deterministic) {
212 builder.append(" DETERMINISTIC");
213 }
214 if (source != null) {
215 StringUtils.quoteStringSQL(builder.append(" AS "), source);
216 } else {
217 StringUtils.quoteStringSQL(builder.append(" FOR "), className + '.' + methodName);
218 }
219 return builder.toString();
220 }
221
222 @Override
223 public int getType() {
224 return DbObject.FUNCTION_ALIAS;
225 }
226
227 @Override
228 public synchronized void removeChildrenAndResources(SessionLocal session) {
229 database.removeMeta(session, getId());
230 className = null;
231 methodName = null;
232 javaMethods = null;
233 invalidate();
234 }
235
236 /**
237 * Find the Java method that matches the arguments.
238 *
239 * @param args the argument list
240 * @return the Java method
241 * @throws DbException if no matching method could be found
242 */
243 public JavaMethod findJavaMethod(Expression[] args) {
244 load();
245 int parameterCount = args.length;
246 for (JavaMethod m : javaMethods) {
247 int count = m.getParameterCount();
248 if (count == parameterCount || (m.isVarArgs() &&
249 count <= parameterCount + 1)) {
250 return m;
251 }
252 }
253 throw DbException.get(ErrorCode.METHOD_NOT_FOUND_1, getName() + " (" +
254 className + ", parameter count: " + parameterCount + ")");
255 }
256
257 public String getJavaMethodName() {
258 return this.methodName;
259 }
260
261 /**
262 * Get the Java methods mapped by this function.
263 *
264 * @return the Java methods.
265 */
266 public JavaMethod[] getJavaMethods() {
267 load();
268 return javaMethods;
269 }
270
271 public void setDeterministic(boolean deterministic) {
272 this.deterministic = deterministic;
273 }
274
275 public boolean isDeterministic() {
276 return deterministic;
277 }
278
279 public String getSource() {
280 return source;
281 }
282
283 /**
284 * There may be multiple Java methods that match a function name.
285 * Each method must have a different number of parameters however.
286 * This helper class represents one such method.
287 */
288 public static class JavaMethod implements Comparable<JavaMethod> {
289 private final int id;
290 private final Method method;
291 private final TypeInfo dataType;
292 private boolean hasConnectionParam;
293 private boolean varArgs;
294 private Class<?> varArgClass;
295 private int paramCount;
296
297 JavaMethod(Method method, int id) {
298 this.method = method;
299 this.id = id;
300 Class<?>[] paramClasses = method.getParameterTypes();
301 paramCount = paramClasses.length;
302 if (paramCount > 0) {
303 Class<?> paramClass = paramClasses[0];
304 if (Connection.class.isAssignableFrom(paramClass)) {
305 hasConnectionParam = true;
306 paramCount--;
307 }
308 }
309 if (paramCount > 0) {
310 Class<?> lastArg = paramClasses[paramClasses.length - 1];
311 if (lastArg.isArray() && method.isVarArgs()) {
312 varArgs = true;
313 varArgClass = lastArg.getComponentType();
314 }
315 }
316 Class<?> returnClass = method.getReturnType();
317 dataType = ResultSet.class.isAssignableFrom(returnClass) ? null
318 : ValueToObjectConverter2.classToType(returnClass);
319 }
320
321 @Override
322 public String toString() {
323 return method.toString();
324 }
325
326 /**
327 * Check if this function requires a database connection.
328 *
329 * @return if the function requires a connection
330 */
331 public boolean hasConnectionParam() {
332 return this.hasConnectionParam;
333 }
334
335 /**
336 * Call the user-defined function and return the value.
337 *
338 * @param session the session
339 * @param args the argument list
340 * @param columnList true if the function should only return the column
341 * list
342 * @return the value
343 */
344 public Value getValue(SessionLocal session, Expression[] args, boolean columnList) {
345 Object returnValue = execute(session, args, columnList);
346 if (Value.class.isAssignableFrom(method.getReturnType())) {
347 return (Value) returnValue;
348 }
349 return ValueToObjectConverter.objectToValue(session, returnValue, dataType.getValueType())
350 .convertTo(dataType, session);
351 }
352
353 /**
354 * Call the table user-defined function and return the value.
355 *
356 * @param session the session
357 * @param args the argument list
358 * @param columnList true if the function should only return the column
359 * list
360 * @return the value
361 */
362 public ResultInterface getTableValue(SessionLocal session, Expression[] args, boolean columnList) {
363 Object o = execute(session, args, columnList);
364 if (o == null) {
365 throw DbException.get(ErrorCode.FUNCTION_MUST_RETURN_RESULT_SET_1, method.getName());
366 }
367 if (ResultInterface.class.isAssignableFrom(method.getReturnType())) {
368 return (ResultInterface) o;
369 }
370 return resultSetToResult(session, (ResultSet) o, columnList ? 0 : Integer.MAX_VALUE);
371 }
372
373 /**
374 * Create a result for the given result set.
375 *
376 * @param session the session
377 * @param resultSet the result set
378 * @param maxrows the maximum number of rows to read (0 to just read the
379 * meta data)
380 * @return the value
381 */
382 public static ResultInterface resultSetToResult(SessionLocal session, ResultSet resultSet, int maxrows) {
383 try (ResultSet rs = resultSet) {
384 ResultSetMetaData meta = rs.getMetaData();
385 int columnCount = meta.getColumnCount();
386 Expression[] columns = new Expression[columnCount];
387 for (int i = 0; i < columnCount; i++) {
388 String alias = meta.getColumnLabel(i + 1);
389 String name = meta.getColumnName(i + 1);
390 String columnTypeName = meta.getColumnTypeName(i + 1);
391 int columnType = DataType.convertSQLTypeToValueType(meta.getColumnType(i + 1), columnTypeName);
392 int precision = meta.getPrecision(i + 1);
393 int scale = meta.getScale(i + 1);
394 TypeInfo typeInfo;
395 if (columnType == Value.ARRAY && columnTypeName.endsWith(" ARRAY")) {
396 typeInfo = TypeInfo
397 .getTypeInfo(Value.ARRAY, -1L, 0,
398 TypeInfo.getTypeInfo(DataType.getTypeByName(
399 columnTypeName.substring(0, columnTypeName.length() - 6),
400 session.getMode()).type));
401 } else {
402 typeInfo = TypeInfo.getTypeInfo(columnType, precision, scale, null);
403 }
404 Expression e = new ExpressionColumn(session.getDatabase(), new Column(name, typeInfo));
405 if (!alias.equals(name)) {
406 e = new Alias(e, alias, false);
407 }
408 columns[i] = e;
409 }
410 LocalResult result = new LocalResult(session, columns, columnCount, columnCount);
411 for (int i = 0; i < maxrows && rs.next(); i++) {
412 Value[] list = new Value[columnCount];
413 for (int j = 0; j < columnCount; j++) {
414 list[j] = ValueToObjectConverter.objectToValue(session, rs.getObject(j + 1),
415 columns[j].getType().getValueType());
416 }
417 result.addRow(list);
418 }
419 result.done();
420 return result;
421 } catch (SQLException e) {
422 throw DbException.convert(e);
423 }
424 }
425
426 private Object execute(SessionLocal session, Expression[] args, boolean columnList) {
427 Class<?>[] paramClasses = method.getParameterTypes();
428 Object[] params = new Object[paramClasses.length];
429 int p = 0;
430 JdbcConnection conn = session.createConnection(columnList);
431 if (hasConnectionParam && params.length > 0) {
432 params[p++] = conn;
433 }
434
435 // allocate array for varArgs parameters
436 Object varArg = null;
437 if (varArgs) {
438 int len = args.length - params.length + 1 +
439 (hasConnectionParam ? 1 : 0);
440 varArg = Array.newInstance(varArgClass, len);
441 params[params.length - 1] = varArg;
442 }
443
444 for (int a = 0, len = args.length; a < len; a++, p++) {
445 boolean currentIsVarArg = varArgs &&
446 p >= paramClasses.length - 1;
447 Class<?> paramClass;
448 if (currentIsVarArg) {
449 paramClass = varArgClass;
450 } else {
451 paramClass = paramClasses[p];
452 }
453 Value v = args[a].getValue(session);
454 Object o;
455 if (Value.class.isAssignableFrom(paramClass)) {
456 o = v;
457 } else {
458 boolean primitive = paramClass.isPrimitive();
459 if (v == ValueNull.INSTANCE) {
460 if (primitive) {
461 if (columnList) {
462 // If the column list is requested, the parameters
463 // may be null. Need to set to default value,
464 // otherwise the function can't be called at all.
465 o = DataType.getDefaultForPrimitiveType(paramClass);
466 } else {
467 // NULL for a java primitive: return NULL
468 return null;
469 }
470 } else {
471 o = null;
472 }
473 } else {
474 o = ValueToObjectConverter.valueToObject(
475 (Class<?>) (primitive ? Utils.getNonPrimitiveClass(paramClass) : paramClass), v, conn);
476 }
477 }
478 if (currentIsVarArg) {
479 Array.set(varArg, p - params.length + 1, o);
480 } else {
481 params[p] = o;
482 }
483 }
484 boolean old = session.getAutoCommit();
485 Value identity = session.getLastIdentity();
486 boolean defaultConnection = session.getDatabase().
487 getSettings().defaultConnection;
488 try {
489 session.setAutoCommit(false);
490 Object returnValue;
491 try {
492 if (defaultConnection) {
493 Driver.setDefaultConnection(session.createConnection(columnList));
494 }
495 returnValue = method.invoke(null, params);
496 if (returnValue == null) {
497 return null;
498 }
499 } catch (InvocationTargetException e) {
500 StringBuilder builder = new StringBuilder(method.getName()).append('(');
501 for (int i = 0, length = params.length; i < length; i++) {
502 if (i > 0) {
503 builder.append(", ");
504 }
505 builder.append(params[i]);
506 }
507 builder.append(')');
508 throw DbException.convertInvocation(e, builder.toString());
509 } catch (Exception e) {
510 throw DbException.convert(e);
511 }
512 return returnValue;
513 } finally {
514 session.setLastIdentity(identity);
515 session.setAutoCommit(old);
516 if (defaultConnection) {
517 Driver.setDefaultConnection(null);
518 }
519 }
520 }
521
522 public Class<?>[] getColumnClasses() {
523 return method.getParameterTypes();
524 }
525
526 /**
527 * Returns data type information for regular functions or {@code null}
528 * for table value functions.
529 *
530 * @return data type information for regular functions or {@code null}
531 * for table value functions
532 */
533 public TypeInfo getDataType() {
534 return dataType;
535 }
536
537 public int getParameterCount() {
538 return paramCount;
539 }
540
541 public boolean isVarArgs() {
542 return varArgs;
543 }
544
545 @Override
546 public int compareTo(JavaMethod m) {
547 if (varArgs != m.varArgs) {
548 return varArgs ? 1 : -1;
549 }
550 if (paramCount != m.paramCount) {
551 return paramCount - m.paramCount;
552 }
553 if (hasConnectionParam != m.hasConnectionParam) {
554 return hasConnectionParam ? 1 : -1;
555 }
556 return id - m.id;
557 }
558
559 }
560
561 }