Debian Codegraph @

src/main/org/h2/util/JdbcUtils.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.util;
7
8 import java.io.ByteArrayInputStream;
9 import java.io.ByteArrayOutputStream;
10 import java.io.IOException;
11 import java.io.ObjectInputStream;
12 import java.io.ObjectOutputStream;
13 import java.io.ObjectStreamClass;
14 import java.lang.reflect.InvocationTargetException;
15 import java.lang.reflect.Method;
16 import java.nio.charset.StandardCharsets;
17 import java.sql.Connection;
18 import java.sql.DatabaseMetaData;
19 import java.sql.Driver;
20 import java.sql.DriverManager;
21 import java.sql.PreparedStatement;
22 import java.sql.ResultSet;
23 import java.sql.SQLException;
24 import java.sql.Statement;
25 import java.sql.Types;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Comparator;
29 import java.util.HashSet;
30 import java.util.Properties;
31
32 import javax.naming.Context;
33 import javax.sql.DataSource;
34 import org.h2.api.ErrorCode;
35 import org.h2.api.JavaObjectSerializer;
36 import org.h2.engine.Constants;
37 import org.h2.engine.SysProperties;
38 import org.h2.jdbc.JdbcConnection;
39 import org.h2.jdbc.JdbcPreparedStatement;
40 import org.h2.message.DbException;
41 import org.h2.tools.SimpleResultSet;
42 import org.h2.util.Utils.ClassFactory;
43 import org.h2.value.Value;
44 import org.h2.value.ValueLob;
45 import org.h2.value.ValueToObjectConverter;
46 import org.h2.value.ValueUuid;
47
48 /**
49 * This is a utility class with JDBC helper functions.
50 */
51 public class JdbcUtils {
52
53 /**
54 * The serializer to use.
55 */
56 public static JavaObjectSerializer serializer;
57
58 private static final String[] DRIVERS = {
59 "h2:", "org.h2.Driver",
60 "Cache:", "com.intersys.jdbc.CacheDriver",
61 "daffodilDB://", "in.co.daffodil.db.rmi.RmiDaffodilDBDriver",
62 "daffodil", "in.co.daffodil.db.jdbc.DaffodilDBDriver",
63 "db2:", "com.ibm.db2.jcc.DB2Driver",
64 "derby:net:", "org.apache.derby.client.ClientAutoloadedDriver",
65 "derby://", "org.apache.derby.client.ClientAutoloadedDriver",
66 "derby:", "org.apache.derby.iapi.jdbc.AutoloadedDriver",
67 "FrontBase:", "com.frontbase.jdbc.FBJDriver",
68 "firebirdsql:", "org.firebirdsql.jdbc.FBDriver",
69 "hsqldb:", "org.hsqldb.jdbcDriver",
70 "informix-sqli:", "com.informix.jdbc.IfxDriver",
71 "jtds:", "net.sourceforge.jtds.jdbc.Driver",
72 "microsoft:", "com.microsoft.jdbc.sqlserver.SQLServerDriver",
73 "mimer:", "com.mimer.jdbc.Driver",
74 "mysql:", "com.mysql.cj.jdbc.Driver",
75 "mariadb:", "org.mariadb.jdbc.Driver",
76 "odbc:", "sun.jdbc.odbc.JdbcOdbcDriver",
77 "oracle:", "oracle.jdbc.driver.OracleDriver",
78 "pervasive:", "com.pervasive.jdbc.v2.Driver",
79 "pointbase:micro:", "com.pointbase.me.jdbc.jdbcDriver",
80 "pointbase:", "com.pointbase.jdbc.jdbcUniversalDriver",
81 "postgresql:", "org.postgresql.Driver",
82 "sybase:", "com.sybase.jdbc3.jdbc.SybDriver",
83 "sqlserver:", "com.microsoft.sqlserver.jdbc.SQLServerDriver",
84 "teradata:", "com.ncr.teradata.TeraDriver",
85 };
86
87 private static final byte[] UUID_PREFIX =
88 "\254\355\0\5sr\0\16java.util.UUID\274\231\3\367\230m\205/\2\0\2J\0\14leastSigBitsJ\0\13mostSigBitsxp"
89 .getBytes(StandardCharsets.ISO_8859_1);
90
91 private static boolean allowAllClasses;
92 private static HashSet<String> allowedClassNames;
93
94 /**
95 * In order to manage more than one class loader
96 */
97 private static final ArrayList<ClassFactory> userClassFactories = new ArrayList<>();
98
99 private static String[] allowedClassNamePrefixes;
100
101 private JdbcUtils() {
102 // utility class
103 }
104
105 /**
106 * Add a class factory in order to manage more than one class loader.
107 *
108 * @param classFactory An object that implements ClassFactory
109 */
110 public static void addClassFactory(ClassFactory classFactory) {
111 userClassFactories.add(classFactory);
112 }
113
114 /**
115 * Remove a class factory
116 *
117 * @param classFactory Already inserted class factory instance
118 */
119 public static void removeClassFactory(ClassFactory classFactory) {
120 userClassFactories.remove(classFactory);
121 }
122
123 static {
124 String clazz = SysProperties.JAVA_OBJECT_SERIALIZER;
125 if (clazz != null) {
126 try {
127 serializer = (JavaObjectSerializer) loadUserClass(clazz).getDeclaredConstructor().newInstance();
128 } catch (Exception e) {
129 throw DbException.convert(e);
130 }
131 }
132 }
133
134 /**
135 * Load a class, but check if it is allowed to load this class first. To
136 * perform access rights checking, the system property h2.allowedClasses
137 * needs to be set to a list of class file name prefixes.
138 *
139 * @param <Z> generic return type
140 * @param className the name of the class
141 * @return the class object
142 */
143 @SuppressWarnings("unchecked")
144 public static <Z> Class<Z> loadUserClass(String className) {
145 if (allowedClassNames == null) {
146 // initialize the static fields
147 String s = SysProperties.ALLOWED_CLASSES;
148 ArrayList<String> prefixes = new ArrayList<>();
149 boolean allowAll = false;
150 HashSet<String> classNames = new HashSet<>();
151 for (String p : StringUtils.arraySplit(s, ',', true)) {
152 if (p.equals("*")) {
153 allowAll = true;
154 } else if (p.endsWith("*")) {
155 prefixes.add(p.substring(0, p.length() - 1));
156 } else {
157 classNames.add(p);
158 }
159 }
160 allowedClassNamePrefixes = prefixes.toArray(new String[0]);
161 allowAllClasses = allowAll;
162 allowedClassNames = classNames;
163 }
164 if (!allowAllClasses && !allowedClassNames.contains(className)) {
165 boolean allowed = false;
166 for (String s : allowedClassNamePrefixes) {
167 if (className.startsWith(s)) {
168 allowed = true;
169 break;
170 }
171 }
172 if (!allowed) {
173 throw DbException.get(
174 ErrorCode.ACCESS_DENIED_TO_CLASS_1, className);
175 }
176 }
177 // Use provided class factory first.
178 for (ClassFactory classFactory : userClassFactories) {
179 if (classFactory.match(className)) {
180 try {
181 Class<?> userClass = classFactory.loadClass(className);
182 if (userClass != null) {
183 return (Class<Z>) userClass;
184 }
185 } catch (Exception e) {
186 throw DbException.get(
187 ErrorCode.CLASS_NOT_FOUND_1, e, className);
188 }
189 }
190 }
191 // Use local ClassLoader
192 try {
193 return (Class<Z>) Class.forName(className);
194 } catch (ClassNotFoundException e) {
195 try {
196 return (Class<Z>) Class.forName(
197 className, true,
198 Thread.currentThread().getContextClassLoader());
199 } catch (Exception e2) {
200 throw DbException.get(
201 ErrorCode.CLASS_NOT_FOUND_1, e, className);
202 }
203 } catch (NoClassDefFoundError e) {
204 throw DbException.get(
205 ErrorCode.CLASS_NOT_FOUND_1, e, className);
206 } catch (Error e) {
207 // UnsupportedClassVersionError
208 throw DbException.get(
209 ErrorCode.GENERAL_ERROR_1, e, className);
210 }
211 }
212
213 /**
214 * Close a statement without throwing an exception.
215 *
216 * @param stat the statement or null
217 */
218 public static void closeSilently(Statement stat) {
219 if (stat != null) {
220 try {
221 stat.close();
222 } catch (SQLException e) {
223 // ignore
224 }
225 }
226 }
227
228 /**
229 * Close a connection without throwing an exception.
230 *
231 * @param conn the connection or null
232 */
233 public static void closeSilently(Connection conn) {
234 if (conn != null) {
235 try {
236 conn.close();
237 } catch (SQLException e) {
238 // ignore
239 }
240 }
241 }
242
243 /**
244 * Close a result set without throwing an exception.
245 *
246 * @param rs the result set or null
247 */
248 public static void closeSilently(ResultSet rs) {
249 if (rs != null) {
250 try {
251 rs.close();
252 } catch (SQLException e) {
253 // ignore
254 }
255 }
256 }
257
258 /**
259 * Open a new database connection with the given settings.
260 *
261 * @param driver the driver class name
262 * @param url the database URL
263 * @param user the user name
264 * @param password the password
265 * @return the database connection
266 * @throws SQLException on failure
267 */
268 public static Connection getConnection(String driver, String url,
269 String user, String password) throws SQLException {
270 return getConnection(driver, url, user, password, null, false);
271 }
272
273 /**
274 * Open a new database connection with the given settings.
275 *
276 * @param driver the driver class name
277 * @param url the database URL
278 * @param user the user name or {@code null}
279 * @param password the password or {@code null}
280 * @param networkConnectionInfo the network connection information, or {@code null}
281 * @param forbidCreation whether database creation is forbidden
282 * @return the database connection
283 * @throws SQLException on failure
284 */
285 public static Connection getConnection(String driver, String url, String user, String password,
286 NetworkConnectionInfo networkConnectionInfo, boolean forbidCreation) throws SQLException {
287 if (url.startsWith(Constants.START_URL)) {
288 JdbcConnection connection = new JdbcConnection(url, null, user, password, forbidCreation);
289 if (networkConnectionInfo != null) {
290 connection.getSession().setNetworkConnectionInfo(networkConnectionInfo);
291 }
292 return connection;
293 }
294 if (StringUtils.isNullOrEmpty(driver)) {
295 JdbcUtils.load(url);
296 } else {
297 Class<?> d = loadUserClass(driver);
298 try {
299 if (java.sql.Driver.class.isAssignableFrom(d)) {
300 Driver driverInstance = (Driver) d.getDeclaredConstructor().newInstance();
301 Properties prop = new Properties();
302 if (user != null) {
303 prop.setProperty("user", user);
304 }
305 if (password != null) {
306 prop.setProperty("password", password);
307 }
308 /*
309 * fix issue #695 with drivers with the same jdbc
310 * subprotocol in classpath of jdbc drivers (as example
311 * redshift and postgresql drivers)
312 */
313 Connection connection = driverInstance.connect(url, prop);
314 if (connection != null) {
315 return connection;
316 }
317 throw new SQLException("Driver " + driver + " is not suitable for " + url, "08001");
318 } else if (javax.naming.Context.class.isAssignableFrom(d)) {
319 if (!url.startsWith("java:")) {
320 throw new SQLException("Only java scheme is supported for JNDI lookups", "08001");
321 }
322 // JNDI context
323 Context context = (Context) d.getDeclaredConstructor().newInstance();
324 DataSource ds = (DataSource) context.lookup(url);
325 if (StringUtils.isNullOrEmpty(user) && StringUtils.isNullOrEmpty(password)) {
326 return ds.getConnection();
327 }
328 return ds.getConnection(user, password);
329 }
330 } catch (Exception e) {
331 throw DbException.toSQLException(e);
332 }
333 // don't know, but maybe it loaded a JDBC Driver
334 }
335 return DriverManager.getConnection(url, user, password);
336 }
337
338 /**
339 * Get the driver class name for the given URL, or null if the URL is
340 * unknown.
341 *
342 * @param url the database URL
343 * @return the driver class name
344 */
345 public static String getDriver(String url) {
346 if (url.startsWith("jdbc:")) {
347 url = url.substring("jdbc:".length());
348 for (int i = 0; i < DRIVERS.length; i += 2) {
349 String prefix = DRIVERS[i];
350 if (url.startsWith(prefix)) {
351 return DRIVERS[i + 1];
352 }
353 }
354 }
355 return null;
356 }
357
358 /**
359 * Load the driver class for the given URL, if the database URL is known.
360 *
361 * @param url the database URL
362 */
363 public static void load(String url) {
364 String driver = getDriver(url);
365 if (driver != null) {
366 loadUserClass(driver);
367 }
368 }
369
370 /**
371 * Serialize the object to a byte array, using the serializer specified by
372 * the connection info if set, or the default serializer.
373 *
374 * @param obj the object to serialize
375 * @param javaObjectSerializer the object serializer (may be null)
376 * @return the byte array
377 */
378 public static byte[] serialize(Object obj, JavaObjectSerializer javaObjectSerializer) {
379 try {
380 if (javaObjectSerializer != null) {
381 return javaObjectSerializer.serialize(obj);
382 }
383 if (serializer != null) {
384 return serializer.serialize(obj);
385 }
386 ByteArrayOutputStream out = new ByteArrayOutputStream();
387 ObjectOutputStream os = new ObjectOutputStream(out);
388 os.writeObject(obj);
389 return out.toByteArray();
390 } catch (Throwable e) {
391 throw DbException.get(ErrorCode.SERIALIZATION_FAILED_1, e, e.toString());
392 }
393 }
394
395 /**
396 * De-serialize the byte array to an object, eventually using the serializer
397 * specified by the connection info.
398 *
399 * @param data the byte array
400 * @param javaObjectSerializer the object serializer (may be null)
401 * @return the object
402 * @throws DbException if serialization fails
403 */
404 public static Object deserialize(byte[] data, JavaObjectSerializer javaObjectSerializer) {
405 try {
406 if (javaObjectSerializer != null) {
407 return javaObjectSerializer.deserialize(data);
408 }
409 if (serializer != null) {
410 return serializer.deserialize(data);
411 }
412 ByteArrayInputStream in = new ByteArrayInputStream(data);
413 ObjectInputStream is;
414 if (SysProperties.USE_THREAD_CONTEXT_CLASS_LOADER) {
415 final ClassLoader loader = Thread.currentThread().getContextClassLoader();
416 is = new ObjectInputStream(in) {
417 @Override
418 protected Class<?> resolveClass(ObjectStreamClass desc)
419 throws IOException, ClassNotFoundException {
420 try {
421 return Class.forName(desc.getName(), true, loader);
422 } catch (ClassNotFoundException e) {
423 return super.resolveClass(desc);
424 }
425 }
426 };
427 } else {
428 is = new ObjectInputStream(in);
429 }
430 return is.readObject();
431 } catch (Throwable e) {
432 throw DbException.get(ErrorCode.DESERIALIZATION_FAILED_1, e, e.toString());
433 }
434 }
435
436 /**
437 * De-serialize the byte array to a UUID object. This method is called on
438 * the server side where regular de-serialization of user-supplied Java
439 * objects may create a security hole if object was maliciously crafted.
440 * Unlike {@link #deserialize(byte[], JavaObjectSerializer)}, this method
441 * does not try to de-serialize instances of other classes.
442 *
443 * @param data the byte array
444 * @return the UUID object
445 * @throws DbException if serialization fails
446 */
447 public static ValueUuid deserializeUuid(byte[] data) {
448 uuid: if (data.length == 80) {
449 for (int i = 0; i < 64; i++) {
450 if (data[i] != UUID_PREFIX[i]) {
451 break uuid;
452 }
453 }
454 return ValueUuid.get(Bits.readLong(data, 72), Bits.readLong(data, 64));
455 }
456 throw DbException.get(ErrorCode.DESERIALIZATION_FAILED_1, "Is not a UUID");
457 }
458
459 /**
460 * Set a value as a parameter in a prepared statement.
461 *
462 * @param prep the prepared statement
463 * @param parameterIndex the parameter index
464 * @param value the value
465 * @param conn the own connection
466 * @throws SQLException on failure
467 */
468 public static void set(PreparedStatement prep, int parameterIndex, Value value, JdbcConnection conn)
469 throws SQLException {
470 if (prep instanceof JdbcPreparedStatement) {
471 if (value instanceof ValueLob) {
472 setLob(prep, parameterIndex, (ValueLob) value);
473 } else {
474 prep.setObject(parameterIndex, value);
475 }
476 } else {
477 setOther(prep, parameterIndex, value, conn);
478 }
479 }
480
481 private static void setOther(PreparedStatement prep, int parameterIndex, Value value, JdbcConnection conn)
482 throws SQLException {
483 int valueType = value.getValueType();
484 switch (valueType) {
485 case Value.NULL:
486 prep.setNull(parameterIndex, Types.NULL);
487 break;
488 case Value.BOOLEAN:
489 prep.setBoolean(parameterIndex, value.getBoolean());
490 break;
491 case Value.TINYINT:
492 prep.setByte(parameterIndex, value.getByte());
493 break;
494 case Value.SMALLINT:
495 prep.setShort(parameterIndex, value.getShort());
496 break;
497 case Value.INTEGER:
498 prep.setInt(parameterIndex, value.getInt());
499 break;
500 case Value.BIGINT:
501 prep.setLong(parameterIndex, value.getLong());
502 break;
503 case Value.NUMERIC:
504 case Value.DECFLOAT:
505 prep.setBigDecimal(parameterIndex, value.getBigDecimal());
506 break;
507 case Value.DOUBLE:
508 prep.setDouble(parameterIndex, value.getDouble());
509 break;
510 case Value.REAL:
511 prep.setFloat(parameterIndex, value.getFloat());
512 break;
513 case Value.TIME:
514 try {
515 prep.setObject(parameterIndex, JSR310Utils.valueToLocalTime(value, null), Types.TIME);
516 } catch (SQLException ignore) {
517 prep.setTime(parameterIndex, LegacyDateTimeUtils.toTime(null, null, value));
518 }
519 break;
520 case Value.DATE:
521 try {
522 prep.setObject(parameterIndex, JSR310Utils.valueToLocalDate(value, null), Types.DATE);
523 } catch (SQLException ignore) {
524 prep.setDate(parameterIndex, LegacyDateTimeUtils.toDate(null, null, value));
525 }
526 break;
527 case Value.TIMESTAMP:
528 try {
529 prep.setObject(parameterIndex, JSR310Utils.valueToLocalDateTime(value, null), Types.TIMESTAMP);
530 } catch (SQLException ignore) {
531 prep.setTimestamp(parameterIndex, LegacyDateTimeUtils.toTimestamp(null, null, value));
532 }
533 break;
534 case Value.VARBINARY:
535 case Value.BINARY:
536 case Value.GEOMETRY:
537 case Value.JSON:
538 prep.setBytes(parameterIndex, value.getBytesNoCopy());
539 break;
540 case Value.VARCHAR:
541 case Value.VARCHAR_IGNORECASE:
542 case Value.ENUM:
543 case Value.INTERVAL_YEAR:
544 case Value.INTERVAL_MONTH:
545 case Value.INTERVAL_DAY:
546 case Value.INTERVAL_HOUR:
547 case Value.INTERVAL_MINUTE:
548 case Value.INTERVAL_SECOND:
549 case Value.INTERVAL_YEAR_TO_MONTH:
550 case Value.INTERVAL_DAY_TO_HOUR:
551 case Value.INTERVAL_DAY_TO_MINUTE:
552 case Value.INTERVAL_DAY_TO_SECOND:
553 case Value.INTERVAL_HOUR_TO_MINUTE:
554 case Value.INTERVAL_HOUR_TO_SECOND:
555 case Value.INTERVAL_MINUTE_TO_SECOND:
556 prep.setString(parameterIndex, value.getString());
557 break;
558 case Value.BLOB:
559 case Value.CLOB:
560 setLob(prep, parameterIndex, (ValueLob) value);
561 break;
562 case Value.ARRAY:
563 prep.setArray(parameterIndex, prep.getConnection().createArrayOf("NULL",
564 (Object[]) ValueToObjectConverter.valueToDefaultObject(value, conn, true)));
565 break;
566 case Value.JAVA_OBJECT:
567 prep.setObject(parameterIndex,
568 JdbcUtils.deserialize(value.getBytesNoCopy(), conn.getJavaObjectSerializer()),
569 Types.JAVA_OBJECT);
570 break;
571 case Value.UUID:
572 prep.setBytes(parameterIndex, value.getBytes());
573 break;
574 case Value.CHAR:
575 try {
576 prep.setObject(parameterIndex, value.getString(), Types.CHAR);
577 } catch (SQLException ignore) {
578 prep.setString(parameterIndex, value.getString());
579 }
580 break;
581 case Value.TIMESTAMP_TZ:
582 try {
583 prep.setObject(parameterIndex, JSR310Utils.valueToOffsetDateTime(value, null),
584 Types.TIMESTAMP_WITH_TIMEZONE);
585 return;
586 } catch (SQLException ignore) {
587 prep.setString(parameterIndex, value.getString());
588 }
589 break;
590 case Value.TIME_TZ:
591 try {
592 prep.setObject(parameterIndex, JSR310Utils.valueToOffsetTime(value, null), Types.TIME_WITH_TIMEZONE);
593 return;
594 } catch (SQLException ignore) {
595 prep.setString(parameterIndex, value.getString());
596 }
597 break;
598 default:
599 throw DbException.getUnsupportedException(Value.getTypeName(valueType));
600 }
601 }
602
603 private static void setLob(PreparedStatement prep, int parameterIndex, ValueLob value) throws SQLException {
604 if (value.getValueType() == Value.BLOB) {
605 long p = value.octetLength();
606 prep.setBinaryStream(parameterIndex, value.getInputStream(), p > Integer.MAX_VALUE ? -1 : (int) p);
607 } else {
608 long p = value.charLength();
609 prep.setCharacterStream(parameterIndex, value.getReader(), p > Integer.MAX_VALUE ? -1 : (int) p);
610 }
611 }
612
613 /**
614 * Get metadata from the database.
615 *
616 * @param conn the connection
617 * @param sql the SQL statement
618 * @return the metadata
619 * @throws SQLException on failure
620 */
621 public static ResultSet getMetaResultSet(Connection conn, String sql)
622 throws SQLException {
623 DatabaseMetaData meta = conn.getMetaData();
624 if (isBuiltIn(sql, "@best_row_identifier")) {
625 String[] p = split(sql);
626 int scale = p[4] == null ? 0 : Integer.parseInt(p[4]);
627 boolean nullable = Boolean.parseBoolean(p[5]);
628 return meta.getBestRowIdentifier(p[1], p[2], p[3], scale, nullable);
629 } else if (isBuiltIn(sql, "@catalogs")) {
630 return meta.getCatalogs();
631 } else if (isBuiltIn(sql, "@columns")) {
632 String[] p = split(sql);
633 return meta.getColumns(p[1], p[2], p[3], p[4]);
634 } else if (isBuiltIn(sql, "@column_privileges")) {
635 String[] p = split(sql);
636 return meta.getColumnPrivileges(p[1], p[2], p[3], p[4]);
637 } else if (isBuiltIn(sql, "@cross_references")) {
638 String[] p = split(sql);
639 return meta.getCrossReference(p[1], p[2], p[3], p[4], p[5], p[6]);
640 } else if (isBuiltIn(sql, "@exported_keys")) {
641 String[] p = split(sql);
642 return meta.getExportedKeys(p[1], p[2], p[3]);
643 } else if (isBuiltIn(sql, "@imported_keys")) {
644 String[] p = split(sql);
645 return meta.getImportedKeys(p[1], p[2], p[3]);
646 } else if (isBuiltIn(sql, "@index_info")) {
647 String[] p = split(sql);
648 boolean unique = Boolean.parseBoolean(p[4]);
649 boolean approx = Boolean.parseBoolean(p[5]);
650 return meta.getIndexInfo(p[1], p[2], p[3], unique, approx);
651 } else if (isBuiltIn(sql, "@primary_keys")) {
652 String[] p = split(sql);
653 return meta.getPrimaryKeys(p[1], p[2], p[3]);
654 } else if (isBuiltIn(sql, "@procedures")) {
655 String[] p = split(sql);
656 return meta.getProcedures(p[1], p[2], p[3]);
657 } else if (isBuiltIn(sql, "@procedure_columns")) {
658 String[] p = split(sql);
659 return meta.getProcedureColumns(p[1], p[2], p[3], p[4]);
660 } else if (isBuiltIn(sql, "@schemas")) {
661 return meta.getSchemas();
662 } else if (isBuiltIn(sql, "@tables")) {
663 String[] p = split(sql);
664 String[] types = p[4] == null ? null : StringUtils.arraySplit(p[4], ',', false);
665 return meta.getTables(p[1], p[2], p[3], types);
666 } else if (isBuiltIn(sql, "@table_privileges")) {
667 String[] p = split(sql);
668 return meta.getTablePrivileges(p[1], p[2], p[3]);
669 } else if (isBuiltIn(sql, "@table_types")) {
670 return meta.getTableTypes();
671 } else if (isBuiltIn(sql, "@type_info")) {
672 return meta.getTypeInfo();
673 } else if (isBuiltIn(sql, "@udts")) {
674 String[] p = split(sql);
675 int[] types;
676 if (p[4] == null) {
677 types = null;
678 } else {
679 String[] t = StringUtils.arraySplit(p[4], ',', false);
680 types = new int[t.length];
681 for (int i = 0; i < t.length; i++) {
682 types[i] = Integer.parseInt(t[i]);
683 }
684 }
685 return meta.getUDTs(p[1], p[2], p[3], types);
686 } else if (isBuiltIn(sql, "@version_columns")) {
687 String[] p = split(sql);
688 return meta.getVersionColumns(p[1], p[2], p[3]);
689 } else if (isBuiltIn(sql, "@memory")) {
690 SimpleResultSet rs = new SimpleResultSet();
691 rs.addColumn("Type", Types.VARCHAR, 0, 0);
692 rs.addColumn("KB", Types.VARCHAR, 0, 0);
693 rs.addRow("Used Memory", Long.toString(Utils.getMemoryUsed()));
694 rs.addRow("Free Memory", Long.toString(Utils.getMemoryFree()));
695 return rs;
696 } else if (isBuiltIn(sql, "@info")) {
697 SimpleResultSet rs = new SimpleResultSet();
698 rs.addColumn("KEY", Types.VARCHAR, 0, 0);
699 rs.addColumn("VALUE", Types.VARCHAR, 0, 0);
700 rs.addRow("conn.getCatalog", conn.getCatalog());
701 rs.addRow("conn.getAutoCommit", Boolean.toString(conn.getAutoCommit()));
702 rs.addRow("conn.getTransactionIsolation", Integer.toString(conn.getTransactionIsolation()));
703 rs.addRow("conn.getWarnings", String.valueOf(conn.getWarnings()));
704 String map;
705 try {
706 map = String.valueOf(conn.getTypeMap());
707 } catch (SQLException e) {
708 map = e.toString();
709 }
710 rs.addRow("conn.getTypeMap", map);
711 rs.addRow("conn.isReadOnly", Boolean.toString(conn.isReadOnly()));
712 rs.addRow("conn.getHoldability", Integer.toString(conn.getHoldability()));
713 addDatabaseMetaData(rs, meta);
714 return rs;
715 } else if (isBuiltIn(sql, "@attributes")) {
716 String[] p = split(sql);
717 return meta.getAttributes(p[1], p[2], p[3], p[4]);
718 } else if (isBuiltIn(sql, "@super_tables")) {
719 String[] p = split(sql);
720 return meta.getSuperTables(p[1], p[2], p[3]);
721 } else if (isBuiltIn(sql, "@super_types")) {
722 String[] p = split(sql);
723 return meta.getSuperTypes(p[1], p[2], p[3]);
724 } else if (isBuiltIn(sql, "@pseudo_columns")) {
725 String[] p = split(sql);
726 return meta.getPseudoColumns(p[1], p[2], p[3], p[4]);
727 }
728 return null;
729 }
730
731 private static void addDatabaseMetaData(SimpleResultSet rs,
732 DatabaseMetaData meta) {
733 Method[] methods = DatabaseMetaData.class.getDeclaredMethods();
734 Arrays.sort(methods, Comparator.comparing(Method::toString));
735 for (Method m : methods) {
736 if (m.getParameterTypes().length == 0) {
737 try {
738 Object o = m.invoke(meta);
739 rs.addRow("meta." + m.getName(), String.valueOf(o));
740 } catch (InvocationTargetException e) {
741 rs.addRow("meta." + m.getName(), e.getTargetException().toString());
742 } catch (Exception e) {
743 rs.addRow("meta." + m.getName(), e.toString());
744 }
745 }
746 }
747 }
748
749 /**
750 * Check is the SQL string starts with a prefix (case insensitive).
751 *
752 * @param sql the SQL statement
753 * @param builtIn the prefix
754 * @return true if yes
755 */
756 public static boolean isBuiltIn(String sql, String builtIn) {
757 return sql.regionMatches(true, 0, builtIn, 0, builtIn.length());
758 }
759
760 /**
761 * Split the string using the space separator into at least 10 entries.
762 *
763 * @param s the string
764 * @return the array
765 */
766 public static String[] split(String s) {
767 String[] t = StringUtils.arraySplit(s, ' ', true);
768 String[] list = new String[Math.max(10, t.length)];
769 System.arraycopy(t, 0, list, 0, t.length);
770 for (int i = 0; i < list.length; i++) {
771 if ("null".equals(list[i])) {
772 list[i] = null;
773 }
774 }
775 return list;
776 }
777 }