comparison src/main/java/org/monetdb/jdbc/MonetDriver.java.in @ 391:f523727db392

Moved Java classes from packages starting with nl.cwi.monetdb.* to package org.monetdb.* This naming complies to the Java Package Naming convention as MonetDB's main website is www.monetdb.org.
author Martin van Dinther <martin.van.dinther@monetdbsolutions.com>
date Thu, 12 Nov 2020 22:02:01 +0100 (2020-11-12)
parents src/main/java/nl/cwi/monetdb/jdbc/MonetDriver.java.in@11c30e3b7966
children bf9f6b6ecf40
comparison
equal deleted inserted replaced
390:6199e0be3c6e 391:f523727db392
1 /*
2 * This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 *
6 * Copyright 1997 - July 2008 CWI, August 2008 - 2020 MonetDB B.V.
7 */
8
9 package org.monetdb.jdbc;
10
11 import java.net.URI;
12 import java.sql.Connection;
13 import java.sql.Driver;
14 import java.sql.DriverManager;
15 import java.sql.DriverPropertyInfo;
16 import java.sql.SQLException;
17 import java.sql.SQLFeatureNotSupportedException;
18 import java.sql.Types;
19 import java.util.Map.Entry;
20 import java.util.Properties;
21
22 /**
23 * A JDBC Driver suitable for the MonetDB RDBMS.
24 *
25 * This driver will be used by the DriverManager to determine if an URL
26 * is to be handled by this driver, and if it does, then this driver
27 * will supply a Connection suitable for MonetDB.
28 *
29 * This class has no explicit constructor, the default constructor
30 * generated by the Java compiler will be sufficient since nothing has
31 * to be set in order to use this driver.
32 *
33 * This Driver supports MonetDB database URLs. MonetDB URLs are defined as:
34 * <tt>jdbc:monetdb://&lt;host&gt;[:&lt;port&gt;]/&lt;database&gt;</tt>
35 * where [:&lt;port&gt;] denotes that a port is optional. If not
36 * given the default (@JDBC_DEF_PORT@) will be used.
37 *
38 * @author Fabian Groffen
39 * @version @JDBC_MAJOR@.@JDBC_MINOR@ (@JDBC_VER_SUFFIX@) based on MCL v@MCL_MAJOR@.@MCL_MINOR@"
40 */
41 public class MonetDriver implements Driver { /* cannot (yet) be final as nl.cwi.monetdb.jdbc.MonetDriver extends this class */
42 // the url kind will be jdbc:monetdb://<host>[:<port>]/<database>
43 // Chapter 9.2.1 from Sun JDBC 3.0 specification
44 /** The prefix of a MonetDB url */
45 static final String MONETURL = "jdbc:monetdb://";
46
47 // initialize this class: register it at the DriverManager
48 // Chapter 9.2 from Sun JDBC 3.0 specification
49 static {
50 try {
51 DriverManager.registerDriver(new MonetDriver());
52 } catch (SQLException e) {
53 e.printStackTrace();
54 }
55 }
56
57 //== methods of interface Driver
58
59 /**
60 * Retrieves whether the driver thinks that it can open a connection to the
61 * given URL. Typically drivers will return true if they understand the
62 * subprotocol specified in the URL and false if they do not.
63 *
64 * @param url the URL of the database
65 * @return true if this driver understands the given URL; false otherwise
66 */
67 @Override
68 public boolean acceptsURL(final String url) {
69 return url != null && url.startsWith(MONETURL);
70 }
71
72 /**
73 * Attempts to make a database connection to the given URL. The driver
74 * should return "null" if it realizes it is the wrong kind of driver to
75 * connect to the given URL. This will be common, as when the JDBC driver
76 * manager is asked to connect to a given URL it passes the URL to each
77 * loaded driver in turn.
78 *
79 * The driver should throw an SQLException if it is the right driver to
80 * connect to the given URL but has trouble connecting to the database.
81 *
82 * The java.util.Properties argument can be used to pass arbitrary string
83 * tag/value pairs as connection arguments. Normally at least "user" and
84 * "password" properties should be included in the Properties object.
85 *
86 * @param url the URL of the database to which to connect
87 * @param info a list of arbitrary string tag/value pairs as connection
88 * arguments. Normally at least a "user" and "password" property
89 * should be included
90 * @return a Connection object that represents a connection to the URL
91 * @throws SQLException if a database access error occurs
92 */
93 @Override
94 public Connection connect(final String url, Properties info)
95 throws SQLException
96 {
97 // url should be of style jdbc:monetdb://<host>/<database>
98 if (!acceptsURL(url))
99 return null;
100
101 final Properties props = new Properties();
102 // set the optional properties and their defaults here
103 props.put("port", "@JDBC_DEF_PORT@");
104 props.put("debug", "false");
105 props.put("language", "sql"); // mal, sql, <future>
106 props.put("so_timeout", "0");
107
108 if (info != null)
109 props.putAll(info);
110 info = props;
111
112 // remove leading "jdbc:" so the rest is a valid hierarchical URI
113 final URI uri;
114 try {
115 uri = new URI(url.substring(5));
116 } catch (java.net.URISyntaxException e) {
117 return null;
118 }
119
120 final String uri_host = uri.getHost();
121 if (uri_host == null)
122 return null;
123 info.put("host", uri_host);
124
125 int uri_port = uri.getPort();
126 if (uri_port > 0)
127 info.put("port", Integer.toString(uri_port));
128
129 // check the database
130 String uri_path = uri.getPath();
131 if (uri_path != null && !uri_path.isEmpty()) {
132 uri_path = uri_path.substring(1).trim();
133 if (!uri_path.isEmpty())
134 info.put("database", uri_path);
135 }
136
137 final String uri_query = uri.getQuery();
138 if (uri_query != null) {
139 int pos;
140 // handle additional connection properties separated by the & character
141 final String args[] = uri_query.split("&");
142 for (int i = 0; i < args.length; i++) {
143 pos = args[i].indexOf('=');
144 if (pos > 0)
145 info.put(args[i].substring(0, pos), args[i].substring(pos + 1));
146 }
147 }
148
149 // finally return the Connection object as requested
150 return new MonetConnection(info);
151 }
152
153 /**
154 * Retrieves the driver's major version number. Initially this should be 1.
155 *
156 * @return this driver's major version number
157 */
158 @Override
159 public int getMajorVersion() {
160 return @JDBC_MAJOR@;
161 }
162
163 /**
164 * Gets the driver's minor version number. Initially this should be 0.
165 *
166 * @return this driver's minor version number
167 */
168 @Override
169 public int getMinorVersion() {
170 return @JDBC_MINOR@;
171 }
172
173 /**
174 * Gets information about the possible properties for this driver.
175 *
176 * The getPropertyInfo method is intended to allow a generic GUI tool to
177 * discover what properties it should prompt a human for in order to get
178 * enough information to connect to a database. Note that depending on the
179 * values the human has supplied so far, additional values may become
180 * necessary, so it may be necessary to iterate though several calls to the
181 * getPropertyInfo method.
182 *
183 * @param url the URL of the database to which to connect
184 * @param info a proposed list of tag/value pairs that will be sent on
185 * connect open
186 * @return an array of DriverPropertyInfo objects describing possible
187 * properties. This array may be an empty array if no properties
188 * are required.
189 */
190 @Override
191 public DriverPropertyInfo[] getPropertyInfo(final String url, final Properties info) {
192 if (!acceptsURL(url))
193 return null;
194
195 final String[] boolean_choices = new String[] { "true", "false" };
196 final DriverPropertyInfo[] dpi = new DriverPropertyInfo[9]; // we currently support 9 connection properties
197
198 DriverPropertyInfo prop = new DriverPropertyInfo("user", info != null ? info.getProperty("user") : null);
199 prop.required = true;
200 prop.description = "The user loginname to use when authenticating on the database server";
201 dpi[0] = prop;
202
203 prop = new DriverPropertyInfo("password", info != null ? info.getProperty("password") : null);
204 prop.required = true;
205 prop.description = "The password to use when authenticating on the database server";
206 dpi[1] = prop;
207
208 prop = new DriverPropertyInfo("debug", "false");
209 prop.required = false;
210 prop.description = "Whether or not to create a log file for debugging purposes";
211 prop.choices = boolean_choices;
212 dpi[2] = prop;
213
214 prop = new DriverPropertyInfo("logfile", null);
215 prop.required = false;
216 prop.description = "The filename to write the debug log to. Only takes effect if debug is set to true. If the file exists, an incrementing number is added, till the filename is unique.";
217 dpi[3] = prop;
218
219 prop = new DriverPropertyInfo("language", "sql");
220 prop.required = false;
221 prop.description = "What language to use for MonetDB conversations (experts only)";
222 prop.choices = new String[] { "sql", "mal" };
223 dpi[4] = prop;
224
225 prop = new DriverPropertyInfo("hash", null);
226 prop.required = false;
227 prop.description = "Force the use of the given hash algorithm (SHA512 or SHA384 or SHA256 or SHA1) during challenge response";
228 prop.choices = new String[] { "SHA512", "SHA384", "SHA256", "SHA1" };
229 dpi[5] = prop;
230
231 prop = new DriverPropertyInfo("treat_blob_as_binary", "true");
232 prop.required = false;
233 prop.description = "Should blob columns be mapped to Types.VARBINARY instead of Types.BLOB in ResultSets and PreparedStatements"; // recommend for increased performance due to less overhead
234 prop.choices = boolean_choices;
235 dpi[6] = prop;
236
237 prop = new DriverPropertyInfo("treat_clob_as_varchar", "true");
238 prop.required = false;
239 prop.description = "Should clob columns be mapped to Types.VARCHAR instead of Types.CLOB in ResultSets and PreparedStatements"; // recommend for increased performance due to less overhead
240 prop.choices = boolean_choices;
241 dpi[7] = prop;
242
243 prop = new DriverPropertyInfo("so_timeout", "0");
244 prop.required = false;
245 prop.description = "Defines the maximum time to wait in milliseconds on a blocking read socket call"; // this corresponds to the Connection.setNetworkTimeout() method introduced in JDBC 4.1
246 dpi[8] = prop;
247
248 /* next property is no longer supported in: new MonetConnection(props)
249 prop = new DriverPropertyInfo("follow_redirects", "true");
250 prop.required = false;
251 prop.description = "Whether redirects issued by the server should be followed";
252 prop.choices = boolean_choices;
253 dpi[9] = prop;
254 */
255
256 return dpi;
257 }
258
259 /**
260 * Reports whether this driver is a genuine JDBC Compliant&trade; driver. A
261 * driver may only report true here if it passes the JDBC compliance tests;
262 * otherwise it is required to return false.
263 *
264 * JDBC compliance requires full support for the JDBC API and full support
265 * for SQL 92 Entry Level. It is expected that JDBC compliant drivers will
266 * be available for all the major commercial databases.
267 *
268 * This method is not intended to encourage the development of non-JDBC
269 * compliant drivers, but is a recognition of the fact that some vendors are
270 * interested in using the JDBC API and framework for lightweight databases
271 * that do not support full database functionality, or for special databases
272 * such as document information retrieval where a SQL implementation may not
273 * be feasible.
274 *
275 * @return true if this driver is JDBC Compliant; false otherwise
276 */
277 @Override
278 public boolean jdbcCompliant() {
279 // We're not fully JDBC compliant, but what we support is compliant
280 return false;
281 }
282
283 /**
284 * Return the parent Logger of all the Loggers used by this data source.
285 * This should be the Logger farthest from the root Logger that is
286 * still an ancestor of all of the Loggers used by this data source.
287 * Configuring this Logger will affect all of the log messages
288 * generated by the data source.
289 * In the worst case, this may be the root Logger.
290 *
291 * @return the parent Logger for this data source
292 * @throws SQLFeatureNotSupportedException if the data source does
293 * not use java.util.logging
294 * @since 1.7
295 */
296 @Override
297 public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {
298 throw MonetWrapper.newSQLFeatureNotSupportedException("getParentLogger");
299 }
300
301 //== end methods of interface driver
302
303
304 /**
305 * utility methods called by MonetDatabaseMetaData methods
306 */
307 static final int getDriverMajorVersion() {
308 return @JDBC_MAJOR@;
309 }
310
311 static final int getDriverMinorVersion() {
312 return @JDBC_MINOR@;
313 }
314
315 /**
316 * Returns a touched up identifying version string of this driver.
317 * It is made public as it is called from org/monetdb/client/JdbcClient.java
318 * @return the version string
319 */
320 public static final String getDriverVersion() {
321 return "@JDBC_MAJOR@.@JDBC_MINOR@ (@JDBC_VER_SUFFIX@ based on MCL v@MCL_MAJOR@.@MCL_MINOR@)";
322 }
323
324 /** A static Map containing the mapping between MonetDB types and Java SQL types */
325 /* use SELECT sqlname, * FROM sys.types order by 1, id; to view all MonetDB types */
326 /* see http://docs.oracle.com/javase/8/docs/api/java/sql/Types.html to view all supported java SQL types */
327 private static final java.util.Map<String, Integer> typeMap = new java.util.HashMap<String, Integer>();
328 static {
329 // fill the typeMap once
330 // typeMap.put("any", Integer.valueOf(Types.???));
331 typeMap.put("bigint", Integer.valueOf(Types.BIGINT));
332 typeMap.put("blob", Integer.valueOf(Types.BLOB));
333 typeMap.put("boolean", Integer.valueOf(Types.BOOLEAN));
334 typeMap.put("char", Integer.valueOf(Types.CHAR));
335 typeMap.put("clob", Integer.valueOf(Types.CLOB));
336 typeMap.put("date", Integer.valueOf(Types.DATE));
337 typeMap.put("day_interval", Integer.valueOf(Types.BIGINT)); // New as of Oct2020 release
338 typeMap.put("decimal", Integer.valueOf(Types.DECIMAL));
339 typeMap.put("double", Integer.valueOf(Types.DOUBLE));
340 // typeMap.put("geometry", Integer.valueOf(Types.???));
341 // typeMap.put("geometrya", Integer.valueOf(Types.???));
342 typeMap.put("hugeint", Integer.valueOf(Types.NUMERIC));
343 typeMap.put("inet", Integer.valueOf(Types.VARCHAR));
344 typeMap.put("int", Integer.valueOf(Types.INTEGER));
345 typeMap.put("json", Integer.valueOf(Types.VARCHAR));
346 // typeMap.put("mbr", Integer.valueOf(Types.???));
347 typeMap.put("month_interval", Integer.valueOf(Types.INTEGER));
348 typeMap.put("oid", Integer.valueOf(Types.BIGINT));
349 // typeMap.put("ptr", Integer.valueOf(Types.???));
350 typeMap.put("real", Integer.valueOf(Types.REAL));
351 typeMap.put("sec_interval", Integer.valueOf(Types.DECIMAL));
352 typeMap.put("smallint", Integer.valueOf(Types.SMALLINT));
353 typeMap.put("str", Integer.valueOf(Types.VARCHAR)); // MonetDB prepare <stmt> uses type 'str' (instead of varchar) for the schema, table and column metadata output
354 // typeMap.put("table", Integer.valueOf(Types.???));
355 typeMap.put("time", Integer.valueOf(Types.TIME));
356 typeMap.put("timestamp", Integer.valueOf(Types.TIMESTAMP));
357 typeMap.put("timestamptz", Integer.valueOf(Types.TIMESTAMP_WITH_TIMEZONE)); // new in Java 8: Types.TIMESTAMP_WITH_TIMEZONE (value 2014)
358 typeMap.put("timetz", Integer.valueOf(Types.TIME_WITH_TIMEZONE)); // new in Java 8: Types.TIME_WITH_TIMEZONE (value 2013)
359 typeMap.put("tinyint", Integer.valueOf(Types.TINYINT));
360 typeMap.put("url", Integer.valueOf(Types.VARCHAR));
361 typeMap.put("uuid", Integer.valueOf(Types.VARCHAR));
362 typeMap.put("varchar", Integer.valueOf(Types.VARCHAR));
363 typeMap.put("wrd", Integer.valueOf(Types.BIGINT)); // keep it in for older MonetDB servers
364 }
365
366 /**
367 * Returns the java.sql.Types equivalent of the given MonetDB type name.
368 *
369 * @param type the SQL data type name as used by MonetDB
370 * @return the matching java.sql.Types constant or
371 * java.sql.Types.OTHER if nothing matched the given type name
372 */
373 static final int getJdbcSQLType(final String type) {
374 // find the column type name in the typeMap
375 final Integer tp = typeMap.get(type);
376 if (tp != null) {
377 return tp.intValue();
378 }
379 // When type name is not found in the map, for instance
380 // when it is a new type (not yet added in the above typeMap) or
381 // when type name is: any or geometry or geometrya or mbr or ptr or table.
382 return Types.OTHER;
383 }
384
385 /**
386 * Returns a String usable in an SQL statement to map the server types
387 * to values of java.sql.Types using the global static type map.
388 * The returned string will be a SQL CASE x statement where the x is
389 * replaced with the given column name (or expression) string.
390 *
391 * @param column a String representing the value that should be evaluated
392 * in the SQL CASE statement
393 * @return a SQL CASE statement
394 */
395 private static String TypeMapppingSQL = null; // cache to optimise getSQLTypeMap()
396 static final String getSQLTypeMap(final String column) {
397 if (TypeMapppingSQL == null) {
398 // first time, compose TypeMappping SQL string
399 final StringBuilder val = new StringBuilder((typeMap.size() * (7 + 7 + 7 + 4)) + 14);
400 for (Entry<String, Integer> entry : typeMap.entrySet()) {
401 val.append(" WHEN '").append(entry.getKey()).append("' THEN ").append(entry.getValue().toString());
402 }
403 val.append(" ELSE ").append(Types.OTHER).append(" END");
404 // as the typeMap is static, cache this SQL part for all next calls
405 TypeMapppingSQL = val.toString();
406 }
407 return "CASE " + column + TypeMapppingSQL;
408 }
409 }