Mercurial > hg > monetdb-java
changeset 85:073ee535234b embedded
Ok. Now everything compiles back with Ant again. Moved the Embedded stuff to the temporary MonetDBJavaLite repository before moving into the suggested MonetDBLite repository. The soon generated Embedded Connection jar will have a dependency on the regular JDBC driver jar. The JDBC driver jar is independent, however if attempted to create an Embedded Connection with will try to load the respective class from the class loader, failing if the Embedded Connection jar is not present. If anyone in the group has expertise on Java Class dynamic loading, please contact me because there might be issues on this. Removed the pom.xml file because the regular maven compilation fails.
author | Pedro Ferreira <pedro.ferreira@monetdbsolutions.com> |
---|---|
date | Fri, 30 Dec 2016 18:55:13 +0000 (2016-12-30) |
parents | d82bf33bf8a6 |
children | 3db0dd967677 |
files | build.xml example/PreparedExample.java example/SQLImport.java example/SQLcopyinto.java pom.xml src/main/java/nl/cwi/monetdb/client/JMonetDB.java src/main/java/nl/cwi/monetdb/client/JdbcClient.java src/main/java/nl/cwi/monetdb/embedded/env/AbstractConnectionResult.java src/main/java/nl/cwi/monetdb/embedded/env/JDBCEmbeddedConnection.java src/main/java/nl/cwi/monetdb/embedded/env/MonetDBEmbeddedConnection.java src/main/java/nl/cwi/monetdb/embedded/env/MonetDBEmbeddedDatabase.java src/main/java/nl/cwi/monetdb/embedded/env/MonetDBEmbeddedException.java src/main/java/nl/cwi/monetdb/embedded/mapping/AbstractColumn.java src/main/java/nl/cwi/monetdb/embedded/mapping/AbstractResultTable.java src/main/java/nl/cwi/monetdb/embedded/mapping/AbstractRowSet.java src/main/java/nl/cwi/monetdb/embedded/mapping/MonetDBRow.java src/main/java/nl/cwi/monetdb/embedded/mapping/MonetDBToJavaMapping.java src/main/java/nl/cwi/monetdb/embedded/resultset/AbstractQueryResultSetColumn.java src/main/java/nl/cwi/monetdb/embedded/resultset/QueryResultRowSet.java src/main/java/nl/cwi/monetdb/embedded/resultset/QueryResultSet.java src/main/java/nl/cwi/monetdb/embedded/resultset/QueryResultSetBooleanColumn.java src/main/java/nl/cwi/monetdb/embedded/resultset/QueryResultSetByteColumn.java src/main/java/nl/cwi/monetdb/embedded/resultset/QueryResultSetDoubleColumn.java src/main/java/nl/cwi/monetdb/embedded/resultset/QueryResultSetFloatColumn.java src/main/java/nl/cwi/monetdb/embedded/resultset/QueryResultSetIntColumn.java src/main/java/nl/cwi/monetdb/embedded/resultset/QueryResultSetLongColumn.java src/main/java/nl/cwi/monetdb/embedded/resultset/QueryResultSetObjectColumn.java src/main/java/nl/cwi/monetdb/embedded/resultset/QueryResultSetShortColumn.java src/main/java/nl/cwi/monetdb/embedded/resultset/UpdateResultSet.java src/main/java/nl/cwi/monetdb/embedded/tables/IMonetDBTableBaseIterator.java src/main/java/nl/cwi/monetdb/embedded/tables/IMonetDBTableCursor.java src/main/java/nl/cwi/monetdb/embedded/tables/MonetDBTable.java src/main/java/nl/cwi/monetdb/embedded/tables/MonetDBTableColumn.java src/main/java/nl/cwi/monetdb/embedded/tables/RowIterator.java src/main/java/nl/cwi/monetdb/embedded/utils/StringEscaper.java src/main/java/nl/cwi/monetdb/jdbc/MonetConnection.java src/main/java/nl/cwi/monetdb/jdbc/MonetDriver.java.in src/main/java/nl/cwi/monetdb/mcl/connection/MonetDBConnectionFactory.java src/main/java/nl/cwi/monetdb/mcl/connection/embedded/EmbeddedConnection.java src/main/java/nl/cwi/monetdb/mcl/connection/embedded/EmbeddedLanguage.java src/main/java/nl/cwi/monetdb/mcl/connection/helpers/Debugger.java src/main/java/nl/cwi/monetdb/mcl/connection/mapi/MapiConnection.java src/main/java/nl/cwi/monetdb/mcl/protocol/embedded/EmbeddedProtocol.java src/main/java/nl/cwi/monetdb/mcl/protocol/oldmapi/OldMapiProtocol.java src/main/java/nl/cwi/monetdb/merovingian/Control.java src/main/java/nl/cwi/monetdb/merovingian/SabaothDB.java src/main/java/nl/cwi/monetdb/util/CmdLineOpts.java src/main/java/nl/cwi/monetdb/util/Exporter.java src/main/java/nl/cwi/monetdb/util/SQLExporter.java src/main/java/nl/cwi/monetdb/util/SQLRestore.java src/main/java/nl/cwi/monetdb/util/XMLExporter.java |
diffstat | 51 files changed, 855 insertions(+), 4158 deletions(-) [+] |
line wrap: on
line diff
--- a/build.xml +++ b/build.xml @@ -31,7 +31,6 @@ Copyright 1997 - July 2008 CWI, August 2 <property name="util-package" value="nl/cwi/monetdb/util" /> <property name="mero-control-package" value="nl/cwi/monetdb/merovingian" /> - <property file="build.local.properties" /> <property file="build.properties" /> <property name="jdbc-jar" @@ -258,7 +257,7 @@ Copyright 1997 - July 2008 CWI, August 2 </target> <!-- - This generates MonetDriver.java from its ".java.in" equivalents. It's + This generates MonetDriver.java.in from its ".java.in" equivalents. It's required for importing the driver version properties. --> <target name="driver" depends="prepare" unless="uptodate.drivers"> @@ -282,7 +281,7 @@ Copyright 1997 - July 2008 CWI, August 2 <!-- now copy and filter the file --> <copy file="${srcdir}/${jdbc-package}/MonetDriver.java.in" overwrite="true" - tofile="${srcdir}/${jdbc-package}/MonetDriver.java" + tofile="src/main/java/nl/cwi/monetdb/jdbc/MonetDriver.java.in" filtering="yes" /> <echo message="Configured build for the ${JDBC_MAJOR}.${JDBC_MINOR} (${JDBC_VER_SUFFIX}) edition driver" />
--- a/example/PreparedExample.java +++ b/example/PreparedExample.java @@ -15,8 +15,7 @@ import java.sql.*; */ public class PreparedExample { public static void main(String[] args) throws Exception { - // make sure the driver is loaded - Class.forName("nl.cwi.monetdb.jdbc.MonetDriver"); + //Class.forName("nl.cwi.monetdb.jdbc.MonetDriver"); Connection con = DriverManager.getConnection("jdbc:monetdb://localhost/notused", "monetdb", "monetdb"); PreparedStatement st = con.prepareStatement("SELECT ? AS a1, ? AS a2"); ResultSet rs;
--- a/example/SQLImport.java +++ b/example/SQLImport.java @@ -37,8 +37,7 @@ public class SQLImport { // open the file BufferedReader fr = new BufferedReader(new FileReader(args[0])); - // make sure the driver is loaded - Class.forName("nl.cwi.monetdb.jdbc.MonetDriver"); + // Class.forName("nl.cwi.monetdb.jdbc.MonetDriver"); // request a connection suitable for Monet from the driver manager // note that the database specifier is currently not implemented, for // Monet itself can't access multiple databases.
--- a/example/SQLcopyinto.java +++ b/example/SQLcopyinto.java @@ -10,6 +10,9 @@ import java.sql.*; import java.io.*; import java.util.*; +import nl.cwi.monetdb.mcl.connection.mapi.MapiConnection; +import nl.cwi.monetdb.mcl.protocol.AbstractProtocol; + /** * This example demonstrates how the MonetDB JDBC driver can facilitate * in performing COPY INTO sequences. This is mainly meant to show how @@ -20,12 +23,9 @@ import java.util.*; public class SQLcopyinto { public static void main(String[] args) throws Exception { - // make sure the driver is loaded - Class.forName("nl.cwi.monetdb.jdbc.MonetDriver"); - // request a connection suitable for Monet from the driver manager - // note that the database specifier is currently not implemented, for - // Monet itself can't access multiple databases. - // turn on debugging + // Class.forName("nl.cwi.monetdb.jdbc.MonetDriver"); + // request a connection suitable for Monet from the driver manager note that the database specifier is currently + // not implemented, for Monet itself can't access multiple databases turn on debugging Connection con = DriverManager.getConnection("jdbc:monetdb://localhost/database", "monetdb", "monetdb"); // get a statement to execute on @@ -43,24 +43,19 @@ public class SQLcopyinto { // of course also be done simultaneously with the JDBC // connection being kept connected - /*DeleteMe server = new DeleteMe("localhost", 50000, "monetdb", "monetdb", false, "sql", "SHA256"); - - server.setDatabase("database"); - server.setLanguage("sql"); + MapiConnection server = new MapiConnection(null, "database",null, "sql", true,"localhost", 50000 ); try { - List warning = - server.connect( "monetdb", "monetdb"); + List warning = server.connect("monetdb", "monetdb"); if (warning != null) { for (Object aWarning : warning) { System.out.println(aWarning.toString()); } } + AbstractProtocol oldmMapiProtocol = server.getProtocol(); - AbstractMCLReader in = server.getReader(); - AbstractMCLWriter out = server.getWriter(); - - String error = in.waitForPrompt(); + oldmMapiProtocol.waitUntilPrompt(); + String error = oldmMapiProtocol.getRemainingStringLine(0); if (error != null) throw new Exception(error); @@ -68,15 +63,13 @@ public class SQLcopyinto { // the leading 's' is essential, since it is a protocol // marker that should not be omitted, likewise the // trailing semicolon - out.write('s'); - out.write(query); - out.newLine(); + oldmMapiProtocol.writeNextQuery("s", query, "\n"); + for (int i = 0; i < 100; i++) { - out.write("" + i + ",val_" + i); - out.newLine(); + oldmMapiProtocol.writeNextQuery(null, "" + i + ",val_" + i, "\n"); } - out.writeLine(""); // need this one for synchronisation over flush() - error = in.waitForPrompt(); + oldmMapiProtocol.waitUntilPrompt(); + error = oldmMapiProtocol.getRemainingStringLine(0); if (error != null) throw new Exception(error); // disconnect from server @@ -103,7 +96,7 @@ public class SQLcopyinto { // free resources, close the statement stmt.close(); // close the connection with the database - con.close();*/ + con.close(); } }
deleted file mode 100644 --- a/pom.xml +++ /dev/null @@ -1,152 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 - http://maven.apache.org/xsd/maven-4.0.0.xsd" - xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> - <modelVersion>4.0.0</modelVersion> - - <groupId>monetdb</groupId> - <artifactId>monetdb-jdbc</artifactId> - <version>2.23</version> - <name>${project.groupId}:${project.artifactId}</name> - <description>MonetDB JDBC driver</description> - <url>https://www.monetdb.org</url> - - <licenses> - <license> - <name>Mozilla Public License, Version 2.0</name> - <url>https://www.mozilla.org/MPL/2.0/</url> - </license> - </licenses> - - <developers> - <developer> - <name>Sjoerd Mullender</name> - <email>sjoerd@monetdb.org</email> - <organization>MonetDB</organization> - <organizationUrl>https://www.monetdb.org</organizationUrl> - </developer> - <developer> - <name>Dimitar Nedev</name> - <email>dimitar.nedev@monetdbsolutions.com</email> - <organization>MonetDB Solutions</organization> - <organizationUrl>https://www.monetdbsolutions.com</organizationUrl> - </developer> - </developers> - - <distributionManagement> - <snapshotRepository> - <id>ossrh</id> - <url>https://oss.sonatype.org/content/repositories/snapshots</url> - </snapshotRepository> - <repository> - <id>ossrh</id> - <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url> - </repository> - </distributionManagement> - - <scm> - <connection>scm:hg:https://dev.monetdb.org/hg/MonetDB/</connection> - <developerConnection>scm:hg:ssh://hg@dev.monetdb.org/MonetDB/</developerConnection> - <url>https://dev.monetdb.org/hg/MonetDB/</url> - </scm> - - <properties> - <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> - <jdbc.sources>nl/cwi/monetdb/jdbc/**/*.java</jdbc.sources> - <mcl.sources>nl/cwi/monetdb/mcl/**/*.java</mcl.sources> - </properties> - - <build> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-compiler-plugin</artifactId> - <version>3.2</version> - <configuration> - <includes> - <include>${jdbc.sources}</include> - <include>${mcl.sources}</include> - </includes> - <source>1.7</source> - <target>1.7</target> - </configuration> - </plugin> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-source-plugin</artifactId> - <version>2.2.1</version> - <executions> - <execution> - <id>attach-sources</id> - <goals> - <goal>jar-no-fork</goal> - </goals> - </execution> - </executions> - <configuration> - <includes> - <include>${jdbc.sources}</include> - <include>${mcl.sources}</include> - </includes> - </configuration> - </plugin> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-javadoc-plugin</artifactId> - <version>2.9.1</version> - <executions> - <execution> - <id>attach-javadocs</id> - <goals> - <goal>jar</goal> - </goals> - </execution> - </executions> - <configuration> - <sourceFileIncludes> - <include>${jdbc.sources}</include> - <include>${mcl.sources}</include> - </sourceFileIncludes> - <additionalparam>-Xdoclint:none</additionalparam> - </configuration> - </plugin> - <plugin> - <groupId>org.sonatype.plugins</groupId> - <artifactId>nexus-staging-maven-plugin</artifactId> - <version>1.6.3</version> - <extensions>true</extensions> - <configuration> - <serverId>ossrh</serverId> - <nexusUrl>https://oss.sonatype.org/</nexusUrl> - <autoReleaseAfterClose>false</autoReleaseAfterClose> - </configuration> - </plugin> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-release-plugin</artifactId> - <version>2.5</version> - <configuration> - <autoVersionSubmodules>true</autoVersionSubmodules> - <useReleaseProfile>false</useReleaseProfile> - <releaseProfiles>release</releaseProfiles> - <goals>deploy</goals> - </configuration> - </plugin> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-gpg-plugin</artifactId> - <version>1.5</version> - <executions> - <execution> - <id>sign-artifacts</id> - <phase>verify</phase> - <goals> - <goal>sign</goal> - </goals> - </execution> - </executions> - </plugin> - </plugins> - </build> - -</project>
--- a/src/main/java/nl/cwi/monetdb/client/JMonetDB.java +++ b/src/main/java/nl/cwi/monetdb/client/JMonetDB.java @@ -8,9 +8,13 @@ package nl.cwi.monetdb.client; -import nl.cwi.monetdb.util.*; -import nl.cwi.monetdb.merovingian.*; -import java.util.*; +import nl.cwi.monetdb.merovingian.Control; +import nl.cwi.monetdb.merovingian.SabaothDB; +import nl.cwi.monetdb.util.CmdLineOpts; +import nl.cwi.monetdb.util.OptionsException; + +import java.util.ArrayList; +import java.util.List; /** * This program mimics the monetdb tool. It is meant as demonstration @@ -22,7 +26,7 @@ import java.util.*; public class JMonetDB { - public final static void main(String[] args) throws Exception { + public static void main(String[] args) throws Exception { CmdLineOpts copts = new CmdLineOpts(); // arguments which take exactly one argument @@ -59,23 +63,21 @@ public class JMonetDB { if (copts.getOption("help").isPresent()) { System.out.print( -"Usage java -jar jmonetdb.jar\n" + -" -h host[:port] -p port -P passphrase [-X<opt>] -c cmd ...\n" + -"or using long option equivalents --host --port --passphrase.\n" + -"Arguments may be written directly after the option like -p50000.\n" + -"\n" + -"If no host and port are given, localhost and 50000 are assumed.\n" + -"\n" + -"OPTIONS\n" + -copts.produceHelpMessage() -); + "Usage java -jar jmonetdb.jar\n" + + " -h host[:port] -p port -P passphrase [-X<opt>] -c cmd ...\n" + + "or using long option equivalents --host --port --passphrase.\n" + + "Arguments may be written directly after the option like -p50000.\n" + + "\n" + + "If no host and port are given, localhost and 50000 are assumed.\n" + + "\n" + + "OPTIONS\n" + + copts.produceHelpMessage()); System.exit(0); } String pass = copts.getOption("passphrase").getArgument(); - // we need the password from the user, fetch it with a pseudo - // password protector + // we need the password from the user, fetch it with a pseudo password protector if (pass == null) { char[] tmp = System.console().readPassword("passphrase: "); if (tmp == null) { @@ -95,9 +97,9 @@ copts.produceHelpMessage() } int port = Integer.parseInt(sport); - /*String hash; TODO check this, the hash algorithm is not being used + String hash = null; if (copts.getOption("Xhash").isPresent()) - hash = copts.getOption("Xhash").getArgument();*/ + hash = copts.getOption("Xhash").getArgument(); if (!copts.getOption("command").isPresent()) { System.err.println("need a command to execute (-c)"); @@ -113,24 +115,19 @@ copts.produceHelpMessage() } // FIXME: Control needs to respect Xhash - if (copts.getOption("Xdebug").isPresent()) { - String fname = copts.getOption("Xdebug").getArgument(); - ctl.setDebug(fname); - } - String[] commands = copts.getOption("command").getArguments(); - /*if (commands[0].equals("status")) { + if (commands[0].equals("status")) { List<SabaothDB> sdbs; if (commands.length == 1) { sdbs = ctl.getAllStatuses(); } else { - sdbs = new ArrayList<>(); + sdbs = new ArrayList<SabaothDB>(); for (int i = 1; i < commands.length; i++) sdbs.add(ctl.getStatus(commands[i])); } for (SabaothDB sdb : sdbs) { System.out.println(sdb.getName() + " " + sdb.getURI()); } - }*/ + } } }
--- a/src/main/java/nl/cwi/monetdb/client/JdbcClient.java +++ b/src/main/java/nl/cwi/monetdb/client/JdbcClient.java @@ -8,12 +8,37 @@ package nl.cwi.monetdb.client; -import nl.cwi.monetdb.util.*; -import java.sql.*; -import java.io.*; -import java.util.*; -import java.util.zip.*; -import java.net.*; +import nl.cwi.monetdb.util.CmdLineOpts; +import nl.cwi.monetdb.util.Exporter; +import nl.cwi.monetdb.util.OptionsException; +import nl.cwi.monetdb.util.SQLExporter; +import nl.cwi.monetdb.util.XMLExporter; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.Statement; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Objects; +import java.util.zip.GZIPInputStream; /** * This program acts like an extended client program for MonetDB. Its @@ -35,7 +60,7 @@ public final class JdbcClient { private static Exporter exporter; private static DatabaseMetaData dbmd; - public final static void main(String[] args) throws Exception { + public static void main(String[] args) throws Exception { CmdLineOpts copts = new CmdLineOpts(); // arguments which take exactly one argument @@ -133,7 +158,7 @@ public final class JdbcClient { System.exit(1); } // we can actually compare pointers (objects) here - if (user != null && !user.equals(copts.getOption("user").getArgument())) pass = null; + if (!Objects.equals(user, copts.getOption("user").getArgument())) pass = null; if (copts.getOption("help").isPresent()) { System.out.print( @@ -194,8 +219,7 @@ public final class JdbcClient { host = host + ":" + copts.getOption("port").getArgument(); } - // make sure the driver is loaded - Class.forName("nl.cwi.monetdb.jdbc.MonetDriver"); + //Class.forName("nl.cwi.monetdb.jdbc.MonetDriver"); // build the extra arguments of the JDBC connect string String attr = "?"; @@ -250,7 +274,7 @@ public final class JdbcClient { dbmd = null; } stmt = con.createStatement(); - + // see if we will have to perform a database dump (only in SQL mode) if ("sql".equals(lang) && copts.getOption("dump").isPresent()) { ResultSet tbl; @@ -508,14 +532,8 @@ public final class JdbcClient { * @throws IOException if an IO exception occurs * @throws SQLException if a database related error occurs */ - public static void processInteractive( - boolean hasFile, - boolean doEcho, - boolean scolonterm, - String user - ) - throws IOException, SQLException - { + public static void processInteractive(boolean hasFile, boolean doEcho, boolean scolonterm, String user) + throws IOException, SQLException { // an SQL stack keeps track of ( " and ' SQLStack stack = new SQLStack(); // a query part is a line of an SQL query @@ -738,12 +756,8 @@ public final class JdbcClient { * @param showTiming flag to specify if timing information nees to be printed * @throws SQLException if a database related error occurs */ - private static void executeQuery(String query, - Statement stmt, - PrintWriter out, - boolean showTiming) - throws SQLException - { + private static void executeQuery(String query, Statement stmt, PrintWriter out, boolean showTiming) + throws SQLException { // warnings generated during querying SQLWarning warn; long startTime = (showTiming ? System.currentTimeMillis() : 0), finishTime; @@ -916,11 +930,7 @@ public final class JdbcClient { * @param scolonterm whether a ';' makes this query part complete * @return a QueryPart object containing the results of this parse */ - private static QueryPart scanQuery( - String query, - SQLStack stack, - boolean scolonterm) - { + private static QueryPart scanQuery(String query, SQLStack stack, boolean scolonterm) { // examine string, char for char boolean wasInString = (stack.peek() == '\''); boolean wasInIdentifier = (stack.peek() == '"'); @@ -1101,7 +1111,7 @@ class Table { final String name; final String type; final String fqname; - List<Table> needs = new ArrayList<>(); + List<Table> needs = new ArrayList<Table>(); Table(String schem, String name, String type) { this.schem = schem; @@ -1123,9 +1133,9 @@ class Table { List<Table> requires(List<Table> existingTables) { if (existingTables == null || existingTables.isEmpty()) - return new ArrayList<>(needs); + return new ArrayList<Table>(needs); - List<Table> req = new ArrayList<>(); + List<Table> req = new ArrayList<Table>(); for (Table n : needs) { if (!existingTables.contains(n)) req.add(n); @@ -1166,7 +1176,6 @@ class Table { return fqname; } - static Table findTable(String fqname, List<Table> list) { for (Table l : list) { if (l.fqname.equals(fqname))
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/env/AbstractConnectionResult.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.env; - -import java.io.Closeable; -import java.util.Random; - -/** - * The base class for a pending statement to a connection. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public abstract class AbstractConnectionResult implements Closeable { - - /** - * A random instance to generate the result set identifier. - */ - private static final Random Randomizer = new Random(); - - /** - * The corresponding connection of this result. - */ - private final MonetDBEmbeddedConnection connection; - - /** - * A long value used to identify this result set. - */ - private final long randomIdentifier; - - protected AbstractConnectionResult(MonetDBEmbeddedConnection connection) { - this.connection = connection; - this.randomIdentifier = Randomizer.nextLong(); - } - - /** - * Gets the corresponding connection to this statement result. - * - * @return A MonetDBEmbeddedConnection instance - */ - public MonetDBEmbeddedConnection getConnection() { return connection; } - - /** - * Gets a long number randomly generated, used to identify the result set. - * - * @return A random long identifier - */ - protected long getRandomIdentifier() { return randomIdentifier; } - - /** - * To be called by the connection when is closing. - */ - protected abstract void closeImplementation(); - - @Override - public void close() { - this.closeImplementation(); - this.connection.removeQueryResult(this); - } -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/env/JDBCEmbeddedConnection.java +++ /dev/null @@ -1,100 +0,0 @@ -package nl.cwi.monetdb.embedded.env; - -import nl.cwi.monetdb.mcl.protocol.ServerResponses; -import nl.cwi.monetdb.mcl.protocol.StarterHeaders; -import nl.cwi.monetdb.mcl.protocol.TableResultHeaders; -import nl.cwi.monetdb.mcl.responses.IResponse; - -/** - * Created by ferreira on 12/1/16. - */ -public class JDBCEmbeddedConnection extends MonetDBEmbeddedConnection { - - private long lastResultSetPointer; - - private final ServerResponses[] lineResponse = new ServerResponses[4]; - - private int currentLineResponseState; - - private StarterHeaders serverHeaderResponse; - - private final int[] lastServerResponseParameters = new int[4]; //for ResultSetResponse and DataBlockResponse - - private IResponse lastServerResponse; //for Update and Autocommit - - private String lastError; - - protected JDBCEmbeddedConnection(long connectionPointer) { - super(connectionPointer); - } - - public ServerResponses getNextServerResponse() { - return lineResponse[currentLineResponseState++]; - } - - public StarterHeaders getServerHeaderResponse() { - return serverHeaderResponse; - } - - public int[] getLastServerResponseParameters() { - return lastServerResponseParameters; - } - - public IResponse getLastServerResponse() { - return lastServerResponse; - } - - public TableResultHeaders fillTableHeaders(String[] columnNames, int[] columnLengths, String[] types, - String[] tableNames) { - this.getNextTableHeaderInternal(this.lastResultSetPointer, columnNames, columnLengths, types, tableNames); - return TableResultHeaders.ALL; - } - - public int parseTupleLines(int[] typesMap, Object[] values, boolean[][] nulls) { - return this.parseTupleLinesInternal(this.lastResultSetPointer, typesMap, values, nulls); - } - - public String getLastError() { - return lastError; - } - - public void processNextQuery(String query) { - if (!query.endsWith(";")) { - query += ";"; - } - this.currentLineResponseState = 0; - this.sendQueryInternal(this.connectionPointer, query, true); - } - - public void sendAutocommitCommand(int flag) { //1 or 0 - this.sendAutocommitCommandInternal(this.connectionPointer, flag); - } - - public void sendReleaseCommand(int commandId) { - this.sendReleaseCommandInternal(this.connectionPointer, commandId); - } - - public void sendCloseCommand(int commandId) { - this.sendCloseCommandInternal(this.connectionPointer, commandId); - } - - public void sendReplySizeCommand(int size) { - this.sendReplySizeCommandInternal(this.connectionPointer, size); - } - - private native void getNextTableHeaderInternal(long resultSetPointer, String[] columnNames, int[] columnLengths, - String[] types, String[] tableNames); - - private native int parseTupleLinesInternal(long resultSetPointer, int[] typesMap, Object[] values, - boolean[][] nulls); - - private native void sendQueryInternal(long connectionPointer, String query, boolean execute); - - private native void sendAutocommitCommandInternal(long connectionPointer, int flag); - - private native void sendReleaseCommandInternal(long connectionPointer, int commandId); - - private native void sendCloseCommandInternal(long connectionPointer, int commandId); - - private native void sendReplySizeCommandInternal(long connectionPointer, int size); -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/env/MonetDBEmbeddedConnection.java +++ /dev/null @@ -1,267 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.env; - -import nl.cwi.monetdb.embedded.resultset.*; -import nl.cwi.monetdb.embedded.tables.MonetDBTable; -import nl.cwi.monetdb.embedded.utils.StringEscaper; - -import java.util.concurrent.ConcurrentHashMap; - -/** - * A single connection to a MonetDB database instance - * Communication between Java and native C is done via JNI. - * <br/> - * <strong>Note</strong>: You can have only one Embedded MonetDB database running per JVM process. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public class MonetDBEmbeddedConnection { - - protected final long connectionPointer; - - private final ConcurrentHashMap<Long, AbstractConnectionResult> results = new ConcurrentHashMap<>(); - - protected MonetDBEmbeddedConnection(long connectionPointer) { this.connectionPointer = connectionPointer; } - - public long getConnectionPointer() { return connectionPointer; } - - /** - * Gets the current schema set on the connection. - * - * @return A Java String with the name of the schema - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - public String getCurrentSchema() throws MonetDBEmbeddedException { - QueryResultSet eqr = this.sendQuery("SELECT current_schema FROM sys.var();"); - QueryResultSetObjectColumn<String> col = eqr.getObjectColumnByIndex(0); - String res = col.fetchFirstNColumnValues(1)[0]; - eqr.close(); - return res; - } - - /** - * Sets the current schema on the connection. - * - * @param newSchema Java String with the name of the schema - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - public void setCurrentSchema(String newSchema) throws MonetDBEmbeddedException { - newSchema = StringEscaper.SQLStringEscape(newSchema); - this.sendUpdate("SET SCHEMA " + newSchema + ";").close(); - } - - /** - * Begins a transaction. - * - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - public void startTransaction() throws MonetDBEmbeddedException { - this.sendUpdate("START TRANSACTION;").close(); - } - - /** - * Commits the current transaction. - * - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - public void commit() throws MonetDBEmbeddedException { - this.sendUpdate("COMMIT;").close(); - } - - /** - * Rollbacks the current transaction. - * - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - public void rollback() throws MonetDBEmbeddedException { - this.sendUpdate("ROLLBACK;").close(); - } - - /** - * Executes a SQL query without a result set. - * - * @param query The SQL query string - * @return The update result object - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - public UpdateResultSet sendUpdate(String query) throws MonetDBEmbeddedException { - if (!query.endsWith(";")) { - query += ";"; - } - UpdateResultSet res = this.sendUpdateInternal(this.connectionPointer, query, true); - results.put(res.getRandomIdentifier(), res); - return res; - } - - /** - * Executes a SQL query without a result set asynchronously. - * - * @param query The SQL query string - * @return The update result object - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - /*public CompletableFuture<UpdateResultSet> sendUpdateAsync(String query) throws MonetDBEmbeddedException { - return CompletableFuture.supplyAsync(() -> this.sendUpdate(query)); - }*/ - - /** - * Executes a SQL query with a result set. - * - * @param query The SQL query string - * @return The query result object - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - public QueryResultSet sendQuery(String query) throws MonetDBEmbeddedException { - if (!query.endsWith(";")) { - query += ";"; - } - QueryResultSet res = this.sendQueryInternal(this.connectionPointer, query, true); - results.put(res.getRandomIdentifier(), res); - return res; - } - - /** - * Executes an SQL query with a result set asynchronously. - * - * @param query The SQL query string - * @return The query result object - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - /*public CompletableFuture<QueryResultSet> sendQueryAsync(String query) throws MonetDBEmbeddedException { - return CompletableFuture.supplyAsync(() -> this.sendQuery(query)); - }*/ - - /** - * Retrieves a MonetDB Table for further operations - * - * @param schemaName The schema of the table - * @param tableName The name of the table - * @return A MonetDBTable instance with column details - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - public MonetDBTable getMonetDBTable(String schemaName, String tableName) throws MonetDBEmbeddedException { - MonetDBTable res = this.getMonetDBTableInternal(this.connectionPointer, schemaName, tableName); - results.put(res.getRandomIdentifier(), res); - return res; - } - - /** - * Retrieves a MonetDB Table for further operations asynchronously. - * - * @param schemaName The schema of the table - * @param tableName The name of the table - * @return A MonetDBTable instance with column details - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - /*public CompletableFuture<MonetDBTable> getMonetDBTableAsync(String schemaName, String tableName) throws MonetDBEmbeddedException { - return CompletableFuture.supplyAsync(() -> this.getMonetDBTable(schemaName, tableName)); - }*/ - - /** - * Performs a listing of the existing tables with schemas. - * - * @param listSystemTables List system's tables as well (default true) - * @return The query result object, {@code null} if the database is not running - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - public QueryResultSet listTables(boolean listSystemTables) throws MonetDBEmbeddedException { - String query = "select schemas.name as sn, tables.name as tn from sys.tables join sys.schemas on tables.schema_id=schemas.id"; - if (!listSystemTables) { - query += " where tables.system=false order by sn, tn"; - } - return this.sendQuery(query + ";"); - } - - /** - * Check if a table it exists. - * - * @param schemaName The schema of the table - * @param tableName The name of the table - * @return If a the table exists or not - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - public boolean checkIfTableExists(String schemaName, String tableName) throws MonetDBEmbeddedException { - schemaName = StringEscaper.SQLStringEscape(schemaName); - tableName = StringEscaper.SQLStringEscape(tableName); - String query = - "select schemas.name as sn, tables.name as tn from sys.tables join sys.schemas on sys.tables.schema_id=schemas.id where tables.system=true order by sn, tn and schemas.name ='" + - schemaName + "' and tables.name ='" + tableName + "';"; - QueryResultSet eqr = this.sendQuery(query); - eqr.close(); - return eqr.getNumberOfRows() > 0; - } - - /** - * Deletes a table if it exists. - * - * @param schemaName The schema of the table - * @param tableName The name of the table - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - public void removeTable(String schemaName, String tableName) throws MonetDBEmbeddedException { - schemaName = StringEscaper.SQLStringEscape(schemaName); - tableName = StringEscaper.SQLStringEscape(tableName); - String query = "drop table " + schemaName + "." + tableName + ";"; - this.sendUpdate(query).close(); - } - - /** - * When the database is shuts down, this method is called instead - */ - void closeConnectionImplementation() { - for(AbstractConnectionResult res : this.results.values()) { - res.closeImplementation(); - } - this.closeConnectionInternal(this.connectionPointer); - } - - /** - * Shuts down this connection. Any pending queries connections will be immediately closed as well. - */ - public void closeConnection() { - this.closeConnectionImplementation(); - MonetDBEmbeddedDatabase.RemoveConnection(this); - } - - /** - * Shuts down this connection asynchronously. Any pending queries connections will be immediately closed as well. - */ - /*public CompletableFuture<Void> closeConnectionAsync() { - return CompletableFuture.runAsync(() -> this.closeConnection()); - }*/ - - /** - * Removes a query result from this connection. - */ - void removeQueryResult(AbstractConnectionResult res) { this.results.remove(res.getRandomIdentifier()); } - - /** - * Internal implementation of sendUpdate. - */ - private native UpdateResultSet sendUpdateInternal(long connectionPointer, String query, boolean execute) - throws MonetDBEmbeddedException; - - /** - * Internal implementation of sendQuery. - */ - private native QueryResultSet sendQueryInternal(long connectionPointer, String query, boolean execute) - throws MonetDBEmbeddedException; - - /** - * Internal implementation of getMonetDBTable. - */ - private native MonetDBTable getMonetDBTableInternal(long connectionPointer, String schemaName, String tableName) - throws MonetDBEmbeddedException; - - /** - * Internal implementation to close a connection. - */ - private native void closeConnectionInternal(long connectionPointer); -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/env/MonetDBEmbeddedDatabase.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.env; - -import java.util.concurrent.ConcurrentHashMap; - -/** - * An embedded version of a MonetDB database. - * Communication between Java and native C is done via JNI. The MonetDB's JNI library must be successfully loaded in - * order to the other methods work. - * <br/> - * <strong>Note</strong>: You can have only one Embedded MonetDB database running per JVM process. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public final class MonetDBEmbeddedDatabase { - - private static MonetDBEmbeddedDatabase MonetDBEmbeddedDatabase = null; - - /** - * Check if the database is still running or not. - * - * @return A boolean indicating if the database is running - */ - public static boolean IsDatabaseRunning() { return MonetDBEmbeddedDatabase != null; } - - /** - * Starts a MonetDB database on the given farm. - * - * @param dbDirectory The full path of the farm - * @param silentFlag A boolean if silent mode will be turned on or not - * @param sequentialFlag A boolean indicating if the sequential pipeline will be set or not - * @return Returns true if the load was successful. - * @throws MonetDBEmbeddedException If the JNI library has not been loaded yet or an error in the database occurred - */ - public static boolean StartDatabase(String dbDirectory, boolean silentFlag, boolean sequentialFlag) - throws MonetDBEmbeddedException { - if(MonetDBEmbeddedDatabase != null) { - throw new MonetDBEmbeddedException("The database is still running!"); - } else { - System.loadLibrary("monetdb5"); - MonetDBEmbeddedDatabase = StartDatabaseInternal(dbDirectory, silentFlag, sequentialFlag); - } - return true; - } - - /** - * Starts a MonetDB database on the given farm asynchronously. - * - * @param dbDirectory The full path of the farm - * @param silentFlag A boolean if silent mode will be turned on or not - * @param sequentialFlag A boolean indicating if the sequential pipeline will be set or not - * @return Returns true if the load was successful - * @throws MonetDBEmbeddedException If the JNI library has not been loaded yet or an error in the database occurred - */ - /*public static CompletableFuture<MonetDBEmbeddedDatabase> StartDatabaseAsync(String dbDirectory, boolean silentFlag, - boolean sequentialFlag) throws MonetDBEmbeddedException { - return CompletableFuture.supplyAsync(() -> StartDatabase(dbDirectory, silentFlag, sequentialFlag)); - }*/ - - /** - * Get the database farm directory. - * - * @throws MonetDBEmbeddedException If the database is not running - * @return A String representing the farm directory - */ - public static String GetDatabaseDirectory() throws MonetDBEmbeddedException { - if(MonetDBEmbeddedDatabase == null) { - throw new MonetDBEmbeddedException("The database is not running!"); - } - return MonetDBEmbeddedDatabase.databaseDirectory; - } - - /** - * Check if the Silent Flag was set while creating the database. - * - * @throws MonetDBEmbeddedException If the database is not running - * @return The Silent Flag - */ - public static boolean IsSilentFlagSet() throws MonetDBEmbeddedException { - if(MonetDBEmbeddedDatabase == null) { - throw new MonetDBEmbeddedException("The database is not running!"); - } - return MonetDBEmbeddedDatabase.silentFlag; - } - - /** - * Check if the Sequential Flag was set while creating the database. - * - * @throws MonetDBEmbeddedException If the database is not running - * @return The Sequential Flag - */ - public static boolean IsSequentialFlagSet() throws MonetDBEmbeddedException { - if(MonetDBEmbeddedDatabase == null) { - throw new MonetDBEmbeddedException("The database is not running!"); - } - return MonetDBEmbeddedDatabase.sequentialFlag; - } - - /** - * Stops the database. All the pending connections will be shut down as well. - * - * @throws MonetDBEmbeddedException If the database is not running or an error in the database occurred - */ - public static void StopDatabase() throws MonetDBEmbeddedException { - if(MonetDBEmbeddedDatabase == null) { - throw new MonetDBEmbeddedException("The database is not running!"); - } else { - for(MonetDBEmbeddedConnection mdbec : MonetDBEmbeddedDatabase.connections.values()) { - mdbec.closeConnectionImplementation(); - } - MonetDBEmbeddedDatabase.connections.clear(); - MonetDBEmbeddedDatabase.stopDatabaseInternal(); - MonetDBEmbeddedDatabase = null; - } - } - - /* - * Stops the database asynchronously. All the pending connections will be shut down as well. - * - * @throws MonetDBEmbeddedException If the database is not running or an error in the database occurred - */ - /*public static CompletableFuture<Void> StopDatabaseAsync() throws MonetDBEmbeddedException { - return CompletableFuture.runAsync(() -> this.stopDatabase()); - }*/ - - private final String databaseDirectory; - - private final boolean silentFlag; - - private final boolean sequentialFlag; - - private final ConcurrentHashMap<Long, MonetDBEmbeddedConnection> connections = new ConcurrentHashMap<>(); - - private MonetDBEmbeddedDatabase(String dbDirectory, boolean silentFlag, boolean sequentialFlag) { - this.databaseDirectory = dbDirectory; - this.silentFlag = silentFlag; - this.sequentialFlag = sequentialFlag; - } - - /** - * Creates a connection on the database, set on the default schema. - * - * @return A MonetDBEmbeddedConnection instance - * @throws MonetDBEmbeddedException If the database is not running or an error in the database occurred - */ - public static MonetDBEmbeddedConnection CreateConnection() throws MonetDBEmbeddedException { - if(MonetDBEmbeddedDatabase == null) { - throw new MonetDBEmbeddedException("The database is not running!"); - } else { - MonetDBEmbeddedConnection con = MonetDBEmbeddedDatabase.createConnectionInternal(); - MonetDBEmbeddedDatabase.connections.put(con.getConnectionPointer(), con); - return con; - } - } - - public static JDBCEmbeddedConnection CreateJDBCEmbeddedConnection() throws MonetDBEmbeddedException { - if(MonetDBEmbeddedDatabase == null) { - throw new MonetDBEmbeddedException("The database is not running!"); - } else { - JDBCEmbeddedConnection con = MonetDBEmbeddedDatabase.createJDBCEmbeddedConnectionInternal(); - MonetDBEmbeddedDatabase.connections.put(con.getConnectionPointer(), con); - return con; - } - } - - /** - * Removes a connection from this database. - */ - static void RemoveConnection(MonetDBEmbeddedConnection con) { - MonetDBEmbeddedDatabase.connections.remove(con.getConnectionPointer()); - } - - /** - * Internal implementation to start a database. - */ - private static native MonetDBEmbeddedDatabase StartDatabaseInternal(String dbDirectory, boolean silentFlag, - boolean sequentialFlag) - throws MonetDBEmbeddedException; - - /** - * Internal implementation to stop a database. - */ - private native void stopDatabaseInternal(); - - /** - * Internal implementation to create a connection on this database. - */ - private native MonetDBEmbeddedConnection createConnectionInternal() throws MonetDBEmbeddedException; - - /** - * Internal implementation to create a JDBC embeddded connection on this database. - */ - private native JDBCEmbeddedConnection createJDBCEmbeddedConnectionInternal() throws MonetDBEmbeddedException; -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/env/MonetDBEmbeddedException.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.env; - -import java.sql.SQLException; - -/** - * The exception fired from embedded methods. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public class MonetDBEmbeddedException extends SQLException { - - public MonetDBEmbeddedException(String message) { super(message); } -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/mapping/AbstractColumn.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.mapping; - -/** - * A single Java representation of a MonetDB column. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public abstract class AbstractColumn { - - /** - * The mapping between MonetDB type and the Java Class. - */ - protected final MonetDBToJavaMapping mapping; - - /** - * The column name. - */ - private final String columnName; - - /** - * The column digits. - */ - private final int columnDigits; - - /** - * The column scale. - */ - private final int columnScale; - - protected AbstractColumn(String columnType, String columnName, int columnDigits, int columnScale) { - this.mapping = MonetDBToJavaMapping.GetJavaMappingFromMonetDBString(columnType); - this.columnName = columnName; - this.columnDigits = columnDigits; - this.columnScale = columnScale; - } - - /** - * Gets the type of the column. - * - * @return The Column type - */ - public String getColumnInternalTypeName() { return mapping.toString(); } - - /** - * Gets the Java mapping of the column. - * - * @return A enum constant of the Java mapping - */ - public MonetDBToJavaMapping getMapping() { return mapping; } - - /** - * Gets the name of the column. - * - * @return The column name - */ - public String getColumnName() { return this.columnName; } - - /** - * Gets the number digits of the column. - * - * @return The number of digits - */ - public int getColumnDigits() { return this.columnDigits; } - - /** - * Gets the scale of the column. - * - * @return The scale - */ - public int getColumnScale() { return this.columnScale; } -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/mapping/AbstractResultTable.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.mapping; - -import nl.cwi.monetdb.embedded.env.AbstractConnectionResult; -import nl.cwi.monetdb.embedded.env.MonetDBEmbeddedConnection; - -/** - * Base class for statement results with data - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public abstract class AbstractResultTable extends AbstractConnectionResult { - - public AbstractResultTable(MonetDBEmbeddedConnection connection) { super(connection); } - - /** - * Returns the number of columns in the result set. - * - * @return Number of columns - */ - public abstract int getNumberOfColumns(); - - /** - * Returns the number of rows in the result set. - * - * @return Number of rows - */ - public abstract int getNumberOfRows(); - - /** - * Gets the columns names as a string array. - * - * @return The columns names array - */ - public abstract String[] getColumnNames(); - - /** - * Gets the columns types as a string array. - * - * @return The columns types array - */ - public abstract String[] getColumnTypes(); - - /** - * Gets the Java mappings as a MonetDBToJavaMapping array. - * - * @return The columns MonetDBToJavaMapping array - */ - public abstract MonetDBToJavaMapping[] getMappings(); - - /** - * Gets the columns digits as an integer array. - * - * @return The columns digits array - */ - public abstract int[] getColumnDigits(); - - /** - * Gets the columns scales as an integer array. - * - * @return The columns scales array - */ - public abstract int[] getColumnScales(); -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/mapping/AbstractRowSet.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.mapping; - -/** - * A row set retrieved from an embedded MonetDB query result. All the values in this set are already mapped - * to Java classes a priori. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public abstract class AbstractRowSet { - - /** - * The original query result set this row set belongs. - */ - private final AbstractResultTable table; - - /** - * The MonetDB-To-Java mappings of the columns. - */ - protected final MonetDBToJavaMapping[] mappings; - - /** - * The rows of this set. - */ - protected final MonetDBRow[] rows; - - protected AbstractRowSet(AbstractResultTable table, MonetDBToJavaMapping[] mappings, Object[][] rows) { - this.table = table; - this.mappings = mappings; - this.rows = new MonetDBRow[rows.length]; - for(int i = 0 ; i < rows.length ; i++) { - this.rows[i] = new MonetDBRow(this, rows[i]); - } - } - - /** - * Gets the original query result set this row set belongs. - * - * @return The original query result set this row set belongs - */ - public AbstractResultTable getQueryResultTable() { return table; } - - /** - * Gets the number of columns in this set. - * - * @return The number of columns in this set - */ - public int getNumberOfColumns() { return mappings.length; } - - /** - * Gets a column index in the result set by name. - * - * @return The index number - */ - public abstract int getColumnIndexByName(String columnName); -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/mapping/MonetDBRow.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.mapping; - -import java.util.Arrays; -import java.util.ListIterator; - -/** - * A single MonetDB row in a result set. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public class MonetDBRow implements Iterable { - - /** - * The original row result set from this row. - */ - private final AbstractRowSet originalSet; - - /** - * The columns values as Java objects. - */ - private Object[] columns; - - MonetDBRow(AbstractRowSet originalSet, Object[] columns) { - this.originalSet = originalSet; - this.columns = columns; - } - - /** - * Gets the original row result set from this row. - * - * @return The original row result set from this row - */ - public AbstractRowSet getRowSet() { return originalSet; } - - /** - * Gets the columns values as Java objects. - * - * @return The columns values as Java objects - */ - public Object[] getAllColumns() { return columns; } - - /** - * Sets all columns values as Java objects. Warning - this method does not override the contents in the database! - * - * @param values An object array of the elements to update - */ - public void setAllColumns(Object[] values) { - if(values.length != this.columns.length) - throw new ArrayStoreException("The values array and the columns length differ!"); - this.columns = values; - } - - /** - * Gets the number of columns. - * - * @return The number of columns - */ - public int getNumberOfColumns() { return columns.length; } - - /** - * Gets a column value as a Java class. - * - * @param <T> A Java class mapped to a MonetDB data type - * @param index The index of the column - * @param javaClass The Java class - * @return The column value as a Java class - */ - public <T> T getColumnByIndex(int index, Class<T> javaClass) { return javaClass.cast(columns[index]); } - - /** - * Gets a column value as a Java class using the default mapping. - * - * @param <T> A Java class mapped to a MonetDB data type - * @param index The index of the column - * @return The column value as a Java class - */ - public <T> T getColumnByIndex(int index) { - Class<T> javaClass = this.originalSet.mappings[index].getJavaClass(); - return javaClass.cast(columns[index]); - } - - /** - * Gets a column value as a Java class. - * - * @param <T> A Java class mapped to a MonetDB data type - * @param columnName The name of the column - * @param javaClass The Java class - * @return The column value as a Java class - */ - public <T> T getColumnByName(String columnName, Class<T> javaClass) { - int index = this.getRowSet().getColumnIndexByName(columnName); - return javaClass.cast(columns[index]); - } - - /** - * Gets a column value as a Java class using the default mapping. - * - * @param <T> A Java class mapped to a MonetDB data type - * @param columnName The name of the column - * @return The column value as a Java class - */ - public <T> T getColumnByName(String columnName) { - int index = this.getRowSet().getColumnIndexByName(columnName); - Class<T> javaClass = this.originalSet.mappings[index].getJavaClass(); - return javaClass.cast(columns[index]); - } - - /** - * Sets a column value as a Java class. Warning - this method does not override the contents in the database! - * - * @param <T> A Java class mapped to a MonetDB data type - * @param index The index of the column - * @param value The value to set - */ - public <T> void setColumnByIndex(int index, T value) { - this.columns[index] = this.originalSet.mappings[index].getJavaClass().cast(value); - } - - /** - * Sets a column value as a Java class. Warning - this method does not override the contents in the database! - * - * @param <T> A Java class mapped to a MonetDB data type - * @param index The index of the column - * @param javaClass The Java class - * @param value The value to set - */ - public <T> void setColumnByIndex(int index, Class<T> javaClass, T value) { - this.columns[index] = javaClass.cast(value); - } - - /** - * Sets a column value as a Java class. Warning - this method does not override the contents in the database! - * - * @param <T> A Java class mapped to a MonetDB data type - * @param columnName The name of the column - * @param value The value to set - */ - public <T> void setColumnByName(String columnName, T value) { - int index = this.getRowSet().getColumnIndexByName(columnName); - this.columns[index] = this.originalSet.mappings[index].getJavaClass().cast(value); - } - - /** - * Sets a column value as a Java class. Warning - this method does not override the contents in the database! - * - * @param <T> A Java class mapped to a MonetDB data type - * @param columnName The name of the column - * @param javaClass The Java class - * @param value The value to set - */ - public <T> void setColumnByName(String columnName, Class<T> javaClass, T value) { - int index = this.getRowSet().getColumnIndexByName(columnName); - this.columns[index] = javaClass.cast(value); - } - - @Override - public ListIterator<Object> iterator() { return Arrays.asList(this.columns).listIterator(); } -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/mapping/MonetDBToJavaMapping.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.mapping; - -import nl.cwi.monetdb.jdbc.MonetBlob; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.net.Inet4Address; -import java.net.URL; -import java.sql.Date; -import java.sql.Time; -import java.sql.Timestamp; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.UUID; - -/** - * A Java enum representing the mappings between MonetDB data types and Java classes. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public enum MonetDBToJavaMapping { - - /* PLEASE Don't change these enum values order!! */ - Boolean(Boolean.class), Char(String.class), Varchar(String.class), Clob(String.class), Oid(Long.class), - Tinyint(Byte.class), Smallint(Short.class), Int(Integer.class), Wrd(Long.class), Bigint(Long.class), - Hugeint(BigInteger.class), Decimal(BigDecimal.class), Real(Float.class), Double(Double.class), - MonthInterval(Integer.class), SecondInterval(Long.class), Time(Time.class), TimeTz(Time.class), Date(Date.class), - Timestamp(Timestamp.class), TimestampTz(Timestamp.class), Blob(MonetBlob.class), Geometry(String.class), - GeometryA(String.class), URL(URL.class), Inet(Inet4Address.class), JSON(String.class), UUID(UUID.class); - - /** - * The mapping between MonetDB data types and enum values. - */ - private static final HashMap<String, MonetDBToJavaMapping> MonetDBMappings; - - /** - * The mapping between MonetDB data types and enum values. - */ - private static final EnumMap<MonetDBToJavaMapping, Class<?>> AppendMappings; - - static { - MonetDBMappings = new HashMap<>(); - MonetDBMappings.put("boolean", Boolean); - MonetDBMappings.put("char", Char); - MonetDBMappings.put("varchar", Varchar); - MonetDBMappings.put("clob", Clob); - MonetDBMappings.put("oid", Oid); - MonetDBMappings.put("tinyint", Tinyint); - MonetDBMappings.put("smallint", Smallint); - MonetDBMappings.put("int", Int); - MonetDBMappings.put("wrd", Wrd); - MonetDBMappings.put("bigint", Bigint); - MonetDBMappings.put("hugeint", Hugeint); - MonetDBMappings.put("decimal", Decimal); - MonetDBMappings.put("real", Real); - MonetDBMappings.put("double", Double); - MonetDBMappings.put("month_interval", MonthInterval); - MonetDBMappings.put("sec_interval", SecondInterval); - MonetDBMappings.put("time", Time); - MonetDBMappings.put("timetz", TimeTz); - MonetDBMappings.put("date", Date); - MonetDBMappings.put("timestamp", Timestamp); - MonetDBMappings.put("timestamptz", TimestampTz); - MonetDBMappings.put("blob", Blob); - MonetDBMappings.put("geometry", Geometry); - MonetDBMappings.put("geometrya", GeometryA); - MonetDBMappings.put("url", URL); - MonetDBMappings.put("inet", Inet); - MonetDBMappings.put("json", JSON); - MonetDBMappings.put("uuid", UUID); - - AppendMappings = new EnumMap<>(MonetDBToJavaMapping.class); - AppendMappings.put(Boolean, boolean[].class); - AppendMappings.put(Char, String[].class); - AppendMappings.put(Varchar, String[].class); - AppendMappings.put(Clob, String[].class); - AppendMappings.put(Oid, long[].class); - AppendMappings.put(Tinyint, byte[].class); - AppendMappings.put(Smallint, short[].class); - AppendMappings.put(Int, int[].class); - AppendMappings.put(Wrd, long[].class); - AppendMappings.put(Bigint, long[].class); - AppendMappings.put(Hugeint, BigInteger[].class); - AppendMappings.put(Decimal, BigDecimal[].class); - AppendMappings.put(Real, float[].class); - AppendMappings.put(Double, double[].class); - AppendMappings.put(MonthInterval, int[].class); - AppendMappings.put(SecondInterval, long[].class); - AppendMappings.put(Time, Time[].class); - AppendMappings.put(TimeTz, Time[].class); - AppendMappings.put(Date, Date[].class); - AppendMappings.put(Timestamp, Timestamp[].class); - AppendMappings.put(TimestampTz, Timestamp[].class); - AppendMappings.put(Blob, MonetBlob[].class); - AppendMappings.put(Geometry, String[].class); - AppendMappings.put(GeometryA, String[].class); - AppendMappings.put(URL, URL[].class); - AppendMappings.put(Inet, Inet4Address[].class); - AppendMappings.put(JSON, String[].class); - AppendMappings.put(UUID, UUID[].class); - } - - /** - * Get the corresponding MonetDBToJavaMapping from MonetDB internal data type. - * - * @param sqlName The MonetDB's data type SQL name - * @return A MonetDBToJavaMapping enum value, or null if it has no mapping - */ - public static MonetDBToJavaMapping GetJavaMappingFromMonetDBString(String sqlName) { - return MonetDBMappings.get(sqlName); - } - - /** - * Get the corresponding MonetDBToJavaMapping from MonetDB internal data type. - * - * @param value A MonetDBToJavaMapping entry - * @return The corresponding Java array class or null if no mapping - */ - public static Class<?> GetArrayMappingFromEnumValue(MonetDBToJavaMapping value) { - return AppendMappings.get(value); - } - - /** - * The corresponding Java class for the enum value. - */ - private final Class<?> javaClass; - - MonetDBToJavaMapping(Class<?> javaClass) { this.javaClass = javaClass; } - - /** - * Gets the corresponding Java class for the enum value. - * - * @return The corresponding Java class for the enum value - */ - @SuppressWarnings("unchecked") - public <T> Class<T> getJavaClass() { return (Class<T>) this.javaClass; } -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/resultset/AbstractQueryResultSetColumn.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.resultset; - -import nl.cwi.monetdb.embedded.env.MonetDBEmbeddedException; -import nl.cwi.monetdb.embedded.mapping.AbstractColumn; - -/** - * An abstract class for accessing materialised (Java-level) query result columns. - * - * @param <A> An array of a Java primitive mapped from a MonetDB column !! Must be a Java array !! - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public abstract class AbstractQueryResultSetColumn<A> extends AbstractColumn { - - /** - * Internal C pointer of the column, - */ - protected long tablePointer; - - /** - * The index of the column. - */ - final int resultSetIndex; - - /** - * The number of rows in this column. - */ - protected final int numberOfRows; - - /** - * The index of the first value mapped to a Java class. - */ - private int firstRetrievedIndex; - - /** - * The index of the last value mapped to a Java class. - */ - private int lastRetrievedIndex; - - /** - * The null values mapping - */ - final boolean[] nullValues; - - protected AbstractQueryResultSetColumn(String columnType, long tablePointer, int resultSetIndex, String columnName, - int columnDigits, int columnScale, int numberOfRows) { - super(columnType, columnName, columnDigits, columnScale); - this.tablePointer = tablePointer; - this.resultSetIndex = resultSetIndex; - this.numberOfRows = numberOfRows; - this.firstRetrievedIndex = numberOfRows; - this.lastRetrievedIndex = 0; - this.nullValues = new boolean[numberOfRows]; - } - - /** - * Gets the result set index of the column. - * - * @return The result set index of the column - */ - public int getResultSetIndex() { - return resultSetIndex; - } - - /** - * Gets the number of rows in this column. - * - * @return The number of rows - */ - public int getNumberOfRows() { return this.numberOfRows; } - - protected abstract void fetchMoreData(int startIndex, int endIndex) throws MonetDBEmbeddedException; - - protected abstract A storeNewDataAndGetResult(int startIndex, int numberOfRowsToRetrieve); - - protected abstract Object[] mapValuesToObjectArrayImplementation(int startIndex, int numberOfRowsToRetrieve); - - private int checkBoundsAndFetch(int startIndex, int endIndex) throws MonetDBEmbeddedException { - if(endIndex < startIndex) { - throw new ArrayIndexOutOfBoundsException("The endIndex cannot be smaller than the startIndex!"); - } else if (startIndex < 0) { - throw new ArrayIndexOutOfBoundsException("The start index must be larger than 0!"); - } else if (endIndex > this.numberOfRows) { - throw new ArrayIndexOutOfBoundsException("The index must be smaller than the number of elements in the set!"); - } else if(startIndex == endIndex) { - throw new ArrayIndexOutOfBoundsException("Retrieving 0 values?"); - } - boolean hasToFetch = false; - int numberOfRowsToRetrieve = endIndex - startIndex; - int firstIndexToFetch = Math.min(startIndex, this.firstRetrievedIndex); - int lastIndexToFetch = Math.max(endIndex, this.lastRetrievedIndex); - if(startIndex < this.firstRetrievedIndex) { - this.firstRetrievedIndex = startIndex; - hasToFetch = true; - } - if(endIndex > this.lastRetrievedIndex) { - this.lastRetrievedIndex = endIndex; - hasToFetch = true; - } - if(hasToFetch) { - if(this.tablePointer == 0) { - throw new MonetDBEmbeddedException("Connection closed!"); - } - this.fetchMoreData(firstIndexToFetch, lastIndexToFetch); - } - return numberOfRowsToRetrieve; - } - - /** - * Maps columns values using the provided Java representation by the query. - * - * @param startIndex The first column index to retrieve - * @param endIndex The last column index to retrieve - * @return The column values as a Java array - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - public A fetchColumnValues(int startIndex, int endIndex) throws MonetDBEmbeddedException { - int numberOfRowsToRetrieve = this.checkBoundsAndFetch(startIndex, endIndex); - return this.storeNewDataAndGetResult(startIndex, numberOfRowsToRetrieve); - } - - /** - * Maps columns values using the provided Java representation by the query asynchronously. - * - * @param startIndex The first column index to retrieve - * @param endIndex The last column index to retrieve - * @return The column values as a Java array - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - /*@SuppressWarnings("unchecked") - public CompletableFuture<T[]> fetchColumnValuesAsync(int startIndex, int endIndex) throws MonetDBEmbeddedException { - return this.fetchColumnValuesAsync(startIndex, endIndex, (Class<T>) this.mapping.getJavaClass()); - }*/ - - /** - * Maps the first N column values using the provided Java representation by the query. - * - * @param n The last column index to map - * @return The column values as a Java array - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - public A fetchFirstNColumnValues(int n) throws MonetDBEmbeddedException { - return this.fetchColumnValues(0, n); - } - - /** - * Maps the first N column values using the provided Java representation by the query asynchronously. - * - * @param n The last column index to map - * @return The column values as a Java array - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - /*public CompletableFuture<T[]> fetchFirstNColumnValuesAsync(int n) throws MonetDBEmbeddedException { - return this.fetchColumnValuesAsync(0, n); - }*/ - - /** - * Maps all column values using the provided Java representation by the query. - * - * @return The column values as a Java array - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - public A fetchAllColumnValues() throws MonetDBEmbeddedException { - return this.fetchColumnValues(0, this.numberOfRows); - } - - /** - * Maps all column values using the provided Java representation by the query asynchronously. - * - * @return The column values as a Java array - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - /*public CompletableFuture<T[]> fetchAllColumnValuesAsync() throws MonetDBEmbeddedException { - return this.fetchColumnValuesAsync(0, this.numberOfRows); - }*/ - - /** - * Checks if column indexes are null - * - * @param startIndex The first column index to check - * @param endIndex The last column index to check - * @return If the index is null or not - */ - public boolean[] checkIfIndexesAreNull(int startIndex, int endIndex) throws MonetDBEmbeddedException { - int numberOfRowsToRetrieve = this.checkBoundsAndFetch(startIndex, endIndex); - boolean[] res = new boolean[numberOfRowsToRetrieve]; - System.arraycopy(this.nullValues, startIndex, res, 0, numberOfRowsToRetrieve); - return res; - } - - /** - * Maps values to a Java Object array while mapping null values as well. - * - * @param startIndex The first column index to map - * @param endIndex The last column index to map - * @return The mapped Java array - */ - public Object[] mapValuesToObjectArray(int startIndex, int endIndex) throws MonetDBEmbeddedException { - int numberOfRowsToRetrieve = this.checkBoundsAndFetch(startIndex, endIndex); - return this.mapValuesToObjectArrayImplementation(startIndex, numberOfRowsToRetrieve); - } -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/resultset/QueryResultRowSet.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.resultset; - -import nl.cwi.monetdb.embedded.mapping.AbstractRowSet; -import nl.cwi.monetdb.embedded.mapping.MonetDBRow; -import nl.cwi.monetdb.embedded.mapping.MonetDBToJavaMapping; - -import java.lang.reflect.Array; -import java.util.Arrays; -import java.util.ListIterator; - -/** - * The row result set from a sendQuery. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public class QueryResultRowSet extends AbstractRowSet implements Iterable { - - QueryResultRowSet(QueryResultSet queryResultSet, MonetDBToJavaMapping[] mappings, Object[][] rows) { - super(queryResultSet, mappings, rows); - } - - /** - * Gets all rows of this set. - * - * @return All rows of this set - */ - public MonetDBRow[] getAllRows() { return rows; } - - /** - * Gets the number of rows in this set. - * - * @return The number of rows in this set - */ - public int getNumberOfRows() { return rows.length; } - - /** - * Gets a single row in this set. - * - * @param row The index of the row to retrieve - * @return A single row in this set - */ - public MonetDBRow getSingleRow(int row) { return rows[row]; } - - @Override - public int getColumnIndexByName(String columnName) { - return ((QueryResultSet) this.getQueryResultTable()).getColumnIndexByName(columnName); - } - - /** - * Gets a single value in this set as a Java class. - * - * @param <T> A Java class mapped to a MonetDB data type - * @param row The index of the row to retrieve - * @param column The index of the column to retrieve - * @param javaClass The Java class to map - * @return The value mapped to a instance of the provided class - */ - public <T> T getSingleValueByIndex(int row, int column, Class<T> javaClass) { - return javaClass.cast(this.rows[row].getColumnByIndex(column)); - } - - /** - * Gets a single value in this set as a Java class using the default mapping. - * - * @param <T> A Java class mapped to a MonetDB data type - * @param row The index of the row to retrieve - * @param column The index of the column to retrieve - * @return The value mapped to a instance of the provided class - */ - public <T> T getSingleValueByIndex(int row, int column) { - Class<T> javaClass = this.mappings[column].getJavaClass(); - return javaClass.cast(this.rows[row].getColumnByIndex(column)); - } - - /** - * Gets a single value in this set as a Java class. - * - * @param <T> A Java class mapped to a MonetDB data type - * @param row The index of the row to retrieve - * @param columnName The name of the column to retrieve - * @param javaClass The Java class to map - * @return The value mapped to a instance of the provided class - */ - public <T> T getSingleValueByName(int row, String columnName, Class<T> javaClass) { - int index = this.getColumnIndexByName(columnName); - return this.getSingleValueByIndex(row, index, javaClass); - } - - /** - * Gets a single value in this set as a Java class using the default mapping. - * - * @param <T> A Java class mapped to a MonetDB data type - * @param row The index of the row to retrieve - * @param columnName The name of the column to retrieve - * @return The value mapped to a instance of the provided class - */ - public <T> T getSingleValueByName(int row, String columnName) { - int index = this.getColumnIndexByName(columnName); - return this.getSingleValueByIndex(row, index); - } - - /** - * Gets a column in this set as a Java class. - * - * @param <T> A Java class mapped to a MonetDB data type - * @param column The index of the column to retrieve - * @param javaClass The Java class - * @return The value mapped to a instance of the provided class - */ - @SuppressWarnings("unchecked") - public <T> T[] getColumnByIndex(int column, Class<T> javaClass) { - T[] res = (T[]) Array.newInstance(javaClass, this.rows.length); - for(int i = 0 ; i < this.rows.length ; i++) { - res[i] = this.rows[i].getColumnByIndex(column); - } - return res; - } - - /** - * Gets a column in this set as a Java class using the default mapping. - * - * @param <T> A Java class mapped to a MonetDB data type - * @param column The index of the column to retrieve - * @return The value mapped to a instance of the provided class - */ - @SuppressWarnings("unchecked") - public <T> T[] getColumnByIndex(int column) { - T[] res = (T[]) Array.newInstance(this.mappings[column].getJavaClass(), this.rows.length); - for(int i = 0 ; i < this.rows.length ; i++) { - res[i] = this.rows[i].getColumnByIndex(column); - } - return res; - } - - /** - * Gets a column in this set as a Java class. - * - * @param <T> A Java class mapped to a MonetDB data type - * @param columnName The name of the column to retrieve - * @param javaClass The Java class - * @return The value mapped to a instance of the provided class - */ - public <T> T[] getColumnByName(String columnName, Class<T> javaClass) { - int index = this.getColumnIndexByName(columnName); - return this.getColumnByIndex(index, javaClass); - } - - /** - * Gets a column in this set as a Java class using the default mapping. - * - * @param <T> A Java class mapped to a MonetDB data type - * @param columnName The name of the column to retrieve - * @return The value mapped to a instance of the provided class - */ - public <T> T[] getColumnByName(String columnName) { - int index = this.getColumnIndexByName(columnName); - return this.getColumnByIndex(index); - } - - @Override - public ListIterator<MonetDBRow> iterator() { return Arrays.asList(this.rows).listIterator(); } -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/resultset/QueryResultSet.java +++ /dev/null @@ -1,423 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.resultset; - -import nl.cwi.monetdb.embedded.mapping.AbstractResultTable; -import nl.cwi.monetdb.embedded.env.MonetDBEmbeddedConnection; -import nl.cwi.monetdb.embedded.env.MonetDBEmbeddedException; -import nl.cwi.monetdb.embedded.mapping.MonetDBRow; -import nl.cwi.monetdb.embedded.mapping.MonetDBToJavaMapping; - -import java.util.Arrays; -import java.util.ListIterator; - -/** - * Embedded MonetDB query result. - * The query result columns are not eagerly copied from the native code to Java. - * Instead, they are kept around at MonetDB native C-level, materialised in Java - * on demand and freed on {@code super.close()}. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public final class QueryResultSet extends AbstractResultTable implements Iterable { - - /** - * The table C pointer. - */ - protected long tablePointer; - - /** - * The query result set columns listing. - */ - private final AbstractQueryResultSetColumn<?>[] columns; - - /** - * The number of rows in the query result. - */ - protected final int numberOfRows; - - protected QueryResultSet(MonetDBEmbeddedConnection connection, long tablePointer, - AbstractQueryResultSetColumn<?>[] columns, int numberOfRows) { - super(connection); - this.tablePointer = tablePointer; - this.numberOfRows = numberOfRows; - this.columns = columns; - } - - @Override - public int getNumberOfRows() { return this.numberOfRows; } - - @Override - public int getNumberOfColumns() { return this.columns.length; } - - @Override - protected void closeImplementation() { this.cleanResultSet(this.tablePointer); } - - @Override - public String[] getColumnNames() { - int i = 0; - String[] result = new String[this.getNumberOfColumns()]; - for(AbstractQueryResultSetColumn col : this.columns) { - result[i] = col.getColumnName(); - } - return result; - } - - @Override - public String[] getColumnTypes() { - int i = 0; - String[] result = new String[this.getNumberOfColumns()]; - for(AbstractQueryResultSetColumn col : this.columns) { - result[i] = col.getColumnInternalTypeName(); - } - return result; - } - - @Override - public MonetDBToJavaMapping[] getMappings() { - int i = 0; - MonetDBToJavaMapping[] result = new MonetDBToJavaMapping[this.getNumberOfColumns()]; - for(AbstractQueryResultSetColumn col : this.columns) { - result[i] = col.getMapping(); - } - return result; - } - - @Override - public int[] getColumnDigits() { - int i = 0; - int[] result = new int[this.getNumberOfColumns()]; - for(AbstractQueryResultSetColumn col : this.columns) { - result[i] = col.getColumnDigits(); - } - return result; - } - - @Override - public int[] getColumnScales() { - int i = 0; - int[] result = new int[this.getNumberOfColumns()]; - for(AbstractQueryResultSetColumn col : this.columns) { - result[i] = col.getColumnScale(); - } - return result; - } - - /** - * Tells if the connection of this statement result has been closed or not. - * - * @return A boolean indicating if the statement result has been cleaned or not - */ - public boolean isStatementClosed() { return this.tablePointer == 0; } - - /** - * Gets a column index from the result set by name - * - * @param columnName AbstractQueryResultSetColumn name - * @return The index number - */ - public int getColumnIndexByName(String columnName) { - int index = 0; - for (AbstractQueryResultSetColumn col : this.columns) { - if (col.getColumnName().equals(columnName)) { - return index; - } - index++; - } - throw new ArrayIndexOutOfBoundsException("The column is not present in the result set!"); - } - - /** - * Gets a column from the result set by index. - * - * @param index AbstractQueryResultSetColumn index (starting from 0) - * @return The column - */ - public AbstractQueryResultSetColumn<?> getColumnByIndex(int index) { return this.columns[index]; } - - /** - * Gets a column from the result set by name. - * - * @param columnName AbstractQueryResultSetColumn name - * @return The column - */ - public AbstractQueryResultSetColumn<?> getColumnByName(String columnName) { - int index = this.getColumnIndexByName(columnName); - return this.columns[index]; - } - - /** - * Gets a boolean column from the result set by index. - * - * @param index QueryResultSetBooleanColumn index (starting from 0) - * @return The boolean column - */ - public QueryResultSetBooleanColumn getBooleanColumnByIndex(int index) { - return (QueryResultSetBooleanColumn) this.columns[index]; - } - - /** - * Gets a boolean column from the result set by name. - * - * @param columnName QueryResultSetBooleanColumn name - * @return The boolean column - */ - public QueryResultSetBooleanColumn getBooleanColumnByName(String columnName) { - int index = this.getColumnIndexByName(columnName); - return (QueryResultSetBooleanColumn) this.columns[index]; - } - - /** - * Gets a byte column from the result set by index. - * - * @param index QueryResultSetByteColumn index (starting from 0) - * @return The byte column - */ - public QueryResultSetByteColumn getByteColumnByIndex(int index) { - return (QueryResultSetByteColumn) this.columns[index]; - } - - /** - * Gets a byte column from the result set by name. - * - * @param columnName QueryResultSetByteColumn name - * @return The byte column - */ - public QueryResultSetByteColumn getByteColumnByName(String columnName) { - int index = this.getColumnIndexByName(columnName); - return (QueryResultSetByteColumn) this.columns[index]; - } - - /** - * Gets a short column from the result set by index. - * - * @param index QueryResultSetShortColumn index (starting from 0) - * @return The short column - */ - public QueryResultSetShortColumn getShortColumnByIndex(int index) { - return (QueryResultSetShortColumn) this.columns[index]; - } - - /** - * Gets a short column from the result set by name. - * - * @param columnName QueryResultSetShortColumn name - * @return The short column - */ - public QueryResultSetShortColumn getShortColumnByName(String columnName) { - int index = this.getColumnIndexByName(columnName); - return (QueryResultSetShortColumn) this.columns[index]; - } - - /** - * Gets a int column from the result set by index. - * - * @param index QueryResultSetIntColumn index (starting from 0) - * @return The int column - */ - public QueryResultSetIntColumn getIntColumnByIndex(int index) { - return (QueryResultSetIntColumn) this.columns[index]; - } - - /** - * Gets a int column from the result set by name. - * - * @param columnName QueryResultSetIntColumn name - * @return The int column - */ - public QueryResultSetIntColumn getIntColumnByName(String columnName) { - int index = this.getColumnIndexByName(columnName); - return (QueryResultSetIntColumn) this.columns[index]; - } - - /** - * Gets a long column from the result set by index. - * - * @param index QueryResultSetLongColumn index (starting from 0) - * @return The long column - */ - public QueryResultSetLongColumn getLongColumnByIndex(int index) { - return (QueryResultSetLongColumn) this.columns[index]; - } - - /** - * Gets a long column from the result set by name. - * - * @param columnName QueryResultSetLongColumn name - * @return The long column - */ - public QueryResultSetLongColumn getLongColumnByName(String columnName) { - int index = this.getColumnIndexByName(columnName); - return (QueryResultSetLongColumn) this.columns[index]; - } - - /** - * Gets a float column from the result set by index. - * - * @param index QueryResultSetFloatColumn index (starting from 0) - * @return The float column - */ - public QueryResultSetFloatColumn getFloatColumnByIndex(int index) { - return (QueryResultSetFloatColumn) this.columns[index]; - } - - /** - * Gets a float column from the result set by name. - * - * @param columnName QueryResultSetFloatColumn name - * @return The float column - */ - public QueryResultSetFloatColumn getFloatColumnByName(String columnName) { - int index = this.getColumnIndexByName(columnName); - return (QueryResultSetFloatColumn) this.columns[index]; - } - - /** - * Gets a double column from the result set by index. - * - * @param index QueryResultSetDoubleColumn index (starting from 0) - * @return The double column - */ - public QueryResultSetDoubleColumn getDoubleColumnByIndex(int index) { - return (QueryResultSetDoubleColumn) this.columns[index]; - } - - /** - * Gets a double column from the result set by name. - * - * @param columnName QueryResultSetDoubleColumn name - * @return The double column - */ - public QueryResultSetDoubleColumn getDoubleColumnByName(String columnName) { - int index = this.getColumnIndexByName(columnName); - return (QueryResultSetDoubleColumn) this.columns[index]; - } - - /** - * Gets an object column from the result set by index. - * - * @param <T> The Java class of the mapped MonetDB column - * @param index QueryResultSetObjectColumn index (starting from 0) - * @return The object column - */ - @SuppressWarnings("unchecked") - public <T> QueryResultSetObjectColumn<T> getObjectColumnByIndex(int index) { - return (QueryResultSetObjectColumn<T>) this.columns[index]; - } - - /** - * Gets an object column from the result set by name. - * - * @param <T> The Java class of the mapped MonetDB column - * @param columnName QueryResultSetObjectColumn name - * @return The object column - */ - @SuppressWarnings("unchecked") - public <T> QueryResultSetObjectColumn<T> getObjectColumnByName(String columnName) { - int index = this.getColumnIndexByName(columnName); - return (QueryResultSetObjectColumn<T>) this.columns[index]; - } - - /** - * Fetches rows from the result set. - * - * @param startIndex The first row index to retrieve - * @param endIndex The last row index to retrieve - * @return The rows as {@code AbstractRowSet} - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - public QueryResultRowSet fetchResultSetRows(int startIndex, int endIndex) throws MonetDBEmbeddedException { - if(endIndex < startIndex) { - int aux = startIndex; - startIndex = endIndex; - endIndex = aux; - } - if (startIndex < 0) { - throw new ArrayIndexOutOfBoundsException("The start index must be larger than 0!"); - } else if (endIndex > this.numberOfRows) { - throw new ArrayIndexOutOfBoundsException("The index must be smaller than the number of elements in the columns!"); - } else if(startIndex == endIndex) { - throw new ArrayIndexOutOfBoundsException("Retrieving 0 rows?"); - } - int numberOfRowsToRetrieve = endIndex - startIndex; - Object[][] temp = new Object[numberOfRowsToRetrieve][this.getNumberOfColumns()]; - for (int i = 0 ; i < this.getNumberOfColumns(); i++) { - Object[] nextColumn = this.columns[i].mapValuesToObjectArray(startIndex, endIndex); - for(int j = 0; j < numberOfRowsToRetrieve; j++) { - temp[j][i] = nextColumn[j]; - } - } - return new QueryResultRowSet(this, this.getMappings(), temp); - } - - /** - * Fetches rows from the result set asynchronously. - * - * @param startIndex The first row index to retrieve - * @param endIndex The last row index to retrieve - * @return The rows as {@code AbstractRowSet} - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - /*public CompletableFuture<AbstractRowSet> fetchResultSetRowsAsync(int startIndex, int endIndex) throws MonetDBEmbeddedException { - return CompletableFuture.supplyAsync(() -> this.fetchResultSetRows(startIndex, endIndex)); - }*/ - - /** - * Fetches the first N rows from the result set. - * - * @param n The last row index to retrieve - * @return The rows as {@code AbstractRowSet} - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - public QueryResultRowSet fetchFirstNRowValues(int n) throws MonetDBEmbeddedException { - return this.fetchResultSetRows(0, n); - } - - /** - * Fetches the first N rows from the result set asynchronously. - * - * @param n The last row index to retrieve - * @return The rows as {@code AbstractRowSet} - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - /*public CompletableFuture<AbstractRowSet> fetchFirstNRowValuesAsync(int n) throws MonetDBEmbeddedException { - return this.fetchResultSetRowsAsync(0, n); - }*/ - - /** - * Fetches all rows from the result set. - * - * @return The rows as {@code AbstractRowSet} - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - public QueryResultRowSet fetchAllRowValues() throws MonetDBEmbeddedException { - return this.fetchResultSetRows(0, this.numberOfRows); - } - - /** - * Fetches all rows from the result set asynchronously. - * - * @return The rows as {@code AbstractRowSet} - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - /*public CompletableFuture<AbstractRowSet> fetchAllRowValuesAsync() throws MonetDBEmbeddedException { - return this.fetchResultSetRowsAsync(0, this.numberOfRows); - }*/ - - @Override - public ListIterator<MonetDBRow> iterator() { - try { - return Arrays.asList(this.fetchAllRowValues().getAllRows()).listIterator(); - } catch (MonetDBEmbeddedException ex) { - return null; - } - } - - private native void cleanResultSet(long tablePointer); -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/resultset/QueryResultSetBooleanColumn.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.resultset; - -import nl.cwi.monetdb.embedded.env.MonetDBEmbeddedException; - -/** - * A MonetDB column converted to an array of Java boolean values. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public final class QueryResultSetBooleanColumn extends AbstractQueryResultSetColumn<boolean[]> { - - /** - * Gets MonetDB's boolean null constant - * - * @return MonetDB's boolean null constant - */ - public static native boolean GetBooleanNullConstant(); - - /** - * Due to restrictions on the representation of boolean values in the Java language, this method should be called - * to check if a boolean value is null or not. - * - * @param value The value to evaluate - * @return If the value is null or not - */ - public static native boolean CheckBooleanIsNull(boolean value); - - /** - * Array with the retrieved values. - */ - private final boolean[] values; - - protected QueryResultSetBooleanColumn(String columnType, long tablePointer, int resultSetIndex, String columnName, - int columnDigits, int columnScale, int numberOfRows) { - super(columnType, tablePointer, resultSetIndex, columnName, columnDigits, columnScale, numberOfRows); - if(!this.getMapping().getJavaClass().equals(Boolean.class)) { - throw new ClassCastException("The parameter must be of boolean type!!"); - } - this.values = new boolean[numberOfRows]; - } - - @Override - protected void fetchMoreData(int startIndex, int endIndex) throws MonetDBEmbeddedException { - this.fetchValuesInternal(this.tablePointer, this.resultSetIndex, startIndex, endIndex, this.values, this.nullValues); - } - - @Override - protected boolean[] storeNewDataAndGetResult(int startIndex, int numberOfRowsToRetrieve) { - boolean[] result = new boolean[numberOfRowsToRetrieve]; - System.arraycopy(this.values, startIndex, result, 0, numberOfRowsToRetrieve); - return result; - } - - @Override - protected Boolean[] mapValuesToObjectArrayImplementation(int startIndex, int numberOfRowsToRetrieve) { - Boolean[] res = new Boolean[numberOfRowsToRetrieve]; - int endIndex = startIndex + numberOfRowsToRetrieve; - for(int i = startIndex, j = 0 ; i < endIndex ; i++, j++) { - res[j] = (this.nullValues[i]) ? null : this.values[i]; - } - return res; - } - - /** - * Internal implementation to fetch values from the column. - */ - private native void fetchValuesInternal(long tablePointer, int resultSetIndex, int startIndex, int endIndex, - boolean[] values, boolean[] nullValues) throws MonetDBEmbeddedException; -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/resultset/QueryResultSetByteColumn.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.resultset; - -import nl.cwi.monetdb.embedded.env.MonetDBEmbeddedException; - -/** - * A MonetDB column converted to an array of Java byte values. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public final class QueryResultSetByteColumn extends AbstractQueryResultSetColumn<byte[]> { - - /** - * Gets MonetDB's byte null constant - * - * @return MonetDB's byte null constant - */ - public static native byte GetByteNullConstant(); - - /** - * Checks if the short value is null or not. - * - * @param value The value to evaluate - * @return If the short value is null or not. - */ - public static native boolean CheckByteIsNull(byte value); - - /** - * Array with the retrieved values. - */ - private final byte[] values; - - protected QueryResultSetByteColumn(String columnType, long tablePointer, int resultSetIndex, String columnName, - int columnDigits, int columnScale, int numberOfRows) { - super(columnType, tablePointer, resultSetIndex, columnName, columnDigits, columnScale, numberOfRows); - if(!this.getMapping().getJavaClass().equals(Byte.class)) { - throw new ClassCastException("The parameter must be of byte type!!"); - } - this.values = new byte[numberOfRows]; - } - - @Override - protected void fetchMoreData(int startIndex, int endIndex) throws MonetDBEmbeddedException { - this.fetchValuesInternal(this.tablePointer, this.resultSetIndex, startIndex, endIndex, this.values, this.nullValues); - } - - @Override - protected byte[] storeNewDataAndGetResult(int startIndex, int numberOfRowsToRetrieve) { - byte[] result = new byte[numberOfRowsToRetrieve]; - System.arraycopy(this.values, startIndex, result, 0, numberOfRowsToRetrieve); - return result; - } - - @Override - protected Byte[] mapValuesToObjectArrayImplementation(int startIndex, int numberOfRowsToRetrieve) { - Byte[] res = new Byte[numberOfRowsToRetrieve]; - int endIndex = startIndex + numberOfRowsToRetrieve; - for(int i = startIndex, j = 0 ; i < endIndex ; i++, j++) { - res[j] = (this.nullValues[i]) ? null : this.values[i]; - } - return res; - } - - /** - * Internal implementation to fetch values from the column. - */ - private native void fetchValuesInternal(long tablePointer, int resultSetIndex, int startIndex, int endIndex, - byte[] values, boolean[] nullValues) throws MonetDBEmbeddedException; -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/resultset/QueryResultSetDoubleColumn.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.resultset; - -import nl.cwi.monetdb.embedded.env.MonetDBEmbeddedException; - -/** - * A MonetDB column converted to an array of Java double values. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public final class QueryResultSetDoubleColumn extends AbstractQueryResultSetColumn<double[]> { - - /** - * Gets MonetDB's double null constant - * - * @return MonetDB's double null constant - */ - public static native double GetDoubleNullConstant(); - - /** - * Checks if the double value is null or not. - * - * @param value The value to evaluate - * @return If the double value is null or not. - */ - public static native boolean CheckDoubleIsNull(double value); - - /** - * Array with the retrieved values. - */ - private final double[] values; - - protected QueryResultSetDoubleColumn(String columnType, long tablePointer, int resultSetIndex, String columnName, - int columnDigits, int columnScale, int numberOfRows) { - super(columnType, tablePointer, resultSetIndex, columnName, columnDigits, columnScale, numberOfRows); - if(!this.getMapping().getJavaClass().equals(Double.class)) { - throw new ClassCastException("The parameter must be of double type!!"); - } - this.values = new double[numberOfRows]; - } - - @Override - protected void fetchMoreData(int startIndex, int endIndex) throws MonetDBEmbeddedException { - this.fetchValuesInternal(this.tablePointer, this.resultSetIndex, startIndex, endIndex, this.values, this.nullValues); - } - - @Override - protected double[] storeNewDataAndGetResult(int startIndex, int numberOfRowsToRetrieve) { - double[] result = new double[numberOfRowsToRetrieve]; - System.arraycopy(this.values, startIndex, result, 0, numberOfRowsToRetrieve); - return result; - } - - @Override - protected Double[] mapValuesToObjectArrayImplementation(int startIndex, int numberOfRowsToRetrieve) { - Double[] res = new Double[numberOfRowsToRetrieve]; - int endIndex = startIndex + numberOfRowsToRetrieve; - for(int i = startIndex, j = 0 ; i < endIndex ; i++, j++) { - res[j] = (this.nullValues[i]) ? null : this.values[i]; - } - return res; - } - - /** - * Internal implementation to fetch values from the column. - */ - private native void fetchValuesInternal(long tablePointer, int resultSetIndex, int startIndex, int endIndex, - double[] values, boolean[] nullValues) throws MonetDBEmbeddedException; -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/resultset/QueryResultSetFloatColumn.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.resultset; - -import nl.cwi.monetdb.embedded.env.MonetDBEmbeddedException; - -/** - * A MonetDB column converted to an array of Java float values. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public final class QueryResultSetFloatColumn extends AbstractQueryResultSetColumn<float[]> { - - /** - * Gets MonetDB's float null constant - * - * @return MonetDB's float null constant - */ - public static native float GetFloatNullConstant(); - - /** - * Checks if the float value is null or not. - * - * @param value The value to evaluate - * @return If the float value is null or not. - */ - public static native boolean CheckFloatIsNull(float value); - - /** - * Array with the retrieved values. - */ - private final float[] values; - - protected QueryResultSetFloatColumn(String columnType, long tablePointer, int resultSetIndex, String columnName, - int columnDigits, int columnScale, int numberOfRows) { - super(columnType, tablePointer, resultSetIndex, columnName, columnDigits, columnScale, numberOfRows); - if(!this.getMapping().getJavaClass().equals(Float.class)) { - throw new ClassCastException("The parameter must be of float type!!"); - } - this.values = new float[numberOfRows]; - } - - @Override - protected void fetchMoreData(int startIndex, int endIndex) throws MonetDBEmbeddedException { - this.fetchValuesInternal(this.tablePointer, this.resultSetIndex, startIndex, endIndex, this.values, this.nullValues); - } - - @Override - protected float[] storeNewDataAndGetResult(int startIndex, int numberOfRowsToRetrieve) { - float[] result = new float[numberOfRowsToRetrieve]; - System.arraycopy(this.values, startIndex, result, 0, numberOfRowsToRetrieve); - return result; - } - - @Override - protected Float[] mapValuesToObjectArrayImplementation(int startIndex, int numberOfRowsToRetrieve) { - Float[] res = new Float[numberOfRowsToRetrieve]; - int endIndex = startIndex + numberOfRowsToRetrieve; - for(int i = startIndex, j = 0 ; i < endIndex ; i++, j++) { - res[j] = (this.nullValues[i]) ? null : this.values[i]; - } - return res; - } - - /** - * Internal implementation to fetch values from the column. - */ - private native void fetchValuesInternal(long tablePointer, int resultSetIndex, int startIndex, int endIndex, - float[] values, boolean[] nullValues) throws MonetDBEmbeddedException; -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/resultset/QueryResultSetIntColumn.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.resultset; - -import nl.cwi.monetdb.embedded.env.MonetDBEmbeddedException; - -/** - * A MonetDB column converted to an array of Java integer values. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public final class QueryResultSetIntColumn extends AbstractQueryResultSetColumn<int[]> { - - /** - * Gets MonetDB's int null constant - * - * @return MonetDB's int null constant - */ - public static native int GetIntNullConstant(); - - /** - * Checks if the int value is null or not. - * - * @param value The value to evaluate - * @return If the int value is null or not. - */ - public static native boolean CheckIntIsNull(int value); - - /** - * Array with the retrieved values. - */ - private final int[] values; - - protected QueryResultSetIntColumn(String columnType, long tablePointer, int resultSetIndex, String columnName, - int columnDigits, int columnScale, int numberOfRows) { - super(columnType, tablePointer, resultSetIndex, columnName, columnDigits, columnScale, numberOfRows); - if(!this.getMapping().getJavaClass().equals(Integer.class)) { - throw new ClassCastException("The parameter must be of integer type!!"); - } - this.values = new int[numberOfRows]; - } - - @Override - protected void fetchMoreData(int startIndex, int endIndex) throws MonetDBEmbeddedException { - this.fetchValuesInternal(this.tablePointer, this.resultSetIndex, startIndex, endIndex, this.values, this.nullValues); - } - - @Override - protected int[] storeNewDataAndGetResult(int startIndex, int numberOfRowsToRetrieve) { - int[] result = new int[numberOfRowsToRetrieve]; - System.arraycopy(this.values, startIndex, result, 0, numberOfRowsToRetrieve); - return result; - } - - @Override - protected Integer[] mapValuesToObjectArrayImplementation(int startIndex, int numberOfRowsToRetrieve) { - Integer[] res = new Integer[numberOfRowsToRetrieve]; - int endIndex = startIndex + numberOfRowsToRetrieve; - for(int i = startIndex, j = 0 ; i < endIndex ; i++, j++) { - res[j] = (this.nullValues[i]) ? null : this.values[i]; - } - return res; - } - - /** - * Internal implementation to fetch values from the column. - */ - private native void fetchValuesInternal(long tablePointer, int resultSetIndex, int startIndex, int endIndex, - int[] values, boolean[] nullValues) throws MonetDBEmbeddedException; -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/resultset/QueryResultSetLongColumn.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.resultset; - -import nl.cwi.monetdb.embedded.env.MonetDBEmbeddedException; - -/** - * A MonetDB column converted to an array of Java long values. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public final class QueryResultSetLongColumn extends AbstractQueryResultSetColumn<long[]> { - - /** - * Gets MonetDB's long null constant - * - * @return MonetDB's long null constant - */ - public static native long GetLongNullConstant(); - - /** - * Checks if the long value is null or not. - * - * @param value The value to evaluate - * @return If the long value is null or not. - */ - public static native boolean CheckLongIsNull(long value); - - /** - * Array with the retrieved values. - */ - private final long[] values; - - protected QueryResultSetLongColumn(String columnType, long tablePointer, int resultSetIndex, String columnName, - int columnDigits, int columnScale, int numberOfRows) { - super(columnType, tablePointer, resultSetIndex, columnName, columnDigits, columnScale, numberOfRows); - if(!this.getMapping().getJavaClass().equals(Long.class)) { - throw new ClassCastException("The parameter must be of long type!!"); - } - this.values = new long[numberOfRows]; - } - - @Override - protected void fetchMoreData(int startIndex, int endIndex) throws MonetDBEmbeddedException { - this.fetchValuesInternal(this.tablePointer, this.resultSetIndex, startIndex, endIndex, this.values, this.nullValues); - } - - @Override - protected long[] storeNewDataAndGetResult(int startIndex, int numberOfRowsToRetrieve) { - long[] result = new long[numberOfRowsToRetrieve]; - System.arraycopy(this.values, startIndex, result, 0, numberOfRowsToRetrieve); - return result; - } - - @Override - protected Long[] mapValuesToObjectArrayImplementation(int startIndex, int numberOfRowsToRetrieve) { - Long[] res = new Long[numberOfRowsToRetrieve]; - int endIndex = startIndex + numberOfRowsToRetrieve; - for(int i = startIndex, j = 0 ; i < endIndex ; i++, j++) { - res[j] = (this.nullValues[i]) ? null : this.values[i]; - } - return res; - } - - /** - * Internal implementation to fetch values from the column. - */ - private native void fetchValuesInternal(long tablePointer, int resultSetIndex, int startIndex, int endIndex, - long[] values, boolean[] nullValues) throws MonetDBEmbeddedException; -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/resultset/QueryResultSetObjectColumn.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.resultset; - -import nl.cwi.monetdb.embedded.env.MonetDBEmbeddedException; - -import java.lang.reflect.Array; -import java.util.Arrays; -import java.util.ListIterator; - -/** - * A MonetDB column converted to an array of Java objects. - * - * @param <T> The Java class of the mapped MonetDB column - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public final class QueryResultSetObjectColumn<T> extends AbstractQueryResultSetColumn<T[]> implements Iterable<T> { - - /** - * A null pointer returning method. - * - * @return A null pointer - */ - public static <T> T GetObjectNullConstant() { return null; } - - /** - * Checks if the Object value is null or not. - * - * @param value The value to evaluate - * @return If the Object value is null or not. - */ - public static <T> boolean CheckObjectIsNull(T value) { return value == null; } - - /** - * Array with the retrieved values. - */ - private final T[] values; - - @SuppressWarnings("unchecked") - public QueryResultSetObjectColumn(String columnType, long tablePointer, int resultSetIndex, String columnName, - int columnDigits, int columnScale, int numberOfRows) { - super(columnType, tablePointer, resultSetIndex, columnName, columnDigits, columnScale, numberOfRows); - this.values = (T[]) Array.newInstance(this.mapping.getJavaClass(), numberOfRows); - } - - @Override - @SuppressWarnings("unchecked") - protected void fetchMoreData(int startIndex, int endIndex) throws MonetDBEmbeddedException { - this.fetchValuesInternal(this.tablePointer, this.resultSetIndex, (Class<T>) this.mapping.getJavaClass(), - this.mapping.ordinal(), startIndex, endIndex, this.values, this.nullValues); - } - - @Override - @SuppressWarnings("unchecked") - protected T[] storeNewDataAndGetResult(int startIndex, int numberOfRowsToRetrieve) { - T[] result = (T[]) Array.newInstance(this.mapping.getJavaClass(), numberOfRowsToRetrieve); - System.arraycopy(this.values, startIndex, result, 0, numberOfRowsToRetrieve); - return result; - } - - @Override - @SuppressWarnings("unchecked") - protected T[] mapValuesToObjectArrayImplementation(int startIndex, int numberOfRowsToRetrieve) { - T[] result = (T[]) Array.newInstance(this.mapping.getJavaClass(), numberOfRowsToRetrieve); - System.arraycopy(this.values, startIndex, result, 0, numberOfRowsToRetrieve); - return result; - } - - @Override - public ListIterator<T> iterator() { - try { - return Arrays.asList(this.fetchAllColumnValues()).listIterator(); - } catch (Exception ex) { - return null; - } - } - - /** - * Internal implementation to fetch values from the column. - */ - private native void fetchValuesInternal(long tablePointer, int resultSetIndex, Class<T> jClass, int javaIndex, - int startIndex, int endIndex, T[] values, boolean[] nullValues) - throws MonetDBEmbeddedException; -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/resultset/QueryResultSetShortColumn.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.resultset; - -import nl.cwi.monetdb.embedded.env.MonetDBEmbeddedException; - -/** - * A MonetDB column converted to an array of Java short values. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public final class QueryResultSetShortColumn extends AbstractQueryResultSetColumn<short[]> { - - /** - * Gets MonetDB's short null constant - * - * @return MonetDB's short null constant - */ - public static native short GetShortNullConstant(); - - /** - * Checks if the short value is null or not. - * - * @param value The value to evaluate - * @return If the short value is null or not. - */ - public static native boolean CheckShortIsNull(short value); - - /** - * Array with the retrieved values. - */ - private final short[] values; - - protected QueryResultSetShortColumn(String columnType, long tablePointer, int resultSetIndex, String columnName, - int columnDigits, int columnScale, int numberOfRows) { - super(columnType, tablePointer, resultSetIndex, columnName, columnDigits, columnScale, numberOfRows); - if(!this.getMapping().getJavaClass().equals(Short.class)) { - throw new ClassCastException("The parameter must be of short type!!"); - } - this.values = new short[numberOfRows]; - } - - @Override - protected void fetchMoreData(int startIndex, int endIndex) throws MonetDBEmbeddedException { - this.fetchValuesInternal(this.tablePointer, this.resultSetIndex, startIndex, endIndex, this.values, this.nullValues); - } - - @Override - protected short[] storeNewDataAndGetResult(int startIndex, int numberOfRowsToRetrieve) { - short[] result = new short[numberOfRowsToRetrieve]; - System.arraycopy(this.values, startIndex, result, 0, numberOfRowsToRetrieve); - return result; - } - - @Override - protected Short[] mapValuesToObjectArrayImplementation(int startIndex, int numberOfRowsToRetrieve) { - Short[] res = new Short[numberOfRowsToRetrieve]; - int endIndex = startIndex + numberOfRowsToRetrieve; - for(int i = startIndex, j = 0 ; i < endIndex ; i++, j++) { - res[j] = (this.nullValues[i]) ? null : this.values[i]; - } - return res; - } - - /** - * Internal implementation to fetch values from the column. - */ - private native void fetchValuesInternal(long tablePointer, int resultSetIndex, int startIndex, int endIndex, - short[] values, boolean[] nullValues) throws MonetDBEmbeddedException; -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/resultset/UpdateResultSet.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.resultset; - -import nl.cwi.monetdb.embedded.env.AbstractConnectionResult; -import nl.cwi.monetdb.embedded.env.MonetDBEmbeddedConnection; - -/** - * The result set from a sendUpdate method from a connection. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public class UpdateResultSet extends AbstractConnectionResult { - - protected UpdateResultSet(MonetDBEmbeddedConnection connection) { super(connection); } - - /** - * Close this result set. - */ - @Override - public void closeImplementation() {} -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/tables/IMonetDBTableBaseIterator.java +++ /dev/null @@ -1,25 +0,0 @@ -package nl.cwi.monetdb.embedded.tables; - -/** - * The base interface for iterating a MonetDB Table. The use can specify which rows to iterate in this interface. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public interface IMonetDBTableBaseIterator { - - /** - * Specify the first row in the table to iterate starting from 0. If a lower number is provided, then the iteration - * will start on the first row. - * - * @return The first row in the table to iterate - */ - int getFirstRowToIterate(); - - /** - * Specify the last row in the table to iterate. If a number larger than the number of rows is provided, then the - * iteration will end on the last row of the table. - * - * @return The last row in the table to iterate - */ - int getLastRowToIterate(); -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/tables/IMonetDBTableCursor.java +++ /dev/null @@ -1,16 +0,0 @@ -package nl.cwi.monetdb.embedded.tables; - -/** - * A row iterator for a MonetDB table. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public interface IMonetDBTableCursor extends IMonetDBTableBaseIterator { - - /** - * The business logic for the iterator. - * - * @param nextRow The next row in the iteration. - */ - void processNextRow(RowIterator nextRow); -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/tables/MonetDBTable.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.tables; - -import nl.cwi.monetdb.embedded.env.MonetDBEmbeddedException; -import nl.cwi.monetdb.embedded.mapping.AbstractResultTable; -import nl.cwi.monetdb.embedded.env.MonetDBEmbeddedConnection; -import nl.cwi.monetdb.embedded.mapping.MonetDBRow; -import nl.cwi.monetdb.embedded.mapping.MonetDBToJavaMapping; -import nl.cwi.monetdb.embedded.resultset.QueryResultSet; -import nl.cwi.monetdb.embedded.resultset.QueryResultSetLongColumn; - -/** - * Java representation of a MonetDB table. It's possible to perform several CRUD operations using the respective - * provided interfaces. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public final class MonetDBTable extends AbstractResultTable { - - private final String tableSchema; - - private final String tableName; - - protected MonetDBTable(MonetDBEmbeddedConnection connection, String tableSchema, String tableName) { - super(connection); - this.tableSchema = tableSchema; - this.tableName = tableName; - } - - @Override - public native int getNumberOfColumns(); - - /** - * Gets the current number of rows in the table, or -1 if an error in the database has occurred. - * - * @return The number of rows in the table. - */ - @Override - public int getNumberOfRows() { - int res; - try { - String query = "SELECT COUNT(*) FROM " + this.getTableSchema() + "." + this.getTableName() + ";"; - QueryResultSet eqr = this.getConnection().sendQuery(query); - QueryResultSetLongColumn eqc = eqr.getLongColumnByIndex(0); - res = (int) eqc.fetchFirstNColumnValues(1)[0]; - eqr.close(); - } catch (MonetDBEmbeddedException ex) { - res = -1; - } - return res; - } - - @Override - public native String[] getColumnNames(); - - @Override - public native String[] getColumnTypes(); - - @Override - public native MonetDBToJavaMapping[] getMappings(); - - @Override - public native int[] getColumnDigits(); - - @Override - public native int[] getColumnScales(); - - /** - * Gets the table schema name. - * - * @return The table schema name - */ - public String getTableSchema() { return this.tableSchema; } - - /** - * Gets the table name. - * - * @return The table name - */ - public String getTableName() { return this.tableName; } - - /** - * Gets the columns nullable indexes as an array. - * - * @return The columns nullable indexes as an array - */ - public native boolean[] getColumnNullableIndexes(); - - /** - * Gets the columns default values in an array. - * - * @return The columns default values in an array - */ - public native String[] getColumnDefaultValues(); - - /** - * Gets a column metadata by index. - * - * @param index The column index (starting from 0) - * @return The column metadata, {@code null} if index not in bounds - */ - public native MonetDBTableColumn getColumnMetadataByIndex(int index); - - /** - * Gets a column metadata by name. - * - * @param name The column name - * @return The column metadata, {@code null} if not found - */ - public native MonetDBTableColumn getColumnMetadataByName(String name); - - /** - * Gets all columns metadata. - * - * @return An array instance of columns metadata - */ - public native MonetDBTableColumn[] getAllColumnsMetadata(); - - /** - * Private method to check the limits of iteration. - * - * @param iterator The iterator to check - * @return An integer array with the limits fixed - */ - private int[] prepareIterator(IMonetDBTableBaseIterator iterator) { - int[] res = {iterator.getFirstRowToIterate(), iterator.getLastRowToIterate()}; - if(res[1] < res[0]) { - int aux = res[0]; - res[0] = res[1]; - res[0] = aux; - } - if (res[0] < 0) { - res[0] = 0; - } - int numberOfRows = this.getNumberOfRows(); - if (res[1] >= numberOfRows) { - res[1] = numberOfRows; - } - return res; - } - - /** - * Iterate over the table using a {@link IMonetDBTableCursor} instance. - * - * @param cursor The iterator with the business logic - * @return The number of rows iterated - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - public int iterateTable(IMonetDBTableCursor cursor) throws MonetDBEmbeddedException { - int[] limits = this.prepareIterator(cursor); - int res = 0, total = limits[1] - limits[0]; - String query = "SELECT * FROM " + this.getTableSchema() + "." + this.getTableName() + " LIMIT " + total - + " OFFSET " + limits[0] + ";"; - - QueryResultSet eqr = this.getConnection().sendQuery(query); - MonetDBRow[] array = eqr.fetchAllRowValues().getAllRows(); - eqr.close(); - Object[][] data = new Object[eqr.getNumberOfRows()][this.getNumberOfColumns()]; - for(int i = 0 ; i < eqr.getNumberOfRows() ; i++) { - data[i] = array[i].getAllColumns(); - } - - RowIterator ri = new RowIterator(this, data, limits[0], limits[1]); - while(ri.hasMore()) { - cursor.processNextRow(ri); - ri.setNextIteration(); - res++; - } - return res; - } - - /** - * Appends new rows to the table column-wise. - * - * @param data An array of columns to append - * @return The number of rows appended - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - public int appendColumns(Object[] data) throws MonetDBEmbeddedException { - MonetDBToJavaMapping[] mappings = this.getMappings(); - if (data.length != mappings.length) { - throw new ArrayStoreException("The number of columns between the data nad the classes is not consistent!"); - } - if (mappings.length != this.getNumberOfColumns()) { - throw new ArrayStoreException("The number of columns between data and the table is not consistent!"); - } - int[] javaIndexes = new int[mappings.length]; - Class<?>[] javaClasses = new Class<?>[mappings.length]; - for (int i = 0; i < mappings.length; i++) { - javaIndexes[i] = mappings[i].ordinal(); - javaClasses[i] = mappings[i].getJavaClass(); - } - return this.appendColumnsInternal(data, javaIndexes, javaClasses); - } - - /* - * Appends new rows to the table column-wise and asynchronously. - * - * @param data An array of columns to append - * @return The number of rows appended - * @throws MonetDBEmbeddedException If an error in the database occurred - */ - /*public CompletableFuture<Integer> appendColumnsAsync(Object[] data) throws MonetDBEmbeddedException { - return CompletableFuture.supplyAsync(() -> this.appendColumns(data)); - }*/ - - @Override - protected void closeImplementation() {} - - private native int appendColumnsInternal(Object[] data, int[] javaIndexes, Class<?>[] javaClasses) - throws MonetDBEmbeddedException; -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/tables/MonetDBTableColumn.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.tables; - -import nl.cwi.monetdb.embedded.mapping.AbstractColumn; - -/** - * Java representation of a MonetDB table column. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public class MonetDBTableColumn extends AbstractColumn { - - /** - * If the column has a default value. - */ - private final String defaultValue; - - /** - * If the column is Nullable. - */ - private final boolean isNullable; - - protected MonetDBTableColumn(String columnType, String columnName, int columnDigits, int columnScale, - String defaultValue, boolean isNullable) { - super(columnType, columnName, columnDigits, columnScale); - this.defaultValue = defaultValue; - this.isNullable = isNullable; - } - - /** - * Get the default value if there is one, or null if none. - * - * @return The default value if there is one, or null if none - */ - public String getDefaultValue() { return this.defaultValue; } - - /** - * Get the indication if the column is nullable. - * - * @return The indication if the column is nullable - */ - public boolean isNullable() { return this.isNullable; } -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/tables/RowIterator.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - * - * Copyright 2016 MonetDB B.V. - */ - -package nl.cwi.monetdb.embedded.tables; - -import nl.cwi.monetdb.embedded.mapping.AbstractRowSet; -import nl.cwi.monetdb.embedded.mapping.MonetDBRow; - -/** - * The iterator class for a MonetDB table. It's possible to inspect the current currentColumns in the row as well - * their mappings. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public class RowIterator extends AbstractRowSet { - - /** - * The current table row number on the fetched set. - */ - private int currentIterationNumber = 0; - - /** - * The first row in the table to iterate. - */ - private final int firstIndex; - - /** - * The last row in the table to iterate. - */ - private final int lastIndex; - - RowIterator(MonetDBTable table, Object[][] rows, int firstIndex, int lastIndex) { - super(table, table.getMappings(), rows); - this.firstIndex = firstIndex; - this.lastIndex = lastIndex; - } - - @Override - public int getColumnIndexByName(String columnName) { - String[] columnNames = this.getTable().getColumnNames(); - int index = 0; - for (String colName : columnNames) { - if (columnName.equals(colName)) { - return this.getColumnByIndex(index); - } - index++; - } - throw new ArrayIndexOutOfBoundsException("The column is not present in the result set!"); - } - - /** - * Gets the original table of this iterator. - * - * @return The original table of this iterator - */ - public MonetDBTable getTable() { return (MonetDBTable) this.getQueryResultTable(); } - - /** - * Gets the first index used on this iteration. - * - * @return The first index used on this iteration - */ - public int getFirstIndex() { return firstIndex; } - - /** - * Gets the last index used on this iteration. - * - * @return The last index used on this iteration - */ - public int getLastIndex() { return lastIndex; } - - /** - * Gets the current iteration number. - * - * @return The current iteration number - */ - public int getCurrentIterationNumber() { return currentIterationNumber; } - - /** - * Gets the current row number of the table in the iteration. - * - * @return The current row number of the table in the iteration - */ - public int getCurrentTableRowNumber() { return this.firstIndex + this.currentIterationNumber; } - - /** - * Gets the current row currentColumns values as Java objects. - * - * @return The current row currentColumns values as Java objects - */ - public MonetDBRow getCurrentRow() { return this.rows[this.currentIterationNumber]; } - - /** - * Checks if there are more rows to iterate after the current one. - * - * @return There are more rows to iterate - */ - public boolean hasMore() { return this.firstIndex + this.currentIterationNumber < this.lastIndex; } - - /** - * Gets a column value as a Java class. - * - * @param <T> A Java class mapped to a MonetDB data type - * @param index The index of the column - * @param javaClass The Java class - * @return The column value as a Java class - */ - public <T> T getColumnByIndex(int index, Class<T> javaClass) { - return javaClass.cast(this.getCurrentRow().getColumnByIndex(index, javaClass)); - } - - /** - * Gets a column value as a Java class using the default mapping. - * - * @param <T> A Java class mapped to a MonetDB data type - * @param index The index of the column - * @return The column value as a Java class - */ - public <T> T getColumnByIndex(int index) { - Class<T> javaClass = this.mappings[index].getJavaClass(); - return javaClass.cast(this.getCurrentRow().getColumnByIndex(index)); - } - - /** - * Gets a column value as a Java class. - * - * @param <T> A Java class mapped to a MonetDB data type - * @param columnName The name of the column - * @param javaClass The Java class - * @return The column value as a Java class - */ - public <T> T getColumnByName(String columnName, Class<T> javaClass) { - int index = this.getColumnIndexByName(columnName); - return this.getColumnByIndex(index, javaClass); - } - - /** - * Gets a column value as a Java class using the default mapping. - * - * @param <T> A Java class mapped to a MonetDB data type - * @param columnName The name of the column - * @return The column value as a Java class - */ - public <T> T getColumnByName(String columnName) { - int index = this.getColumnIndexByName(columnName); - return this.getColumnByIndex(index); - } - - /** - * Sets the next value to iterate. - */ - void setNextIteration() { this.currentIterationNumber++; } -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/embedded/utils/StringEscaper.java +++ /dev/null @@ -1,19 +0,0 @@ -package nl.cwi.monetdb.embedded.utils; - -/** - * An util class to escape Java Strings to avoid SQL Injection and other problems with SQL queries. - * - * @author <a href="mailto:pedro.ferreira@monetdbsolutions.com">Pedro Ferreira</a> - */ -public class StringEscaper { - - /** - * Escapes a Java String for usage in SQL queries. - * - * @param input The String to escape - * @return The input String escaped - */ - public static String SQLStringEscape(String input) { - return "'" + input.replaceAll("\\\\", "\\\\\\\\").replaceAll("'", "\\\\'") + "'"; - } -}
--- a/src/main/java/nl/cwi/monetdb/jdbc/MonetConnection.java +++ b/src/main/java/nl/cwi/monetdb/jdbc/MonetConnection.java @@ -3,7 +3,6 @@ package nl.cwi.monetdb.jdbc; import nl.cwi.monetdb.jdbc.types.INET; import nl.cwi.monetdb.jdbc.types.URL; import nl.cwi.monetdb.mcl.connection.*; -import nl.cwi.monetdb.mcl.connection.helpers.Debugger; import nl.cwi.monetdb.mcl.connection.SenderThread; import nl.cwi.monetdb.mcl.connection.mapi.MapiLanguage; import nl.cwi.monetdb.mcl.protocol.ProtocolException; @@ -88,10 +87,6 @@ public abstract class MonetConnection ex /** Whether or not BLOB is mapped to BINARY within the driver */ private final boolean blobIsBinary; - protected boolean isDebugging; - - private Debugger ourSavior; - protected AbstractProtocol protocol; /** @@ -102,13 +97,12 @@ public abstract class MonetConnection ex * @throws IOException if an error occurs */ public MonetConnection(Properties props, String database, String hash, IMonetDBLanguage language, - boolean blobIsBinary, boolean isDebugging) throws IOException { + boolean blobIsBinary) throws IOException { this.conn_props = props; this.database = database; this.hash = hash; this.language = language; this.blobIsBinary = blobIsBinary; - this.isDebugging = isDebugging; } public IMonetDBLanguage getLanguage() { @@ -119,18 +113,6 @@ public abstract class MonetConnection ex this.closed = closed; } - public boolean isDebugging() { - return isDebugging; - } - - public void setDebugging(String filename) throws IOException { - ourSavior = new Debugger(filename); - } - - public Debugger getOurSavior() { - return ourSavior; - } - public AbstractProtocol getProtocol() { return this.protocol; } @@ -170,7 +152,7 @@ public abstract class MonetConnection ex * Calling the method close on a Connection object that is already closed is a no-op. */ @Override - public void close() { + public synchronized void close() { for (Statement st : statements.keySet()) { try { st.close(); @@ -178,14 +160,6 @@ public abstract class MonetConnection ex // better luck next time! } } - //close the debugger - try { - if (ourSavior != null) { - ourSavior.close(); - } - } catch (IOException e) { - // ignore it - } // close the socket or the embedded server try { this.closeUnderlyingConnection();
copy from src/main/java/nl/cwi/monetdb/jdbc/MonetDriver.java copy to src/main/java/nl/cwi/monetdb/jdbc/MonetDriver.java.in --- a/src/main/java/nl/cwi/monetdb/jdbc/MonetDriver.java +++ b/src/main/java/nl/cwi/monetdb/jdbc/MonetDriver.java.in @@ -8,8 +8,13 @@ package nl.cwi.monetdb.jdbc; -import nl.cwi.monetdb.mcl.connection.MonetDBConnectionFactory; +import nl.cwi.monetdb.mcl.connection.MCLException; +import nl.cwi.monetdb.mcl.connection.mapi.MapiConnection; +import nl.cwi.monetdb.mcl.connection.mapi.MapiLanguage; +import nl.cwi.monetdb.mcl.protocol.ProtocolException; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.net.URISyntaxException; import java.sql.Connection; @@ -49,21 +54,23 @@ final public class MonetDriver implement /** The prefix of a MonetDB url */ private static final String MONETURL = "jdbc:monetdb://"; /** Major version of this driver */ - private static final int DRIVERMAJOR = 4; + private static final int DRIVERMAJOR = @JDBC_MAJOR@; /** Minor version of this driver */ - private static final int DRIVERMINOR = 1; + private static final int DRIVERMINOR = @JDBC_MINOR@; + /** Version suffix string */ - private static final String DRIVERVERSIONSUFFIX = "@JDBC_VER_SUFFIX@ based on MCL v@MCL_MAJOR@.@MCL_MINOR@"; + private static final String DRIVERVERSIONSUFFIX = + "@JDBC_VER_SUFFIX@ based on MCL v@MCL_MAJOR@.@MCL_MINOR@"; // We're not fully compliant, but what we support is compliant /** Whether this driver is JDBC compliant or not */ private static final boolean MONETJDBCCOMPLIANT = false; /** MonetDB default port to connect to */ - private static final String PORT = "50000"; + private static final String PORT = "@JDBC_DEF_PORT@"; - public static String getPORT() { - return PORT; - } + private static final ClassLoader MonetDBClassLoader = MonetDriver.class.getClassLoader(); + + private static Class EmbeddedConnectionClass = null; // initialize this class: register it at the DriverManager // Chapter 9.2 from Sun JDBC 3.0 specification @@ -90,78 +97,6 @@ final public class MonetDriver implement } /** - * Attempts to make a database connection to the given URL. The driver - * should return "null" if it realizes it is the wrong kind of driver to - * connect to the given URL. This will be common, as when the JDBC driver - * manager is asked to connect to a given URL it passes the URL to each - * loaded driver in turn. - * - * The driver should throw an SQLException if it is the right driver to - * connect to the given URL but has trouble connecting to the database. - * - * The java.util.Properties argument can be used to pass arbitrary string - * tag/value pairs as connection arguments. Normally at least "user" and - * "password" properties should be included in the Properties object. - * - * @param url the URL of the database to which to connect - * @param info a list of arbitrary string tag/value pairs as connection - * arguments. Normally at least a "user" and "password" property - * should be included - * @return a Connection object that represents a connection to the URL - * @throws SQLException if a database access error occurs - */ - public Connection connect(String url, Properties info) throws SQLException { - int tmp; - Properties props = new Properties(); - props.put("port", PORT); - props.putAll(info); - info = props; - - // url should be of style jdbc:monetdb://<host>/<database> - if (!acceptsURL(url)) - throw new SQLException("Invalid URL: it does not start with: " + MONETURL, "08M26"); - - // remove leading "jdbc:" so the rest is a valid hierarchical URI - URI uri; - try { - uri = new URI(url.substring(5)); - } catch (URISyntaxException e) { - throw new SQLException(e.toString(), "08M26"); - } - - String uri_host = uri.getHost(); - if (uri_host == null) - throw new SQLException("Invalid URL: no hostname given or unparsable in '" + url + "'", "08M26"); - info.put("host", uri_host); - - int uri_port = uri.getPort(); - if (uri_port > 0) - info.put("port", "" + uri_port); - - // check the database - String uri_path = uri.getPath(); - if (uri_path != null && uri_path.length() != 0) { - uri_path = uri_path.substring(1); - if (!uri_path.trim().isEmpty()) - info.put("database", uri_path); - } - - String uri_query = uri.getQuery(); - if (uri_query != null) { - // handle additional arguments - String args[] = uri_query.split("&"); - for (String arg : args) { - tmp = arg.indexOf('='); - if (tmp > 0) - info.put(arg.substring(0, tmp), arg.substring(tmp + 1)); - } - } - - // finally return the Connection as requested - return MonetDBConnectionFactory.CreateMonetDBJDBCConnection(info); - } - - /** * Retrieves the driver's major version number. Initially this should be 1. * * @return this driver's major version number @@ -210,16 +145,6 @@ final public class MonetDriver implement prop.description = "The password to use when authenticating on the database server"; props.add(prop); - prop = new DriverPropertyInfo("debug", "false"); - prop.required = false; - prop.description = "Whether or not to create a log file for debugging purposes"; - props.add(prop); - - prop = new DriverPropertyInfo("logfile", ""); - prop.required = false; - 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."; - props.add(prop); - prop = new DriverPropertyInfo("language", "sql"); prop.required = false; prop.description = "What language to use for MonetDB conversations (experts only)"; @@ -393,4 +318,219 @@ final public class MonetDriver implement public Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException("java.util.logging not in use", "0A000"); } + + /** + * Attempts to make a database connection to the given URL. The driver + * should return "null" if it realizes it is the wrong kind of driver to + * connect to the given URL. This will be common, as when the JDBC driver + * manager is asked to connect to a given URL it passes the URL to each + * loaded driver in turn. + * + * The driver should throw an SQLException if it is the right driver to + * connect to the given URL but has trouble connecting to the database. + * + * The java.util.Properties argument can be used to pass arbitrary string + * tag/value pairs as connection arguments. Normally at least "user" and + * "password" properties should be included in the Properties object. + * + * @param url the URL of the database to which to connect + * @param info a list of arbitrary string tag/value pairs as connection + * arguments. Normally at least a "user" and "password" property + * should be included + * @return a Connection object that represents a connection to the URL + * @throws SQLException if a database access error occurs + */ + public Connection connect(String url, Properties info) throws SQLException { + int tmp; + Properties props = new Properties(); + props.put("port", PORT); + props.putAll(info); + info = props; + + // url should be of style jdbc:monetdb://<host>/<database> + if (!acceptsURL(url)) + throw new SQLException("Invalid URL: it does not start with: " + MONETURL, "08M26"); + + // remove leading "jdbc:" so the rest is a valid hierarchical URI + URI uri; + try { + uri = new URI(url.substring(5)); + } catch (URISyntaxException e) { + throw new SQLException(e.toString(), "08M26"); + } + + String uri_host = uri.getHost(); + if (uri_host == null) + throw new SQLException("Invalid URL: no hostname given or unparsable in '" + url + "'", "08M26"); + info.put("host", uri_host); + + int uri_port = uri.getPort(); + if (uri_port > 0) + info.put("port", "" + uri_port); + + // check the database + String uri_path = uri.getPath(); + if (uri_path != null && uri_path.length() != 0) { + uri_path = uri_path.substring(1); + if (!uri_path.trim().isEmpty()) + info.put("database", uri_path); + } + + String uri_query = uri.getQuery(); + if (uri_query != null) { + // handle additional arguments + String args[] = uri_query.split("&"); + for (String arg : args) { + tmp = arg.indexOf('='); + if (tmp > 0) + info.put(arg.substring(0, tmp), arg.substring(tmp + 1)); + } + } + + // finally return the Connection as requested + return CreateMonetDBJDBCConnection(info); + } + + @SuppressWarnings("unchecked") + private static MonetConnection CreateMonetDBJDBCConnection(Properties props) throws SQLException, + IllegalArgumentException { + MonetConnection res; + + boolean isEmbedded = Boolean.parseBoolean(props.getProperty("embedded", "false")); + boolean blobIsBinary = Boolean.valueOf(props.getProperty("treat_blob_as_binary", "false")); + String language = props.getProperty("language", "sql"); + String username = props.getProperty("user", null); + String password = props.getProperty("password", null); + String database = props.getProperty("database"); + if (database == null || database.trim().isEmpty()) + throw new IllegalArgumentException("database should not be null or empty"); + String hash = props.getProperty("hash"); + int sockTimeout = 0; + + //instantiate the connection + if(isEmbedded) { + String directory = props.getProperty("directory"); + if (directory == null || directory.trim().isEmpty()) + throw new IllegalArgumentException("directory should not be null or empty"); + try { + if(EmbeddedConnectionClass != null) { + EmbeddedConnectionClass = MonetDBClassLoader + .loadClass("nl.cwi.monetdb.embedded.jdbc.EmbeddedConnection"); + } + if(EmbeddedConnectionClass == null) { + throw new SQLException("EmbeddedConnection Class not found!"); + } + + res = (MonetConnection) EmbeddedConnectionClass + .getDeclaredConstructor(Properties.class, String.class, String.class, Boolean.TYPE, String.class) + .newInstance(props, database, hash, language, blobIsBinary, directory); + } catch (InvocationTargetException | InstantiationException | IllegalAccessException | + NoSuchMethodException | ClassNotFoundException e) { + throw new SQLException(e); + } + } else { + String hostname = props.getProperty("host"); + if (hostname == null || hostname.trim().isEmpty()) + throw new IllegalArgumentException("hostname should not be null or empty"); + if (username == null || username.trim().isEmpty()) + throw new IllegalArgumentException("user should not be null or empty"); + if (password == null || password.trim().isEmpty()) + throw new IllegalArgumentException("password should not be null or empty"); + + boolean negative1 = false, failedparse1 = false; + int port = 0; + try { + port = Integer.parseInt(props.getProperty("port")); + } catch (NumberFormatException e) { + failedparse1 = true; + props.setProperty("port", PORT); + } + if (port <= 0) { + negative1 = true; + port = Integer.parseInt(PORT); + props.setProperty("port", PORT); + } + + String timeout = props.getProperty("so_timeout", "0"); + boolean negative2 = false, failedparse2 = false; + try { + sockTimeout = Integer.parseInt(timeout); + } catch (NumberFormatException e) { + sockTimeout = 0; + failedparse2 = true; + props.setProperty("so_timeout", "0"); + } + if (sockTimeout < 0) { + negative2 = true; + sockTimeout = 0; + props.setProperty("so_timeout", "0"); + } + try { + res = new MapiConnection(props, database, hash, language, blobIsBinary, hostname, port); + } catch (IOException e) { + throw new SQLException(e); + } + if(failedparse1) { + res.addWarning("Unable to parse port number from: " + port, "M1M05"); + } + if(negative1) { + res.addWarning("Negative port not allowed. Value ignored", "M1M05"); + } + if(failedparse2) { + res.addWarning("Unable to parse socket timeout number from: " + timeout, "M1M05"); + } + if(negative2) { + res.addWarning("Negative socket timeout not allowed. Value ignored", "M1M05"); + } + res.setSoTimeout(sockTimeout); + } + + try { + List<String> warnings = res.connect(username, password); + if(warnings != null) { + for (String warning : warnings) { + res.addWarning(warning, "01M02"); + } + } + // apply NetworkTimeout value from legacy (pre 4.1) driver so_timeout calls + if(!isEmbedded) { + res.setSoTimeout(sockTimeout); + } + } catch (IOException e) { + if(!isEmbedded) { + MapiConnection con = (MapiConnection) res; + throw new SQLException("Unable to connect (" + con.getHostname() + ":" + + con.getPort() + "): " + e.getMessage(), "08006"); + } else { + throw new SQLException("Unable to connect the provided directory : " + e.getMessage(), "08006"); + } + } catch (ProtocolException e) { + throw new SQLException(e.getMessage(), "08001"); + } catch (MCLException e) { + String[] connex = e.getMessage().split("\n"); + SQLException sqle = new SQLException(connex[0], "08001", e); + for (int i = 1; i < connex.length; i++) { + sqle.setNextException(new SQLException(connex[1], "08001")); + } + throw sqle; + } + + //set the timezone + if (res.getLanguage() == MapiLanguage.LANG_SQL) { + // enable auto commit + res.setAutoCommit(true); + // set our time zone on the server + Calendar cal = Calendar.getInstance(); + int offset = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET); + offset /= (60 * 1000); // milliseconds to minutes + String tz = offset < 0 ? "-" : "+"; + tz += (Math.abs(offset) / 60 < 10 ? "0" : "") + (Math.abs(offset) / 60) + ":"; + offset -= (offset / 60) * 60; + tz += (offset < 10 ? "0" : "") + offset; + + res.sendIndependentCommand("SET TIME ZONE INTERVAL '" + tz + "' HOUR TO MINUTE"); + } + + return res; + } }
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/mcl/connection/MonetDBConnectionFactory.java +++ /dev/null @@ -1,175 +0,0 @@ -package nl.cwi.monetdb.mcl.connection; - -import nl.cwi.monetdb.jdbc.MonetConnection; -import nl.cwi.monetdb.jdbc.MonetDriver; -import nl.cwi.monetdb.mcl.connection.embedded.EmbeddedConnection; -import nl.cwi.monetdb.mcl.connection.mapi.MapiConnection; -import nl.cwi.monetdb.mcl.connection.mapi.MapiLanguage; -import nl.cwi.monetdb.mcl.protocol.ProtocolException; - -import java.io.File; -import java.io.IOException; -import java.sql.SQLException; -import java.util.Calendar; -import java.util.List; -import java.util.Properties; - -/** - * Created by ferreira on 12/1/16. - */ -public final class MonetDBConnectionFactory { - - public static MonetConnection CreateMonetDBJDBCConnection(Properties props) - throws SQLException, IllegalArgumentException { - MonetConnection res; - - boolean isEmbedded = Boolean.parseBoolean(props.getProperty("embedded", "false")); - boolean debug = Boolean.valueOf(props.getProperty("debug", "false")); - boolean blobIsBinary = Boolean.valueOf(props.getProperty("treat_blob_as_binary", "false")); - String language = props.getProperty("language", "sql"); - - String username = props.getProperty("user", null); - String password = props.getProperty("password", null); - String database = props.getProperty("database"); - if (database == null || database.trim().isEmpty()) - throw new IllegalArgumentException("database should not be null or empty"); - String hash = props.getProperty("hash"); - int sockTimeout = 0; - - //instantiate the connection - if(isEmbedded) { - String directory = props.getProperty("directory"); - if (directory == null || directory.trim().isEmpty()) - throw new IllegalArgumentException("directory should not be null or empty"); - try { - res = new EmbeddedConnection(props, database, hash, language, blobIsBinary, debug, directory); - } catch (IOException e) { - throw new SQLException(e); - } - } else { - String hostname = props.getProperty("host"); - if (hostname == null || hostname.trim().isEmpty()) - throw new IllegalArgumentException("hostname should not be null or empty"); - if (username == null || username.trim().isEmpty()) - throw new IllegalArgumentException("user should not be null or empty"); - if (password == null || password.trim().isEmpty()) - throw new IllegalArgumentException("password should not be null or empty"); - - boolean negative1 = false, failedparse1 = false; - int port = 0; - try { - port = Integer.parseInt(props.getProperty("port")); - } catch (NumberFormatException e) { - failedparse1 = true; - props.setProperty("port", MonetDriver.getPORT()); - } - if (port <= 0) { - negative1 = true; - port = Integer.parseInt(MonetDriver.getPORT()); - props.setProperty("port", MonetDriver.getPORT()); - } - - String timeout = props.getProperty("so_timeout", "0"); - boolean negative2 = false, failedparse2 = false; - try { - sockTimeout = Integer.parseInt(timeout); - } catch (NumberFormatException e) { - sockTimeout = 0; - failedparse2 = true; - props.setProperty("so_timeout", "0"); - } - if (sockTimeout < 0) { - negative2 = true; - sockTimeout = 0; - props.setProperty("so_timeout", "0"); - } - try { - res = new MapiConnection(props, database, hash, language, blobIsBinary, debug, hostname, port); - } catch (IOException e) { - throw new SQLException(e); - } - if(failedparse1) { - res.addWarning("Unable to parse port number from: " + port, "M1M05"); - } - if(negative1) { - res.addWarning("Negative port not allowed. Value ignored", "M1M05"); - } - if(failedparse2) { - res.addWarning("Unable to parse socket timeout number from: " + timeout, "M1M05"); - } - if(negative2) { - res.addWarning("Negative socket timeout not allowed. Value ignored", "M1M05"); - } - res.setSoTimeout(sockTimeout); - } - //initialize the debugging stuff if so - if (debug) { - try { - String fname = props.getProperty("logfile", "monet_" + - System.currentTimeMillis() + ".log"); - File f = new File(fname); - int ext = fname.lastIndexOf('.'); - if (ext < 0) ext = fname.length(); - String pre = fname.substring(0, ext); - String suf = fname.substring(ext); - for (int i = 1; f.exists(); i++) { - f = new File(pre + "-" + i + suf); - } - res.setDebugging(f.getAbsolutePath()); - } catch (IOException ex) { - throw new SQLException("Opening logfile failed: " + ex.getMessage(), "08M01"); - } - } - - try { - List<String> warnings = res.connect(username, password); - if(warnings != null) { - for (String warning : warnings) { - res.addWarning(warning, "01M02"); - } - } - // apply NetworkTimeout value from legacy (pre 4.1) driver so_timeout calls - if(!isEmbedded) { - res.setSoTimeout(sockTimeout); - } - } catch (IOException e) { - if(!isEmbedded) { - MapiConnection con = (MapiConnection) res; - throw new SQLException("Unable to connect (" + con.getHostname() + ":" - + con.getPort() + "): " + e.getMessage(), "08006"); - } else { - EmbeddedConnection em = (EmbeddedConnection) res; - throw new SQLException("Unable to connect the directory " + em.getDirectory() + ": " - + e.getMessage(), "08006"); - } - } catch (ProtocolException e) { - throw new SQLException(e.getMessage(), "08001"); - } catch (MCLException e) { - String[] connex = e.getMessage().split("\n"); - SQLException sqle = new SQLException(connex[0], "08001", e); - for (int i = 1; i < connex.length; i++) { - sqle.setNextException(new SQLException(connex[1], "08001")); - } - throw sqle; - } - - //set the timezone - if (res.getLanguage() == MapiLanguage.LANG_SQL) { - // enable auto commit - res.setAutoCommit(true); - - // set our time zone on the server - Calendar cal = Calendar.getInstance(); - int offset = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET); - offset /= (60 * 1000); // milliseconds to minutes - String tz = offset < 0 ? "-" : "+"; - tz += (Math.abs(offset) / 60 < 10 ? "0" : "") + (Math.abs(offset) / 60) + ":"; - offset -= (offset / 60) * 60; - tz += (offset < 10 ? "0" : "") + offset; - - res.sendIndependentCommand("SET TIME ZONE INTERVAL '" + tz + "' HOUR TO MINUTE"); - } - - return res; - } -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/mcl/connection/embedded/EmbeddedConnection.java +++ /dev/null @@ -1,111 +0,0 @@ -package nl.cwi.monetdb.mcl.connection.embedded; - -import nl.cwi.monetdb.embedded.env.MonetDBEmbeddedConnection; -import nl.cwi.monetdb.embedded.env.MonetDBEmbeddedDatabase; -import nl.cwi.monetdb.embedded.env.MonetDBEmbeddedException; -import nl.cwi.monetdb.jdbc.MonetConnection; -import nl.cwi.monetdb.mcl.connection.ControlCommands; -import nl.cwi.monetdb.mcl.connection.MCLException; -import nl.cwi.monetdb.mcl.protocol.ProtocolException; -import nl.cwi.monetdb.mcl.protocol.ServerResponses; -import nl.cwi.monetdb.mcl.protocol.embedded.EmbeddedProtocol; - -import java.io.*; -import java.sql.SQLException; -import java.util.List; -import java.util.Properties; - -/** - * Created by ferreira on 11/23/16. - */ -public final class EmbeddedConnection extends MonetConnection { - - private final String directory; - - public EmbeddedConnection(Properties props, String database, String hash, String language, boolean blobIsBinary, - boolean isDebugging, String directory) throws IOException { - super(props, database, hash, EmbeddedLanguage.GetLanguageFromString(language), blobIsBinary, isDebugging); - this.directory = directory; - } - - public String getDirectory() { - return directory; - } - - public MonetDBEmbeddedConnection getAsMonetDBEmbeddedConnection() { - return ((EmbeddedProtocol)protocol).getEmbeddedConnection(); - } - - @Override - public List<String> connect(String username, String password) throws IOException, ProtocolException, MCLException { - try { - if(MonetDBEmbeddedDatabase.IsDatabaseRunning() && - !MonetDBEmbeddedDatabase.GetDatabaseDirectory().equals(this.directory)) { - throw new MCLException("The embedded database is already running on a different directory!"); - } else { - MonetDBEmbeddedDatabase.StartDatabase(this.directory, true, false); - } - this.protocol = new EmbeddedProtocol(MonetDBEmbeddedDatabase.CreateJDBCEmbeddedConnection()); - } catch (MonetDBEmbeddedException ex) { - throw new MCLException(ex); - } - return null; - } - - @Override - public String getJDBCURL() { - return "jdbc:monetdb://localhost@" + this.directory + "/" + this.database; - } - - @Override - public int getBlockSize() { - return Integer.MAX_VALUE; - } - - @Override - public int getDefFetchsize() { - return Integer.MAX_VALUE; - } - - @Override - public int getSoTimeout() { - this.addWarning("Cannot get a timeout on a embedded connection!", "M1M05"); - return -1; - } - - @Override - public void setSoTimeout(int s) { - this.addWarning("Cannot set a timeout on a embedded connection!", "M1M05"); - } - - @Override - public void closeUnderlyingConnection() throws IOException { - ((EmbeddedProtocol)protocol).getEmbeddedConnection().closeConnection(); - } - - @Override - public void sendControlCommand(ControlCommands con, int data) throws SQLException { - switch (con) { - case AUTO_COMMIT: - ((EmbeddedProtocol)protocol).getEmbeddedConnection().sendAutocommitCommand(data); - break; - case RELEASE: - ((EmbeddedProtocol)protocol).getEmbeddedConnection().sendReleaseCommand(data); - break; - case CLOSE: - ((EmbeddedProtocol)protocol).getEmbeddedConnection().sendCloseCommand(data); - break; - case REPLY_SIZE: - ((EmbeddedProtocol)protocol).getEmbeddedConnection().sendReplySizeCommand(data); - } - if (protocol.getCurrentServerResponseHeader() == ServerResponses.ERROR) { - throw new SQLException(protocol.getRemainingStringLine(0)); - } - } - - @Override - public ResponseList createResponseList(int fetchSize, int maxRows, int resultSetType, int resultSetConcurrency) throws SQLException { - return new MonetConnection.ResponseList(this.getDefFetchsize(), maxRows, resultSetType, resultSetConcurrency); - } - -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/mcl/connection/embedded/EmbeddedLanguage.java +++ /dev/null @@ -1,57 +0,0 @@ -package nl.cwi.monetdb.mcl.connection.embedded; - -import nl.cwi.monetdb.mcl.connection.IMonetDBLanguage; - -/** - * Created by ferreira on 12/9/16. - */ -public enum EmbeddedLanguage implements IMonetDBLanguage { - - /** the SQL language */ - LANG_SQL(new String[]{null, null, null}, "sql"), - /** an unknown language */ - LANG_UNKNOWN(new String[]{null, null, null}, "unknown"); - - EmbeddedLanguage(String[] queryTemplates, String representation) { - this.queryTemplates = queryTemplates; - this.representation = representation; - } - - private final String[] queryTemplates; - - private final String representation; - - @Override - public String getQueryTemplateIndex(int index) { - return this.queryTemplates[index]; - } - - @Override - public String getCommandTemplateIndex(int index) { - return null; - } - - @Override - public String[] getQueryTemplates() { - return this.queryTemplates; - } - - @Override - public String[] getCommandTemplates() { - return null; - } - - @Override - public String getRepresentation() { - return representation; - } - - public static EmbeddedLanguage GetLanguageFromString(String language) { - switch (language) { - case "sql": - return LANG_SQL; - default: - return LANG_UNKNOWN; - } - } -}
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/mcl/connection/helpers/Debugger.java +++ /dev/null @@ -1,115 +0,0 @@ -package nl.cwi.monetdb.mcl.connection.helpers; - -import java.io.*; - -/** - * Created by ferreira on 12/1/16. - */ -public class Debugger implements Closeable { - - /** The Writer for the debug log-file */ - private final Writer log; - - /** - * Enables logging to a stream what is read and written from and to - * the server. Logging can be enabled at any time. However, it is - * encouraged to start debugging before actually connecting the - * socket. - * - * @param log to write the log to - */ - public Debugger(Writer log) { - this.log = log; - } - - public Writer getLog() { - return log; - } - - /** - * Enables logging to a file what is read and written from and to - * the server. Logging can be enabled at any time. However, it is - * encouraged to start debugging before actually connecting the - * socket. - * - * @param filename the name of the file to write to - * @throws IOException if the file could not be opened for writing - */ - public Debugger(String filename) throws IOException { - this.log = new FileWriter(filename); - } - - /** - * Enables logging to a stream what is read and written from and to - * the server. Logging can be enabled at any time. However, it is - * encouraged to start debugging before actually connecting the - * socket. - * - * @param out to write the log to - */ - public Debugger(PrintStream out) { - this.log = new PrintWriter(out); - } - - /** - * Writes a logline tagged with a timestamp using the given string. - * Used for debugging purposes only and represents a message that is - * connected to writing to the socket. A logline might look like: - * TX 152545124: Hello MonetDB! - * - * @param message the message to log - * @throws IOException if an IO error occurs while writing to the logfile - */ - public void logTx(String message) throws IOException { - log.write("TX " + System.currentTimeMillis() + ": " + message + "\n"); - } - - /** - * Writes a logline tagged with a timestamp using the given string. - * Lines written using this log method are tagged as "added - * metadata" which is not strictly part of the data sent. - * - * @param message the message to log - * @throws IOException if an IO error occurs while writing to the logfile - */ - public void logTd(String message) throws IOException { - log.write("TD " + System.currentTimeMillis() + ": " + message + "\n"); - } - - /** - * Writes a logline tagged with a timestamp using the given string, - * and flushes afterwards. Used for debugging purposes only and - * represents a message that is connected to reading from the - * socket. The log is flushed after writing the line. A logline - * might look like: - * RX 152545124: Hi JDBC! - * - * @param message the message to log - * @throws IOException if an IO error occurs while writing to the logfile - */ - public void logRx(String message) throws IOException { - log.write("RX " + System.currentTimeMillis() + ": " + message + "\n"); - log.flush(); - } - - /** - * Writes a logline tagged with a timestamp using the given string, - * and flushes afterwards. Lines written using this log method are - * tagged as "added metadata" which is not strictly part of the data - * received. - * - * @param message the message to log - * @throws IOException if an IO error occurs while writing to the logfile - */ - public void logRd(String message) throws IOException { - log.write("RD " + System.currentTimeMillis() + ": " + message + "\n"); - log.flush(); - } - - @Override - public void close() throws IOException { - if (log instanceof FileWriter) { - log.close(); - } - } -}
--- a/src/main/java/nl/cwi/monetdb/mcl/connection/mapi/MapiConnection.java +++ b/src/main/java/nl/cwi/monetdb/mcl/connection/mapi/MapiConnection.java @@ -40,8 +40,8 @@ public class MapiConnection extends Mone private ByteOrder serverEndianness; public MapiConnection(Properties props, String database, String hash, String language, boolean blobIsBinary, - boolean isDebugging, String hostname, int port) throws IOException { - super(props, database, hash, MapiLanguage.GetLanguageFromString(language), blobIsBinary, isDebugging); + String hostname, int port) throws IOException { + super(props, database, hash, MapiLanguage.GetLanguageFromString(language), blobIsBinary); this.hostname = hostname; this.port = port; } @@ -331,15 +331,6 @@ public class MapiConnection extends Mone switch (u.getScheme()) { case "monetdb": - // this is a redirect to another (monetdb) server, which means a full reconnect avoid the debug - // log being closed - if (this.isDebugging) { - this.isDebugging = false; - this.close(); - this.isDebugging = true; - } else { - this.close(); - } tmp = u.getPath(); if (tmp != null && tmp.length() != 0) { tmp = tmp.substring(1).trim();
deleted file mode 100644 --- a/src/main/java/nl/cwi/monetdb/mcl/protocol/embedded/EmbeddedProtocol.java +++ /dev/null @@ -1,100 +0,0 @@ -package nl.cwi.monetdb.mcl.protocol.embedded; - -import nl.cwi.monetdb.jdbc.MonetConnection; -import nl.cwi.monetdb.embedded.env.JDBCEmbeddedConnection; -import nl.cwi.monetdb.mcl.protocol.*; -import nl.cwi.monetdb.mcl.responses.AutoCommitResponse; -import nl.cwi.monetdb.mcl.responses.DataBlockResponse; -import nl.cwi.monetdb.mcl.responses.ResultSetResponse; -import nl.cwi.monetdb.mcl.responses.UpdateResponse; - -import java.io.IOException; -import java.util.Map; - -/** - * Created by ferreira on 11/30/16. - */ -public class EmbeddedProtocol extends AbstractProtocol { - - private final JDBCEmbeddedConnection connection; - - public EmbeddedProtocol(JDBCEmbeddedConnection con) { - this.connection = con; - } - - public JDBCEmbeddedConnection getEmbeddedConnection() { - return this.connection; - } - - @Override - public ServerResponses getCurrentServerResponseHeader() { - return connection.getNextServerResponse(); - } - - @Override - public void waitUntilPrompt() throws IOException {} //Nothing really :) - - @Override - public void fetchNextResponseData() throws IOException {} //Nothing really :) - - @Override - public StarterHeaders getNextStarterHeader() { - return connection.getServerHeaderResponse(); - } - - @Override - public ResultSetResponse getNextResultSetResponse(MonetConnection con, MonetConnection.ResponseList list, int seqnr) throws ProtocolException { - int[] array = connection.getLastServerResponseParameters(); - int id = array[0]; //The order cannot be switched!! - int tuplecount = array[1]; - int columncount = array[2]; - int rowcount = array[3]; - return new ResultSetResponse(con, list, seqnr, id, rowcount, tuplecount, columncount); - } - - @Override - public UpdateResponse getNextUpdateResponse() throws ProtocolException { - return (UpdateResponse) connection.getLastServerResponse(); - } - - @Override - public AutoCommitResponse getNextAutoCommitResponse() throws ProtocolException { - return (AutoCommitResponse) connection.getLastServerResponse(); - } - - @Override - public DataBlockResponse getNextDatablockResponse(Map<Integer, ResultSetResponse> rsresponses) throws ProtocolException { - int[] array = connection.getLastServerResponseParameters(); - int id = array[0]; //The order cannot be switched!! - int columncount = array[1]; - int rowcount = array[2]; - int offset = array[3]; - - ResultSetResponse rs = rsresponses.get(id); - if (rs == null) { - return null; - } - return rs.addDataBlockResponse(offset, rowcount, columncount, this); - } - - @Override - public TableResultHeaders getNextTableHeader(String[] columnNames, int[] columnLengths, String[] types, - String[] tableNames) throws ProtocolException { - return connection.fillTableHeaders(columnNames, columnLengths, types, tableNames); - } - - @Override - public int parseTupleLines(int lineNumber, int[] typesMap, Object[] values, boolean[][] nulls) throws ProtocolException { - return connection.parseTupleLines(typesMap, values, nulls); - } - - @Override - public String getRemainingStringLine(int startIndex) { - return connection.getLastError(); - } - - @Override - public void writeNextQuery(String prefix, String query, String suffix) throws IOException { - connection.processNextQuery(query); - } -}
--- a/src/main/java/nl/cwi/monetdb/mcl/protocol/oldmapi/OldMapiProtocol.java +++ b/src/main/java/nl/cwi/monetdb/mcl/protocol/oldmapi/OldMapiProtocol.java @@ -136,7 +136,11 @@ public class OldMapiProtocol extends Abs @Override public String getRemainingStringLine(int startIndex) { - return new String(this.lineBuffer.array(), startIndex, this.lineBuffer.limit() - startIndex); + if(this.lineBuffer.limit() > startIndex) { + return new String(this.lineBuffer.array(), startIndex, this.lineBuffer.limit() - startIndex); + } else { + return null; + } } @Override
--- a/src/main/java/nl/cwi/monetdb/merovingian/Control.java +++ b/src/main/java/nl/cwi/monetdb/merovingian/Control.java @@ -8,7 +8,23 @@ package nl.cwi.monetdb.merovingian; +import nl.cwi.monetdb.mcl.connection.MCLException; +import nl.cwi.monetdb.mcl.connection.mapi.MapiConnection; +import nl.cwi.monetdb.mcl.protocol.AbstractProtocol; +import nl.cwi.monetdb.mcl.protocol.ProtocolException; +import nl.cwi.monetdb.mcl.protocol.ServerResponses; + +import java.io.BufferedReader; import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.net.Socket; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; /** * A Control class to perform operations on a remote merovingian @@ -28,7 +44,7 @@ import java.io.IOException; * @author Fabian Groffen * @version 1.0 */ -public class Control { //TODO make me working again +public class Control { /** The host to connect to */ private final String host; /** The port to connect to */ @@ -36,7 +52,6 @@ public class Control { //TODO make me wo /** The passphrase to use when connecting */ private final String passphrase; /** The file we should write MapiSocket debuglog to */ - private String debug; /** * Constructs a new Control object. @@ -50,18 +65,6 @@ public class Control { //TODO make me wo this.passphrase = passphrase; } - /** - * Instructs to write a MCL protocol debug log to the given file. - * This affects any newly performed command, and can be changed - * inbetween commands. Passing null to this method disables the - * debug log. - * - * @param filename the filename to write debug information to, or null - */ - public void setDebug(String filename) { - this.debug = filename; - } - private String controlHash(String pass, String salt) { long ho; long h = 0; @@ -92,35 +95,28 @@ public class Control { //TODO make me wo final static private String RESPONSE_OK = "OK"; - /*private List<String> sendCommand(String database, String command, boolean hasOutput) + private List<String> sendCommand(String database, String command, boolean hasOutput) throws MerovingianException, IOException { - AbstractMCLReader min; - AbstractMCLWriter mout; - DeleteMe ms = new DeleteMe(host, port, "monetdb", "monetdb", false, "sql", "SHA256"); - ms.setDatabase("merovingian"); - ms.setLanguage("control"); - if (debug != null) - ms.debug(debug); + + MapiConnection server = new MapiConnection(null, "merovingian",null, "control", true, host, port ); + AbstractProtocol protocol = server.getProtocol(); try { - ms.connect("monetdb", passphrase); - min = ms.getReader(); - mout = ms.getWriter(); - } catch (MCLParseException | MCLException e) { + server.connect("monetdb", passphrase); + } catch (ProtocolException | MCLException e) { throw new MerovingianException(e.getMessage()); } catch (AssertionError e) { // mcl panics - ms.close(); + server.close(); - // Try resultset protocol instead + // Try old protocol instead Socket s; PrintStream out; BufferedReader in; s = new Socket(host, port); out = new PrintStream(s.getOutputStream()); - in = new BufferedReader( - new InputStreamReader(s.getInputStream())); + in = new BufferedReader(new InputStreamReader(s.getInputStream())); try { /* login ritual, step 1: get challenge from server */ - /*String response = in.readLine(); + String response = in.readLine(); if (response == null) throw new MerovingianException("server closed the connection"); @@ -152,12 +148,12 @@ public class Control { //TODO make me wo } /* send command, form is simple: "<db> <cmd>\n" */ - //out.print(database + " " + command + "\n"); + out.print(database + " " + command + "\n"); /* Response has the first line either "OK\n" or an error * message. In case of a command with output, the data will * follow the first line */ - /*response = in.readLine(); + response = in.readLine(); if (response == null) { throw new MerovingianException("server closed the connection"); } @@ -180,34 +176,36 @@ public class Control { //TODO make me wo } } - mout.writeLine(database + " " + command + "\n"); + protocol.writeNextQuery(null,database + " " + command, "\n"); ArrayList<String> l = new ArrayList<>(); - String tmpLine = min.readLine(); - int linetype = min.getLineType(); - if (linetype == AbstractMCLReader.ERROR) - throw new MerovingianException(tmpLine.substring(6)); - if (linetype != AbstractMCLReader.RESULT) - throw new MerovingianException("unexpected line: " + tmpLine); - if (!tmpLine.substring(1).equals(RESPONSE_OK)) - throw new MerovingianException(tmpLine.substring(1)); - tmpLine = min.readLine(); - linetype = min.getLineType(); - while (linetype != AbstractMCLReader.PROMPT) { - if (linetype != AbstractMCLReader.RESULT) - throw new MerovingianException("unexpected line: " + - tmpLine); + protocol.waitUntilPrompt(); + ServerResponses next = protocol.getCurrentServerResponseHeader(); + String line = protocol.getRemainingStringLine(0); + + if (next == ServerResponses.ERROR) + throw new MerovingianException(line.substring(6)); + if (next != ServerResponses.RESULT) + throw new MerovingianException("unexpected line: " + line); + if (!line.substring(1).equals(RESPONSE_OK)) + throw new MerovingianException(line.substring(1)); - l.add(tmpLine.substring(1)); + next = protocol.getCurrentServerResponseHeader(); + line = protocol.getRemainingStringLine(0); + while (next != ServerResponses.PROMPT) { + if (next != ServerResponses.RESULT) + throw new MerovingianException("unexpected line: " + line); - tmpLine = min.readLine(); - linetype = min.getLineType(); + l.add(line.substring(1)); + + next = protocol.getCurrentServerResponseHeader(); + line = protocol.getRemainingStringLine(0); } - ms.close(); + server.close(); return l; - }*/ + } - /*public void start(String database) throws MerovingianException, IOException { + public void start(String database) throws MerovingianException, IOException { sendCommand(database, "start", false); } @@ -239,8 +237,8 @@ public class Control { //TODO make me wo if (newname == null) newname = ""; /* force error from merovingian */ - /*sendCommand(database, "name=" + newname, false); - }*/ + sendCommand(database, "name=" + newname, false); + } /** * Sets property for database to value. If value is null, the @@ -259,16 +257,16 @@ public class Control { //TODO make me wo if (value == null) value = ""; - //sendCommand(database, property + "=" + value, false); + sendCommand(database, property + "=" + value, false); } public void inheritProperty(String database, String property) throws MerovingianException, IOException { setProperty(database, property, null); } - /*public Properties getProperties(String database) throws MerovingianException, IOException { + public Properties getProperties(String database) throws MerovingianException, IOException { Properties ret = new Properties(); - //List<String> response = sendCommand(database, "get", true); + List<String> response = sendCommand(database, "get", true); for (String responseLine : response) { if (responseLine.startsWith("#")) continue; @@ -296,12 +294,12 @@ public class Control { //TODO make me wo /** * Test whether a specific database exists. * - * @param database The database name + * @param database * @return true, iff database already exists. * @throws MerovingianException * @throws IOException */ - /*public boolean exists(String database) throws MerovingianException, IOException { + public boolean exists(String database) throws MerovingianException, IOException { List<SabaothDB> all = getAllStatuses(); for (SabaothDB db : all) { if (db.getName().equals(database)) { @@ -325,7 +323,7 @@ public class Control { //TODO make me wo } public List<URI> getAllNeighbours() throws MerovingianException, IOException { - List<URI> l = new ArrayList<URI>(); + List<URI> l = new ArrayList<>(); List<String> response = sendCommand("anelosimus", "eximius", true); try { for (String responseLine : response) { @@ -344,5 +342,5 @@ public class Control { //TODO make me wo throw new MerovingianException(e.getMessage()); } return Collections.unmodifiableList(l); - }*/ + } }
--- a/src/main/java/nl/cwi/monetdb/merovingian/SabaothDB.java +++ b/src/main/java/nl/cwi/monetdb/merovingian/SabaothDB.java @@ -8,11 +8,11 @@ package nl.cwi.monetdb.merovingian; -import java.util.*; +import java.util.Date; /** * Implementation of the Sabaoth C-struct as Java object. - * + * * This Class implements a parser for the string representation of a * sabaoth information struct as returned by monetdbd. * <br /> @@ -56,6 +56,7 @@ public class SabaothDB { private double crashAvg10; /** Average of crashes in the last 30 start attempts */ private double crashAvg30; + /** The serialised format header */ private final String sabdbhdr = "sabdb:";
--- a/src/main/java/nl/cwi/monetdb/util/CmdLineOpts.java +++ b/src/main/java/nl/cwi/monetdb/util/CmdLineOpts.java @@ -8,28 +8,34 @@ package nl.cwi.monetdb.util; -import java.util.*; -import java.io.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; public class CmdLineOpts { /** the arguments we handle */ - private Map<String, OptionContainer> opts = new HashMap<String, OptionContainer>(); + private Map<String, OptionContainer> opts = new HashMap<>(); /** the options themself */ - private List<OptionContainer> options = new ArrayList<OptionContainer>(); - + private List<OptionContainer> options = new ArrayList<>(); + /** no arguments */ - public static int CAR_ZERO = 0; + public static int CAR_ZERO = 0; /** always one argument */ - public static int CAR_ONE = 1; + public static int CAR_ONE = 1; /** zero or one argument */ public static int CAR_ZERO_ONE = 2; /** zero or many arguments */ public static int CAR_ZERO_MANY = 3; /** one or many arguments */ public static int CAR_ONE_MANY = 4; - - public CmdLineOpts() { - } + + public CmdLineOpts() {} public void addOption(String shorta, String longa, int type, String defaulta, String descriptiona) throws OptionsException { @@ -68,8 +74,8 @@ public class CmdLineOpts { for (Enumeration<?> e = prop.propertyNames(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); OptionContainer option = opts.get(key); - if (option == null) throw - new OptionsException("Unknown option: " + key); + if (option == null) + throw new OptionsException("Unknown option: " + key); option.resetArguments(); option.addArgument(prop.getProperty(key)); } @@ -193,7 +199,7 @@ public class CmdLineOpts { // yes, we don't care about branch mispredictions here ;) if (maxlen < len) maxlen = len; } - + // get the individual strings StringBuilder ret = new StringBuilder(); for (OptionContainer oc : options) { @@ -276,7 +282,7 @@ public class CmdLineOpts { boolean present; public OptionContainer(String shorta, String longa, int cardinality, String defaulta, String descriptiona) - throws IllegalArgumentException { + throws IllegalArgumentException { this.cardinality = cardinality; this.shorta = shorta; this.longa = longa; @@ -284,8 +290,8 @@ public class CmdLineOpts { this.descriptiona = descriptiona; this.present = false; - if (cardinality != CAR_ZERO && cardinality != CAR_ONE && cardinality != CAR_ZERO_ONE - && cardinality != CAR_ZERO_MANY && cardinality != CAR_ONE_MANY) + if (cardinality != CAR_ZERO && cardinality != CAR_ONE && cardinality != CAR_ZERO_ONE && + cardinality != CAR_ZERO_MANY && cardinality != CAR_ONE_MANY) throw new IllegalArgumentException("unknown cardinality"); if (shorta != null && shorta.length() != 1) throw new IllegalArgumentException("short option should consist of exactly one character"); @@ -299,7 +305,6 @@ public class CmdLineOpts { } name = (longa != null) ? longa : shorta; - options.add(this); }
--- a/src/main/java/nl/cwi/monetdb/util/Exporter.java +++ b/src/main/java/nl/cwi/monetdb/util/Exporter.java @@ -8,11 +8,12 @@ package nl.cwi.monetdb.util; -import java.io.*; -import java.sql.*; +import java.io.PrintWriter; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.Arrays; - public abstract class Exporter { protected PrintWriter out; protected boolean useSchema; @@ -21,24 +22,20 @@ public abstract class Exporter { this.out = out; } - public abstract void dumpSchema( - DatabaseMetaData dbmd, - String type, - String catalog, - String schema, - String name) throws SQLException; + public abstract void dumpSchema(DatabaseMetaData dbmd, String type, String catalog, String schema, String name) + throws SQLException; public abstract void dumpResultSet(ResultSet rs) throws SQLException; public abstract void setProperty(int type, int value) throws Exception; public abstract int getProperty(int type) throws Exception; - + //=== shared utilities - + public void useSchemas(boolean use) { useSchema = use; } - + /** * returns the given string between two double quotes for usage as * identifier such as column or table name in SQL queries.
--- a/src/main/java/nl/cwi/monetdb/util/SQLExporter.java +++ b/src/main/java/nl/cwi/monetdb/util/SQLExporter.java @@ -27,7 +27,7 @@ public class SQLExporter extends Exporte private Stack<String> lastSchema; public final static int TYPE_OUTPUT = 1; - public final static int VALUE_INSERT = 0; + public final static int VALUE_INSERT = 0; public final static int VALUE_COPY = 1; public final static int VALUE_TABLE = 2; @@ -48,7 +48,7 @@ public class SQLExporter extends Exporte * @throws SQLException if a database related error occurs */ public void dumpSchema(DatabaseMetaData dbmd, String type, String catalog, String schema, String name) - throws SQLException { + throws SQLException { assert dbmd != null; assert type != null; assert schema != null; @@ -175,13 +175,13 @@ public class SQLExporter extends Exporte // print column type, optional length and scale, optional Not NULL, optional default value out.print(sb.toString()); - sb.delete(0, sb.length()); // clear the stringbuffer for next columns + sb.delete(0, sb.length()); // clear the stringbuffer for next column } cols.close(); // add the primary key constraint definition // unfortunately some idiot defined that getPrimaryKeys() - // returns the primary key column sorted by column name, not + // returns the primary key columns sorted by column name, not // key sequence order. So we have to sort ourself :( cols = dbmd.getPrimaryKeys(catalog, schema, name); // first make an 'index' of the KEY_SEQ column @@ -466,7 +466,10 @@ public class SQLExporter extends Exporte strbuf.append('|'); for (int j = 1; j < width.length; j++) { String colLabel = md.getColumnLabel(j); - strbuf.append(' ').append(colLabel).append(repeat(' ', width[j] - colLabel.length())).append(" |"); + strbuf.append(' '); + strbuf.append(colLabel); + strbuf.append(repeat(' ', width[j] - colLabel.length())); + strbuf.append(" |"); } // print the header text out.println(outsideLine);
--- a/src/main/java/nl/cwi/monetdb/util/SQLRestore.java +++ b/src/main/java/nl/cwi/monetdb/util/SQLRestore.java @@ -8,19 +8,29 @@ package nl.cwi.monetdb.util; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; import java.io.IOException; +import java.util.concurrent.atomic.AtomicBoolean; + +import nl.cwi.monetdb.mcl.connection.MCLException; +import nl.cwi.monetdb.mcl.connection.mapi.MapiConnection; +import nl.cwi.monetdb.mcl.protocol.AbstractProtocol; +import nl.cwi.monetdb.mcl.protocol.ProtocolException; +import nl.cwi.monetdb.mcl.protocol.ServerResponses; /** * Use this class to restore an SQL dump file. */ public class SQLRestore { - /*private final String _host; TODO make me working again! + private final String _host; private final int _port; private final String _user; private final String _password; private final String _dbName; - + public SQLRestore(String host, int port, String user, String password, String dbName) throws IOException { if (host == null || user == null || password == null || dbName == null) throw new NullPointerException(); @@ -30,96 +40,88 @@ public class SQLRestore { _password = password; _dbName = dbName; } - - private static class ServerResponseReader implements Runnable { - private final AbstractMCLReader _is; + + private class ServerResponseReader implements Runnable { + private final MapiConnection _is; private final AtomicBoolean _errorState = new AtomicBoolean(false); - private String _errorMessage = null; - - ServerResponseReader(AbstractMCLReader is) { + private String _errorMessage = null; + + ServerResponseReader(MapiConnection is) { _is = is; } - + public void run() { + AbstractProtocol protocol = _is.getProtocol(); + ServerResponses next; + String line; try { while (true) { - String line = _is.readLine(); + protocol.waitUntilPrompt(); + next = protocol.getCurrentServerResponseHeader(); + line = protocol.getRemainingStringLine(0); if (line == null) break; - int result = _is.getLineType(); - switch (result) { - case AbstractMCLReader.ERROR: - _errorMessage = line; - _errorState.set(true); - return; - default: - // do nothing... + switch (next) { + case ERROR: + _errorMessage = line; + _errorState.set(true); + return; + default: + // do nothing... } } - } catch (IOException e) { _errorMessage = e.getMessage(); _errorState.set(true); } finally { - try { - _is.close(); - } catch (IOException e) { - // ignore errors - } + _is.close(); } - }*/ - + } + /** * @return whether the server has responded with an error. Any * error is regarded as fatal. */ - /*public boolean inErrorState() { + public boolean inErrorState() { return _errorState.get(); - }*/ - + } + /** - * @return the error message if inErrorState() is true. Behaviour is - * not defined if called before inErrorState is true. + * @return the error message if inErrorState() is true. Behaviour is + * not defined if called before inErrorState is true. */ - /*public String getErrorMessage() { + public String getErrorMessage() { return _errorMessage; - }*/ - - //} - + } + } + /** * Restores a given SQL dump to the database. - * - * @param source File location of the SQL dump + * + * @param source * @throws IOException */ - /*public void restore(File source) throws IOException { - DeleteMe ms = new DeleteMe(_host, _port, _dbName, _user, false, "sql", "SHA256"); + public void restore(File source) throws IOException { + MapiConnection server = new MapiConnection(null, _dbName,null, "sql", true,_host, _port ); try { - ms.connect(_user, _password); - - AbstractMCLWriter os = ms.getWriter(); - AbstractMCLReader reader = ms.getReader(); - - ServerResponseReader srr = new ServerResponseReader(reader); + server.connect(_user, _password); + ServerResponseReader srr = new ServerResponseReader(server); Thread responseReaderThread = new Thread(srr); responseReaderThread.start(); try { // FIXME: we assume here that the dump is in system's default encoding BufferedReader sourceData = new BufferedReader(new FileReader(source)); try { - os.write('s'); // signal that a new statement (or series of) is coming + AbstractProtocol protocol = server.getProtocol(); + protocol.writeNextQuery(null, "s", null); // signal that a new statement (or series of) is coming while(!srr.inErrorState()) { char[] buf = new char[4096]; int result = sourceData.read(buf); if (result < 0) break; - os.write(buf, 0, result); + protocol.writeNextQuery(null, new String(buf, 0, result), null); } - - os.flush(); // mark the end of the statement (or series of) - os.close(); } finally { sourceData.close(); } @@ -129,31 +131,30 @@ public class SQLRestore { } catch (InterruptedException e) { throw new IOException(e.getMessage()); } - - // if the server signalled an error, we should respect it... + + // if the server signalled an error, we should respect it... if (srr.inErrorState()) { throw new IOException(srr.getErrorMessage()); } } - } catch (MCLException | MCLParseException e) { + } catch (MCLException | ProtocolException e) { throw new IOException(e.getMessage()); } finally { - ms.close(); + server.close(); } } - + public void close() { // do nothing at the moment... } - - + public static void main(String[] args) throws IOException { if (args.length != 6) { - System.err.println("USAGE: java " + SQLRestore.class.getName() + + System.err.println("USAGE: java " + SQLRestore.class.getName() + " <host> <port> <user> <password> <dbname> <dumpfile>"); System.exit(1); } - + // parse arguments String host = args[0]; int port = Integer.parseInt(args[1]); // FIXME: catch NumberFormatException @@ -161,13 +162,13 @@ public class SQLRestore { String password = args[3]; String dbName = args[4]; File dumpFile = new File(args[5]); - + // check arguments if (!dumpFile.isFile() || !dumpFile.canRead()) { System.err.println("Cannot read: " + dumpFile); System.exit(1); } - + SQLRestore md = new SQLRestore(host, port, user, password, dbName); try { System.out.println("Start restoring " + dumpFile); @@ -178,5 +179,5 @@ public class SQLRestore { } finally { md.close(); } - }*/ + } }
--- a/src/main/java/nl/cwi/monetdb/util/XMLExporter.java +++ b/src/main/java/nl/cwi/monetdb/util/XMLExporter.java @@ -8,10 +8,16 @@ package nl.cwi.monetdb.util; -import java.io.*; -import java.sql.*; -import java.util.*; -import java.text.*; +import java.io.PrintWriter; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.sql.Types; +import java.text.SimpleDateFormat; +import java.util.HashSet; +import java.util.Set; public class XMLExporter extends Exporter { private boolean useNil; @@ -36,7 +42,7 @@ public class XMLExporter extends Exporte out.print("<!-- unable to represent: CREATE " + type + " " + (!useSchema ? dq(schema) + "." : "") + dq(name)); out.print(" AS "); - out.print(tbl.getString("REMARKS").trim()); + out.print(tbl.getString("REMARKS").trim()); out.print(" -->"); return; } @@ -51,7 +57,7 @@ public class XMLExporter extends Exporte // http://books.xmlschemata.org/relaxng/relax-CHP-19.html while (cols.next()) { switch (cols.getInt("DATA_TYPE")) { - case java.sql.Types.CHAR: + case Types.CHAR: ident = "CHAR_" + cols.getString("COLUMN_SIZE"); if (types.contains(ident)) break; types.add(ident); @@ -66,8 +72,8 @@ public class XMLExporter extends Exporte out.println(" </xsd:restriction>"); out.println(" </xsd:simpleType>"); break; - case java.sql.Types.VARCHAR: - case java.sql.Types.LONGVARCHAR: + case Types.VARCHAR: + case Types.LONGVARCHAR: ident = "VARCHAR_" + cols.getString("COLUMN_SIZE"); if (types.contains(ident)) break; types.add(ident); @@ -82,7 +88,7 @@ public class XMLExporter extends Exporte out.println(" </xsd:restriction>"); out.println(" </xsd:simpleType>"); break; - case java.sql.Types.CLOB: + case Types.CLOB: ident = "CLOB"; if (types.contains(ident)) break; types.add(ident); @@ -93,8 +99,8 @@ public class XMLExporter extends Exporte out.println(" <xsd:restriction base=\"xsd:string\" />"); out.println(" </xsd:simpleType>"); break; - case java.sql.Types.DECIMAL: - case java.sql.Types.NUMERIC: + case Types.DECIMAL: + case Types.NUMERIC: ident = "DECIMAL_" + cols.getString("COLUMN_SIZE") + "_" + cols.getString("DECIMAL_DIGITS"); if (types.contains(ident)) break; @@ -113,7 +119,7 @@ public class XMLExporter extends Exporte out.println(" </xsd:restriction>"); out.println(" </xsd:simpleType>"); break; - case java.sql.Types.TINYINT: + case Types.TINYINT: ident = "TINYINT"; if (types.contains(ident)) break; types.add(ident); @@ -124,7 +130,7 @@ public class XMLExporter extends Exporte out.println(" <xsd:restriction base=\"xsd:byte\" />"); out.println(" </xsd:simpleType>"); break; - case java.sql.Types.SMALLINT: + case Types.SMALLINT: ident = "SMALLINT"; if (types.contains(ident)) break; types.add(ident); @@ -135,7 +141,7 @@ public class XMLExporter extends Exporte out.println(" <xsd:restriction base=\"xsd:short\" />"); out.println(" </xsd:simpleType>"); break; - case java.sql.Types.INTEGER: + case Types.INTEGER: ident = "INTEGER"; if (types.contains(ident)) break; types.add(ident); @@ -146,7 +152,7 @@ public class XMLExporter extends Exporte out.println(" <xsd:restriction base=\"xsd:integer\" />"); out.println(" </xsd:simpleType>"); break; - case java.sql.Types.BIGINT: + case Types.BIGINT: ident = "BIGINT"; if (types.contains(ident)) break; types.add(ident); @@ -157,8 +163,18 @@ public class XMLExporter extends Exporte out.println(" <xsd:restriction base=\"xsd:long\" />"); out.println(" </xsd:simpleType>"); break; - case java.sql.Types.BIT: - case java.sql.Types.BOOLEAN: + case Types.BIT: + ident = "BIT"; + if (types.contains(ident)) break; + types.add(ident); + + out.print(" <xsd:simpleType name="); + out.print(dq(ident)); + out.println(">"); + out.println(" <xsd:restriction base=\"xsd:bit\" />"); + out.println(" </xsd:simpleType>"); + break; + case Types.BOOLEAN: ident = "BOOLEAN"; if (types.contains(ident)) break; types.add(ident); @@ -169,7 +185,7 @@ public class XMLExporter extends Exporte out.println(" <xsd:restriction base=\"xsd:boolean\" />"); out.println(" </xsd:simpleType>"); break; - case java.sql.Types.DATE: + case Types.DATE: ident = "DATE"; if (types.contains(ident)) break; types.add(ident); @@ -180,7 +196,7 @@ public class XMLExporter extends Exporte out.println(" <xsd:restriction base=\"xsd:date\" />"); out.println(" </xsd:simpleType>"); break; - case java.sql.Types.TIME: + case Types.TIME: if ("timetz".equals(cols.getString("TYPE_NAME"))) { ident = "TIME_WTZ"; } else { @@ -195,7 +211,7 @@ public class XMLExporter extends Exporte out.println(" <xsd:restriction base=\"xsd:time\" />"); out.println(" </xsd:simpleType>"); break; - case java.sql.Types.TIMESTAMP: + case Types.TIMESTAMP: if ("timestamptz".equals(cols.getString("TYPE_NAME"))) { ident = "TIMESTAMP_WTZ"; } else { @@ -228,48 +244,50 @@ public class XMLExporter extends Exporte out.print(dq(cols.getString("COLUMN_NAME"))); out.print(" type="); switch (cols.getInt("DATA_TYPE")) { - case java.sql.Types.CHAR: + case Types.CHAR: ident = "CHAR_" + cols.getString("COLUMN_SIZE"); break; - case java.sql.Types.VARCHAR: - case java.sql.Types.LONGVARCHAR: + case Types.VARCHAR: + case Types.LONGVARCHAR: ident = "VARCHAR_" + cols.getString("COLUMN_SIZE"); break; - case java.sql.Types.CLOB: + case Types.CLOB: ident = "CLOB"; break; - case java.sql.Types.DECIMAL: - case java.sql.Types.NUMERIC: + case Types.DECIMAL: + case Types.NUMERIC: ident = "DECIMAL_" + cols.getString("COLUMN_SIZE") + "_" + cols.getString("DECIMAL_DIGITS"); break; - case java.sql.Types.TINYINT: + case Types.TINYINT: ident = "TINYINT"; break; - case java.sql.Types.SMALLINT: + case Types.SMALLINT: ident = "SMALLINT"; break; - case java.sql.Types.INTEGER: + case Types.INTEGER: ident = "INTEGER"; break; - case java.sql.Types.BIGINT: + case Types.BIGINT: ident = "BIGINT"; break; - case java.sql.Types.BIT: - case java.sql.Types.BOOLEAN: + case Types.BIT: + ident = "BIT"; + break; + case Types.BOOLEAN: ident = "BOOLEAN"; break; - case java.sql.Types.DATE: + case Types.DATE: ident = "DATE"; break; - case java.sql.Types.TIME: + case Types.TIME: if ("timetz".equals(cols.getString("TYPE_NAME"))) { ident = "TIME_WTZ"; } else { ident = "TIME"; } break; - case java.sql.Types.TIMESTAMP: + case Types.TIMESTAMP: if ("timestamptz".equals(cols.getString("TYPE_NAME"))) { ident = "TIMESTAMP_WTZ"; } else { @@ -314,14 +332,15 @@ public class XMLExporter extends Exporte public void dumpResultSet(ResultSet rs) throws SQLException { // write simple XML serialisation ResultSetMetaData rsmd = rs.getMetaData(); - if (!useSchema) out.println("<" + rsmd.getSchemaName(1) + ">"); + if (!useSchema) + out.println("<" + rsmd.getSchemaName(1) + ">"); out.println("<" + rsmd.getTableName(1) + ">"); String data; while (rs.next()) { out.println(" <row>"); for (int i = 1; i <= rsmd.getColumnCount(); i++) { switch (rsmd.getColumnType(i)) { - case java.sql.Types.TIMESTAMP: + case Types.TIMESTAMP: Timestamp ts = rs.getTimestamp(i); if ("timestamptz".equals(rsmd.getColumnTypeName(i))) { data = xsd_tstz.format(ts);