comparison src/main/java/nl/cwi/monetdb/jdbc/MonetDriver.java.in @ 0:a5a898f6886c

Copy of MonetDB java directory changeset e6e32756ad31.
author Sjoerd Mullender <sjoerd@acm.org>
date Wed, 21 Sep 2016 09:34:48 +0200 (2016-09-21)
parents
children a27ee2cb14a0
comparison
equal deleted inserted replaced
-1:000000000000 0:a5a898f6886c
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 - 2016 MonetDB B.V.
7 */
8
9 package nl.cwi.monetdb.jdbc;
10
11 import java.net.URI;
12 import java.net.URISyntaxException;
13 import java.sql.Connection;
14 import java.sql.Driver;
15 import java.sql.DriverManager;
16 import java.sql.DriverPropertyInfo;
17 import java.sql.SQLException;
18 import java.sql.SQLFeatureNotSupportedException;
19 import java.sql.Types;
20 import java.util.ArrayList;
21 import java.util.List;
22 import java.util.Map.Entry;
23 import java.util.Properties;
24 import java.util.logging.Logger;
25
26 /**
27 * A Driver suitable for the MonetDB database.
28 *
29 * This driver will be used by the DriverManager to determine if an URL
30 * is to be handled by this driver, and if it does, then this driver
31 * will supply a Connection suitable for MonetDB.
32 *
33 * This class has no explicit constructor, the default constructor
34 * generated by the Java compiler will be sufficient since nothing has
35 * to be set in order to use this driver.
36 *
37 * This Driver supports MonetDB database URLs. MonetDB URLs are defined
38 * as:
39 * <tt>jdbc:monetdb://&lt;host&gt;[:&lt;port&gt;]/&lt;database&gt;</tt>
40 * where [:&lt;port&gt;] denotes that a port is optional. If not
41 * given the default (@JDBC_DEF_PORT@) will be used.
42 *
43 * @author Fabian Groffen
44 * @version @JDBC_MAJOR@.@JDBC_MINOR@ (@JDBC_VER_SUFFIX@)
45 */
46 final public class MonetDriver implements Driver {
47 // the url kind will be jdbc:monetdb://<host>[:<port>]/<database>
48 // Chapter 9.2.1 from Sun JDBC 3.0 specification
49 /** The prefix of a MonetDB url */
50 private static final String MONETURL = "jdbc:monetdb://";
51 /** Major version of this driver */
52 private static final int DRIVERMAJOR = @JDBC_MAJOR@;
53 /** Minor version of this driver */
54 private static final int DRIVERMINOR = @JDBC_MINOR@;
55 /** Version suffix string */
56 private static final String DRIVERVERSIONSUFFIX =
57 "@JDBC_VER_SUFFIX@ based on MCL v@MCL_MAJOR@.@MCL_MINOR@";
58 // We're not fully compliant, but what we support is compliant
59 /** Whether this driver is JDBC compliant or not */
60 private static final boolean MONETJDBCCOMPLIANT = false;
61
62 /** MonetDB default port to connect to */
63 private static final String PORT = "@JDBC_DEF_PORT@";
64
65
66 // initialize this class: register it at the DriverManager
67 // Chapter 9.2 from Sun JDBC 3.0 specification
68 static {
69 try {
70 DriverManager.registerDriver(new MonetDriver());
71 } catch (SQLException e) {
72 e.printStackTrace();
73 }
74 }
75
76 //== methods of interface Driver
77
78 /**
79 * Retrieves whether the driver thinks that it can open a connection to the
80 * given URL. Typically drivers will return true if they understand the
81 * subprotocol specified in the URL and false if they do not.
82 *
83 * @param url the URL of the database
84 * @return true if this driver understands the given URL; false otherwise
85 */
86 public boolean acceptsURL(String url) {
87 return url != null && url.startsWith(MONETURL);
88 }
89
90 /**
91 * Attempts to make a database connection to the given URL. The driver
92 * should return "null" if it realizes it is the wrong kind of driver to
93 * connect to the given URL. This will be common, as when the JDBC driver
94 * manager is asked to connect to a given URL it passes the URL to each
95 * loaded driver in turn.
96 *
97 * The driver should throw an SQLException if it is the right driver to
98 * connect to the given URL but has trouble connecting to the database.
99 *
100 * The java.util.Properties argument can be used to pass arbitrary string
101 * tag/value pairs as connection arguments. Normally at least "user" and
102 * "password" properties should be included in the Properties object.
103 *
104 * @param url the URL of the database to which to connect
105 * @param info a list of arbitrary string tag/value pairs as connection
106 * arguments. Normally at least a "user" and "password" property
107 * should be included
108 * @return a Connection object that represents a connection to the URL
109 * @throws SQLException if a database access error occurs
110 */
111 public Connection connect(String url, Properties info)
112 throws SQLException
113 {
114 int tmp;
115 Properties props = new Properties();
116 // set the optional properties and their defaults here
117 props.put("port", PORT);
118 props.put("debug", "false");
119 props.put("language", "sql"); // mal, sql, <future>
120 props.put("so_timeout", "0");
121
122 props.putAll(info);
123 info = props;
124
125 // url should be of style jdbc:monetdb://<host>/<database>
126 if (!acceptsURL(url))
127 throw new SQLException("Invalid URL: it does not start with: " + MONETURL, "08M26");
128
129 // remove leading "jdbc:" so the rest is a valid hierarchical URI
130 URI uri;
131 try {
132 uri = new URI(url.substring(5));
133 } catch (URISyntaxException e) {
134 throw new SQLException(e.toString(), "08M26");
135 }
136
137 String uri_host = uri.getHost();
138 if (uri_host == null)
139 throw new SQLException("Invalid URL: no hostname given or unparsable in '" + url + "'", "08M26");
140 info.put("host", uri_host);
141
142 int uri_port = uri.getPort();
143 if (uri_port > 0)
144 info.put("port", "" + uri_port);
145
146 // check the database
147 String uri_path = uri.getPath();
148 if (uri_path != null && uri_path.length() != 0) {
149 uri_path = uri_path.substring(1);
150 if (!uri_path.trim().equals(""))
151 info.put("database", uri_path);
152 }
153
154 String uri_query = uri.getQuery();
155 if (uri_query != null) {
156 // handle additional arguments
157 String args[] = uri_query.split("&");
158 for (int i = 0; i < args.length; i++) {
159 tmp = args[i].indexOf("=");
160 if (tmp > 0)
161 info.put(args[i].substring(0, tmp), args[i].substring(tmp + 1));
162 }
163 }
164
165 // finally return the Connection as requested
166 return new MonetConnection(info);
167 }
168
169 /**
170 * Retrieves the driver's major version number. Initially this should be 1.
171 *
172 * @return this driver's major version number
173 */
174 public int getMajorVersion() {
175 return DRIVERMAJOR;
176 }
177
178 /**
179 * Gets the driver's minor version number. Initially this should be 0.
180 *
181 * @return this driver's minor version number
182 */
183 public int getMinorVersion() {
184 return DRIVERMINOR;
185 }
186
187 /**
188 * Gets information about the possible properties for this driver.
189 *
190 * The getPropertyInfo method is intended to allow a generic GUI tool to
191 * discover what properties it should prompt a human for in order to get
192 * enough information to connect to a database. Note that depending on the
193 * values the human has supplied so far, additional values may become
194 * necessary, so it may be necessary to iterate though several calls to the
195 * getPropertyInfo method.
196 *
197 * @param url the URL of the database to which to connect
198 * @param info a proposed list of tag/value pairs that will be sent on
199 * connect open
200 * @return an array of DriverPropertyInfo objects describing possible
201 * properties. This array may be an empty array if no properties
202 * are required.
203 */
204 public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) {
205 if (!acceptsURL(url))
206 return null;
207
208 List<DriverPropertyInfo> props = new ArrayList<DriverPropertyInfo>();
209
210 DriverPropertyInfo prop = new DriverPropertyInfo("user", info.getProperty("user"));
211 prop.required = true;
212 prop.description = "The user loginname to use when authenticating on the database server";
213 props.add(prop);
214
215 prop = new DriverPropertyInfo("password", info.getProperty("password"));
216 prop.required = true;
217 prop.description = "The password to use when authenticating on the database server";
218 props.add(prop);
219
220 prop = new DriverPropertyInfo("debug", "false");
221 prop.required = false;
222 prop.description = "Whether or not to create a log file for debugging purposes";
223 props.add(prop);
224
225 prop = new DriverPropertyInfo("logfile", "");
226 prop.required = false;
227 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.";
228 props.add(prop);
229
230 prop = new DriverPropertyInfo("language", "sql");
231 prop.required = false;
232 prop.description = "What language to use for MonetDB conversations (experts only)";
233 props.add(prop);
234
235 prop = new DriverPropertyInfo("hash", "");
236 prop.required = false;
237 prop.description = "Force the use of the given hash algorithm during challenge response (one of SHA1, MD5, plain)";
238 props.add(prop);
239
240 prop = new DriverPropertyInfo("follow_redirects", "true");
241 prop.required = false;
242 prop.description = "Whether redirects issued by the server should be followed";
243 props.add(prop);
244
245 prop = new DriverPropertyInfo("treat_blob_as_binary", "false");
246 prop.required = false;
247 prop.description = "Whether BLOBs on the server should be treated as BINARY types, thus mapped to byte[]";
248 props.add(prop);
249
250 prop = new DriverPropertyInfo("so_timeout", "0");
251 prop.required = false;
252 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
253 props.add(prop);
254
255 DriverPropertyInfo[] dpi = new DriverPropertyInfo[props.size()];
256 return props.toArray(dpi);
257 }
258
259 /**
260 * Reports whether this driver is a genuine JDBC Compliant&tm; 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 public boolean jdbcCompliant() {
278 return MONETJDBCCOMPLIANT;
279 }
280
281 //== end methods of interface driver
282
283
284 /** A static Map containing the mapping between MonetDB types and Java SQL types */
285 /* use SELECT sqlname, * FROM sys.types order by 1, id; to view all MonetDB types */
286 /* see http://docs.oracle.com/javase/7/docs/api/java/sql/Types.html to view all supported java SQL types */
287 private static java.util.Map<String, Integer> typeMap = new java.util.HashMap<String, Integer>();
288 static {
289 // fill the typeMap once
290 // typeMap.put("any", Integer.valueOf(Types.???));
291 typeMap.put("bigint", Integer.valueOf(Types.BIGINT));
292 typeMap.put("blob", Integer.valueOf(Types.BLOB));
293 typeMap.put("boolean", Integer.valueOf(Types.BOOLEAN));
294 typeMap.put("char", Integer.valueOf(Types.CHAR));
295 typeMap.put("clob", Integer.valueOf(Types.CLOB));
296 typeMap.put("date", Integer.valueOf(Types.DATE));
297 typeMap.put("decimal", Integer.valueOf(Types.DECIMAL));
298 typeMap.put("double", Integer.valueOf(Types.DOUBLE));
299 // typeMap.put("geometry", Integer.valueOf(Types.???));
300 // typeMap.put("geometrya", Integer.valueOf(Types.???));
301 typeMap.put("hugeint", Integer.valueOf(Types.NUMERIC));
302 typeMap.put("inet", Integer.valueOf(Types.VARCHAR));
303 typeMap.put("int", Integer.valueOf(Types.INTEGER));
304 typeMap.put("json", Integer.valueOf(Types.VARCHAR));
305 // typeMap.put("mbr", Integer.valueOf(Types.???));
306 typeMap.put("month_interval", Integer.valueOf(Types.INTEGER));
307 typeMap.put("oid", Integer.valueOf(Types.BIGINT));
308 // typeMap.put("ptr", Integer.valueOf(Types.???));
309 typeMap.put("real", Integer.valueOf(Types.REAL));
310 typeMap.put("sec_interval", Integer.valueOf(Types.DECIMAL));
311 typeMap.put("smallint", Integer.valueOf(Types.SMALLINT));
312 // typeMap.put("table", Integer.valueOf(Types.???));
313 typeMap.put("time", Integer.valueOf(Types.TIME));
314 typeMap.put("timestamp", Integer.valueOf(Types.TIMESTAMP));
315 typeMap.put("timestamptz", Integer.valueOf(Types.TIMESTAMP));
316 // new in Java 8: Types.TIMESTAMP_WITH_TIMEZONE (value 2014). Can't use it yet as we compile for java 7
317 typeMap.put("timetz", Integer.valueOf(Types.TIME));
318 // new in Java 8: Types.TIME_WITH_TIMEZONE (value 2013). Can't use it yet as we compile for java 7
319 typeMap.put("tinyint", Integer.valueOf(Types.TINYINT));
320 typeMap.put("url", Integer.valueOf(Types.VARCHAR));
321 typeMap.put("uuid", Integer.valueOf(Types.VARCHAR));
322 typeMap.put("varchar", Integer.valueOf(Types.VARCHAR));
323 typeMap.put("wrd", Integer.valueOf(Types.BIGINT));
324 }
325
326 /**
327 * Returns the java.sql.Types equivalent of the given MonetDB type.
328 *
329 * @param type the type as used by MonetDB
330 * @return the mathing java.sql.Types constant or java.sql.Types.OTHER if
331 * nothing matched on the given string
332 */
333 static int getJavaType(String type) {
334 // match the column type on a java.sql.Types constant
335 Integer tp = typeMap.get(type);
336 if (tp != null) {
337 return tp.intValue();
338 } else {
339 // this should not be able to happen
340 // do not assert, since maybe future versions introduce
341 // new types
342 return Types.OTHER;
343 }
344 }
345
346 /**
347 * Returns a String usable in an SQL statement to map the server types
348 * to values of java.sql.Types using the global static type map.
349 * The returned string will be a SQL CASE x statement where the x is
350 * replaced with the given column name (or expression) string.
351 *
352 * @param column a String representing the value that should be evaluated
353 * in the SQL CASE statement
354 * @return a SQL CASE statement
355 */
356 private static String TypeMapppingSQL = null; // cache to optimise getSQLTypeMap()
357 static String getSQLTypeMap(String column) {
358 if (TypeMapppingSQL == null) {
359 // first time, compose TypeMappping SQL string
360 StringBuilder val = new StringBuilder((typeMap.size() * (7 + 7 + 7 + 4)) + 14);
361 for (Entry<String, Integer> entry : typeMap.entrySet()) {
362 val.append(" WHEN '").append(entry.getKey()).append("' THEN ").append(entry.getValue().toString());
363 }
364 val.append(" ELSE ").append(Types.OTHER).append(" END");
365 // as the typeMap is static, cache this SQL part for all next calls
366 TypeMapppingSQL = val.toString();
367 }
368 return "CASE " + column + TypeMapppingSQL;
369 }
370
371 /**
372 * Returns a touched up identifying version string of this driver.
373 *
374 * @return the version string
375 */
376 public static String getDriverVersion() {
377 return "" + DRIVERMAJOR + "." + DRIVERMINOR + " (" + DRIVERVERSIONSUFFIX + ")";
378 }
379
380 public static int getDriverMajorVersion() {
381 return DRIVERMAJOR;
382 }
383
384 public static int getDriverMinorVersion() {
385 return DRIVERMINOR;
386 }
387
388 /**
389 * Return the parent Logger of all the Loggers used by this data
390 * source. This should be the Logger farthest from the root Logger
391 * that is still an ancestor of all of the Loggers used by this data
392 * source. Configuring this Logger will affect all of the log
393 * messages generated by the data source. In the worst case, this
394 * may be the root Logger.
395 *
396 * @return the parent Logger for this data source
397 * @throws SQLFeatureNotSupportedException if the data source does
398 * not use java.util.logging
399 */
400 public Logger getParentLogger() throws SQLFeatureNotSupportedException {
401 throw new SQLFeatureNotSupportedException("java.util.logging not in use", "0A000");
402 }
403 }