Mercurial > hg > monetdb-java
changeset 309:8a96a4a13528
Add additional "final" keyword to classes, method arguments and local variables where possible.
Small improvements to the code and comments
author | Martin van Dinther <martin.van.dinther@monetdbsolutions.com> |
---|---|
date | Thu, 22 Aug 2019 16:04:25 +0200 (2019-08-22) |
parents | 1948dbcd9991 |
children | 5ddab9d8d3dd |
files | src/main/java/nl/cwi/monetdb/client/JdbcClient.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/Extract.java src/main/java/nl/cwi/monetdb/util/OptionsException.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 | 8 files changed, 216 insertions(+), 210 deletions(-) [+] |
line wrap: on
line diff
--- a/src/main/java/nl/cwi/monetdb/client/JdbcClient.java +++ b/src/main/java/nl/cwi/monetdb/client/JdbcClient.java @@ -284,13 +284,12 @@ public final class JdbcClient { // we only want user tables and views to be dumped, unless a specific // table is requested - String[] types = {"TABLE", "VIEW"}; - if (copts.getOption("dump").getArgumentCount() > 0) - types = null; - // request the tables available in the current schema in the database - ResultSet tbl = dbmd.getTables(null, con.getSchema(), null, types); + final String[] types = {"TABLE", "VIEW"}; + final boolean usetypes = (copts.getOption("dump").getArgumentCount() == 0); + // request the list of tables available in the current schema in the database + ResultSet tbl = dbmd.getTables(null, con.getSchema(), null, usetypes ? types : null); + // fetch all tables and store them in a LinkedList of Table objects final LinkedList<Table> tables = new LinkedList<Table>(); - // fetch all tables and store them in a LinkedList while (tbl.next()) { tables.add(new Table( tbl.getString(2), // 2 = "TABLE_SCHEM" @@ -360,7 +359,7 @@ public final class JdbcClient { // find the graph, at this point we know there are no // cycles, thus a solution exists for (int i = 0; i < tables.size(); i++) { - List<Table> needs = tables.get(i).requires(tables.subList(0, i + 1)); + final List<Table> needs = tables.get(i).requires(tables.subList(0, i + 1)); if (needs.size() > 0) { tables.removeAll(needs); tables.addAll(i, needs); @@ -497,17 +496,16 @@ public final class JdbcClient { if (ret == null) { try { HttpURLConnection.setFollowRedirects(true); - HttpURLConnection con = (HttpURLConnection)u.openConnection(); + final HttpURLConnection con = (HttpURLConnection)u.openConnection(); con.setRequestMethod("GET"); - String ct = con.getContentType(); + final String ct = con.getContentType(); if ("application/x-gzip".equals(ct)) { // open gzip stream ret = new BufferedReader(new InputStreamReader( new java.util.zip.GZIPInputStream(con.getInputStream()))); } else { // text/plain otherwise just attempt to read as is - ret = new BufferedReader(new InputStreamReader( - con.getInputStream())); + ret = new BufferedReader(new InputStreamReader(con.getInputStream())); } } catch (IOException e) { // failed to open the url @@ -538,17 +536,13 @@ public final class JdbcClient { final boolean hasFile, final boolean doEcho, final boolean scolonterm, - final String user - ) + final String user) throws IOException, SQLException { // an SQL stack keeps track of ( " and ' final SQLStack stack = new SQLStack(); - // a query part is a line of an SQL query - QueryPart qp = null; + boolean lastac = false; - String query = "", curLine; - boolean wasComplete = true, doProcess, lastac = false; if (!hasFile) { lastac = con.getAutoCommit(); out.println("auto commit mode: " + (lastac ? "on" : "off")); @@ -556,6 +550,11 @@ public final class JdbcClient { out.flush(); } + String curLine; + String query = ""; + boolean doProcess; + boolean wasComplete = true; + // the main (interactive) process loop for (long i = 1; true; i++) { // Manually read a line, because we want to detect an EOF @@ -582,7 +581,7 @@ public final class JdbcClient { query = ""; wasComplete = true; if (!hasFile) { - boolean ac = con.getAutoCommit(); + final boolean ac = con.getAutoCommit(); if (ac != lastac) { out.println("auto commit mode: " + (ac ? "on" : "off")); lastac = ac; @@ -603,9 +602,11 @@ public final class JdbcClient { out.println(curLine); out.flush(); } - qp = scanQuery(curLine, stack, scolonterm); + + // a query part is a line of an SQL query + QueryPart qp = scanQuery(curLine, stack, scolonterm); if (!qp.isEmpty()) { - String command = qp.getQuery(); + final String command = qp.getQuery(); doProcess = true; if (wasComplete) { doProcess = false; @@ -633,7 +634,7 @@ public final class JdbcClient { // give us a list of all non-system tables and views (including temp ones) while (tbl.next()) { - String tableType = tbl.getString(4); // 4 = "TABLE_TYPE" + final String tableType = tbl.getString(4); // 4 = "TABLE_TYPE" if (tableType != null && tableType.startsWith("SYSTEM ")) out.println(tableType + "\t" + tbl.getString(2) + "." + // 2 = "TABLE_SCHEM" @@ -649,7 +650,7 @@ public final class JdbcClient { // give us a list of all non-system tables and views (including temp ones) while (tbl.next()) { - String tableType = tbl.getString(4); // 4 = "TABLE_TYPE" + final String tableType = tbl.getString(4); // 4 = "TABLE_TYPE" if (tableType != null && !tableType.startsWith("SYSTEM ")) out.println(tableType + "\t" + tbl.getString(2) + "." + // 2 = "TABLE_SCHEM" @@ -671,8 +672,8 @@ public final class JdbcClient { } tbl = dbmd.getTables(null, schema, obj_nm, null); while (tbl.next() && !found) { - String tableName = tbl.getString(3); // 3 = "TABLE_NAME" - String schemaName = tbl.getString(2); // 2 = "TABLE_SCHEM" + final String schemaName = tbl.getString(2); // 2 = "TABLE_SCHEM" + final String tableName = tbl.getString(3); // 3 = "TABLE_NAME" if (obj_nm.equals(tableName) && schema.equals(schemaName)) { // we found it, describe it exporter.dumpSchema(dbmd,
--- a/src/main/java/nl/cwi/monetdb/util/CmdLineOpts.java +++ b/src/main/java/nl/cwi/monetdb/util/CmdLineOpts.java @@ -8,42 +8,36 @@ package nl.cwi.monetdb.util; -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 { +public final class CmdLineOpts { /** the arguments we handle */ - private Map<String, OptionContainer> opts = new HashMap<String, OptionContainer>(); + private HashMap<String, OptionContainer> opts = new HashMap<String, OptionContainer>(); /** the options themself */ - private List<OptionContainer> options = new ArrayList<OptionContainer>(); + private ArrayList<OptionContainer> options = new ArrayList<OptionContainer>(); /** no arguments */ - public static int CAR_ZERO = 0; + public static final int CAR_ZERO = 0; /** always one argument */ - public static int CAR_ONE = 1; + public static final int CAR_ONE = 1; /** zero or one argument */ - public static int CAR_ZERO_ONE = 2; + public static final int CAR_ZERO_ONE = 2; /** zero or many arguments */ - public static int CAR_ZERO_MANY = 3; + public static final int CAR_ZERO_MANY = 3; /** one or many arguments */ - public static int CAR_ONE_MANY = 4; + public static final int CAR_ONE_MANY = 4; public CmdLineOpts() { } public void addOption( - String shorta, - String longa, - int type, - String defaulta, - String descriptiona) + final String shorta, + final String longa, + final int type, + final String defaulta, + final String descriptiona) throws OptionsException { OptionContainer oc = new OptionContainer( @@ -53,11 +47,13 @@ public class CmdLineOpts { defaulta, descriptiona ); - if (shorta != null) opts.put(shorta, oc); - if (longa != null) opts.put(longa, oc); + if (shorta != null) + opts.put(shorta, oc); + if (longa != null) + opts.put(longa, oc); } - public void removeOption(String name) { + public void removeOption(final String name) { OptionContainer oc = opts.get(name); if (oc != null) { opts.remove(oc.shorta); @@ -65,26 +61,26 @@ public class CmdLineOpts { } } - public OptionContainer getOption(String key) throws OptionsException { + public OptionContainer getOption(final String key) throws OptionsException { OptionContainer ret = opts.get(key); - if (ret == null) throw - new OptionsException("No such option: " + key); + if (ret == null) + throw new OptionsException("No such option: " + key); return ret; } - public void processFile(File file) throws OptionsException { + public void processFile(final java.io.File file) throws OptionsException { // the file is there, parse it and set its settings - Properties prop = new Properties(); + final Properties prop = new Properties(); try { - FileInputStream in = new FileInputStream(file); + final java.io.FileInputStream in = new java.io.FileInputStream(file); try { prop.load(in); } finally { in.close(); } - for (Enumeration<?> e = prop.propertyNames(); e.hasMoreElements(); ) { + for (java.util.Enumeration<?> e = prop.propertyNames(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); OptionContainer option = opts.get(key); if (option == null) @@ -92,12 +88,12 @@ public class CmdLineOpts { option.resetArguments(); option.addArgument(prop.getProperty(key)); } - } catch (IOException e) { + } catch (java.io.IOException e) { // well... then forget about it } } - public void processArgs(String args[]) throws OptionsException { + public void processArgs(final String args[]) throws OptionsException { // parse and set the command line arguments OptionContainer option = null; int quant = -1; @@ -105,19 +101,20 @@ public class CmdLineOpts { boolean moreData = false; for (int i = 0; i < args.length; i++) { if (option == null) { - if (args[i].charAt(0) != '-') throw - new OptionsException("Unexpected value: " + args[i]); + if (args[i].charAt(0) != '-') + throw new OptionsException("Unexpected value: " + args[i]); // see what kind of argument we have if (args[i].length() == 1) throw new OptionsException("Illegal argument: '-'"); + if (args[i].charAt(1) == '-') { // we have a long argument // since we don't accept inline values we can take // everything left in the string as argument, unless // there is a = in there... - String tmp = args[i].substring(2); - int pos = tmp.indexOf('='); + final String tmp = args[i].substring(2); + final int pos = tmp.indexOf('='); if (pos == -1) { option = opts.get(tmp); moreData = false; @@ -130,8 +127,8 @@ public class CmdLineOpts { } } else if (args[i].charAt(1) == 'X') { // extra argument, same as long argument - String tmp = args[i].substring(1); - int pos = tmp.indexOf('='); + final String tmp = args[i].substring(1); + final int pos = tmp.indexOf('='); if (pos == -1) { option = opts.get(tmp); moreData = false; @@ -152,7 +149,7 @@ public class CmdLineOpts { if (option != null) { // make sure we overwrite previously set arguments option.resetArguments(); - int card = option.getCardinality(); + final int card = option.getCardinality(); if (card == CAR_ONE) { if (moreData) { option.addArgument(args[i].substring(2)); @@ -204,17 +201,20 @@ public class CmdLineOpts { // first calculate how much space is necessary for the options int maxlen = 0; for (OptionContainer oc : options) { - String shorta = oc.getShort(); - String longa = oc.getLong(); + final String shorta = oc.getShort(); + final String longa = oc.getLong(); int len = 0; - if (shorta != null) len += shorta.length() + 1 + 1; - if (longa != null) len += longa.length() + 1 + (longa.charAt(0) == 'X' ? 0 : 1) + 1; + if (shorta != null) + len += shorta.length() + 1 + 1; + if (longa != null) + len += longa.length() + 1 + (longa.charAt(0) == 'X' ? 0 : 1) + 1; // yes, we don't care about branch mispredictions here ;) - if (maxlen < len) maxlen = len; + if (maxlen < len) + maxlen = len; } // get the individual strings - StringBuilder ret = new StringBuilder(); + final StringBuilder ret = new StringBuilder(); for (OptionContainer oc : options) { ret.append(produceHelpMessage(oc, maxlen)); } @@ -232,37 +232,45 @@ public class CmdLineOpts { * @param indentwidth padding width for the command line flags * @return the help message for the option */ - public String produceHelpMessage(OptionContainer oc, int indentwidth) { - String desc = oc.getDescription(); - if (desc == null) return ""; + public String produceHelpMessage(final OptionContainer oc, int indentwidth) { + final String desc = oc.getDescription(); + if (desc == null) + return ""; - String shorta = oc.getShort(); - String longa = oc.getLong(); + final String shorta = oc.getShort(); + final String longa = oc.getLong(); int optwidth = 0; - if (shorta != null) optwidth += shorta.length() + 1 + 1; - if (longa != null) optwidth += longa.length() + 1 + (longa.charAt(0) == 'X' ? 0 : 1) + 1; - int descwidth = 80 - indentwidth; + if (shorta != null) + optwidth += shorta.length() + 1 + 1; + if (longa != null) + optwidth += longa.length() + 1 + (longa.charAt(0) == 'X' ? 0 : 1) + 1; + final int descwidth = 80 - indentwidth; // default to with of command line flags if no width given - if (indentwidth <= 0) indentwidth = optwidth; + if (indentwidth <= 0) + indentwidth = optwidth; - StringBuilder ret = new StringBuilder(); + final StringBuilder ret = new StringBuilder(); // add the command line flags - if (shorta != null) ret.append('-').append(shorta).append(' '); + if (shorta != null) + ret.append('-').append(shorta).append(' '); if (longa != null) { ret.append('-'); - if (longa.charAt(0) != 'X') ret.append('-'); + if (longa.charAt(0) != 'X') + ret.append('-'); ret.append(longa).append(' '); } - for (int i = optwidth; i < indentwidth; i++) ret.append(' '); + for (int i = optwidth; i < indentwidth; i++) + ret.append(' '); // add the description, wrap around words int pos = 0, lastpos = 0; while (pos < desc.length()) { pos += descwidth; if (lastpos != 0) { - for (int i = 0; i < indentwidth; i++) ret.append(' '); + for (int i = 0; i < indentwidth; i++) + ret.append(' '); } if (pos >= desc.length()) { ret.append(desc.substring(lastpos)).append('\n'); @@ -277,29 +285,30 @@ public class CmdLineOpts { } pos = space; ret.append(desc.substring(lastpos, pos)).append('\n'); - while (desc.charAt(pos) == ' ') pos++; + while (desc.charAt(pos) == ' ') + pos++; lastpos = pos; } return ret.toString(); } - public class OptionContainer { - int cardinality; - String shorta; - String longa; - List<String> values = new ArrayList<String>(); - String name; - String defaulta; - String descriptiona; - boolean present; + public final class OptionContainer { + private final int cardinality; + private final String shorta; + private final String longa; + private final ArrayList<String> values = new ArrayList<String>(); + private final String name; + private final String defaulta; + private final String descriptiona; + private boolean present; public OptionContainer( - String shorta, - String longa, - int cardinality, - String defaulta, - String descriptiona) + final String shorta, + final String longa, + final int cardinality, + final String defaulta, + final String descriptiona) throws IllegalArgumentException { this.cardinality = cardinality; @@ -310,19 +319,19 @@ public class CmdLineOpts { this.present = false; if (cardinality != CAR_ZERO && - cardinality != CAR_ONE && - cardinality != CAR_ZERO_ONE && - cardinality != CAR_ZERO_MANY && - cardinality != CAR_ONE_MANY) + 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"); - if (shorta == null && longa == null) throw - new IllegalArgumentException("either a short or long argument should be given"); + if (shorta != null && shorta.length() != 1) + throw new IllegalArgumentException("short option should consist of exactly one character"); + if (shorta == null && longa == null) + throw new IllegalArgumentException("either a short or long argument should be given"); if ((cardinality == CAR_ZERO || - cardinality == CAR_ZERO_ONE || - cardinality == CAR_ZERO_MANY) && - defaulta != null) { + cardinality == CAR_ZERO_ONE || + cardinality == CAR_ZERO_MANY) && + defaulta != null) { throw new IllegalArgumentException("cannot specify a default for a (possible) zero argument option"); } @@ -330,11 +339,11 @@ public class CmdLineOpts { options.add(this); } - public void resetArguments() { + public final void resetArguments() { values.clear(); } - public void addArgument(String val) throws OptionsException { + public void addArgument(final String val) throws OptionsException { if (cardinality == CAR_ZERO) { throw new OptionsException("option " + name + " does not allow arguments"); } else if ((cardinality == CAR_ONE || @@ -347,47 +356,49 @@ public class CmdLineOpts { setPresent(); } - public void setPresent() { + public final void setPresent() { present = true; } - public boolean isPresent() { + public final boolean isPresent() { return present; } - public int getCardinality() { + public final int getCardinality() { return cardinality; } - public int getArgumentCount() { + public final int getArgumentCount() { return values.size(); } - public String getArgument() { - String ret = getArgument(1); - if (ret == null) ret = defaulta; + public final String getArgument() { + final String ret = getArgument(1); + if (ret == null) + return defaulta; return ret; } - public String getArgument(int index) { - String[] args = getArguments(); - if (index < 1 || index > args.length) return null; + public final String getArgument(final int index) { + final String[] args = getArguments(); + if (index < 1 || index > args.length) + return null; return args[index - 1]; } - public String[] getArguments() { + public final String[] getArguments() { return values.toArray(new String[values.size()]); } - public String getShort() { + public final String getShort() { return shorta; } - public String getLong() { + public final String getLong() { return longa; } - public String getDescription() { + public final String getDescription() { return descriptiona; } }
--- a/src/main/java/nl/cwi/monetdb/util/Exporter.java +++ b/src/main/java/nl/cwi/monetdb/util/Exporter.java @@ -41,7 +41,7 @@ public abstract class Exporter { /** * returns the given string between two double quotes for usage as - * identifier such as column or table name in SQL queries. + * identifier such as column or table or schema name in SQL queries. * * @param in the string to quote * @return the quoted string
--- a/src/main/java/nl/cwi/monetdb/util/Extract.java +++ b/src/main/java/nl/cwi/monetdb/util/Extract.java @@ -39,15 +39,14 @@ public class Extract { public static void extractFile(final String fromFile, final String toFile) throws FileNotFoundException, IOException { - java.io.InputStream is = new Extract().getClass().getResourceAsStream(fromFile); + final java.io.InputStream is = new Extract().getClass().getResourceAsStream(fromFile); if (is == null) { throw new FileNotFoundException("File " + fromFile + " does not exist in the JAR package."); } - BufferedReader reader = new BufferedReader(new java.io.InputStreamReader(is)); - FileWriter writer = new FileWriter(toFile, false); - + final BufferedReader reader = new BufferedReader(new java.io.InputStreamReader(is)); + final FileWriter writer = new FileWriter(toFile, false); final char[] cbuf = new char[DEFAULT_BUFSIZE]; int ret = reader.read(cbuf, 0, DEFAULT_BUFSIZE); while (ret > 0) {
--- a/src/main/java/nl/cwi/monetdb/util/OptionsException.java +++ b/src/main/java/nl/cwi/monetdb/util/OptionsException.java @@ -8,10 +8,10 @@ package nl.cwi.monetdb.util; -public class OptionsException extends Exception { +public final class OptionsException extends Exception { static final long serialVersionUID = 42L; // needed to prevent: warning: [serial] serializable class OptionsException has no definition of serialVersionUID - public OptionsException(String reason) { + public OptionsException(final String reason) { super(reason); } }
--- a/src/main/java/nl/cwi/monetdb/util/SQLExporter.java +++ b/src/main/java/nl/cwi/monetdb/util/SQLExporter.java @@ -23,10 +23,10 @@ public final class SQLExporter extends E private int outputMode; private Stack<String> lastSchema; - public final static int TYPE_OUTPUT = 1; - public final static int VALUE_INSERT = 0; - public final static int VALUE_COPY = 1; - public final static int VALUE_TABLE = 2; + public final static short TYPE_OUTPUT = 1; + public final static short VALUE_INSERT = 0; + public final static short VALUE_COPY = 1; + public final static short VALUE_TABLE = 2; public SQLExporter(final java.io.PrintWriter out) { super(out); @@ -81,14 +81,12 @@ public final class SQLExporter extends E return; } - int i; - String s; out.println("CREATE " + type + " " + fqname + " ("); // add all columns with their type, nullability and default definition ResultSet cols = dbmd.getColumns(catalog, schema, name, null); - int colNmIndex = cols.findColumn("COLUMN_NAME"); - int colTypeNmIndex = cols.findColumn("TYPE_NAME"); + final int colNmIndex = cols.findColumn("COLUMN_NAME"); + final int colTypeNmIndex = cols.findColumn("TYPE_NAME"); final ResultSetMetaData rsmd = cols.getMetaData(); final int colwidth = rsmd.getColumnDisplaySize(colNmIndex); @@ -97,12 +95,13 @@ public final class SQLExporter extends E typewidth = 13; // use minimal 13 characters for the typename (same as used in mclient) final StringBuilder sb = new StringBuilder(128); + int i; for (i = 0; cols.next(); i++) { if (i > 0) out.println(","); // print column name (with double quotes) - s = dq(cols.getString(colNmIndex)); + String s = dq(cols.getString(colNmIndex)); out.print("\t" + s + repeat(' ', (colwidth - s.length() + 3))); int ctype = cols.getInt("DATA_TYPE"); @@ -161,7 +160,7 @@ public final class SQLExporter extends E break; } if (isNotNull || hasDefault) { - int spaces = typewidth - sb.length(); + final int spaces = typewidth - sb.length(); if (spaces > 0) sb.append(repeat(' ', spaces)); if (isNotNull) @@ -191,13 +190,11 @@ public final class SQLExporter extends E // terminate the previous line out.println(","); cols.absolute(1); - out.print("\tCONSTRAINT " + dq(cols.getString("PK_NAME")) + - " PRIMARY KEY ("); - i = 0; - for (Iterator<Map.Entry<Integer, Integer>> it = seqIndex.entrySet().iterator(); - it.hasNext(); i++) - { - Map.Entry<Integer, Integer> e = it.next(); + out.print("\tCONSTRAINT " + dq(cols.getString("PK_NAME")) + " PRIMARY KEY ("); + + final Iterator<Map.Entry<Integer, Integer>> it = seqIndex.entrySet().iterator(); + for (i = 0; it.hasNext(); i++) { + final Map.Entry<Integer, Integer> e = it.next(); cols.absolute(e.getValue().intValue()); if (i > 0) out.print(", "); @@ -214,7 +211,7 @@ public final class SQLExporter extends E int colIndexNm = cols.findColumn("INDEX_NAME"); int colIndexColNm = cols.findColumn("COLUMN_NAME"); while (cols.next()) { - String idxname = cols.getString(colIndexNm); + final String idxname = cols.getString(colIndexNm); if (idxname != null && !idxname.endsWith("_pkey")) { out.println(","); out.print("\tCONSTRAINT " + dq(idxname) + " UNIQUE (" + @@ -240,12 +237,12 @@ public final class SQLExporter extends E out.println(","); out.print("\tCONSTRAINT " + dq(cols.getString("FK_NAME")) + " FOREIGN KEY ("); - boolean next; - Set<String> fk = new LinkedHashSet<String>(); + final Set<String> fk = new LinkedHashSet<String>(); fk.add(cols.getString("FKCOLUMN_NAME").intern()); - Set<String> pk = new LinkedHashSet<String>(); + final Set<String> pk = new LinkedHashSet<String>(); pk.add(cols.getString("PKCOLUMN_NAME").intern()); + boolean next; while ((next = cols.next()) && cols.getInt("KEY_SEQ") != 1) { @@ -288,7 +285,7 @@ public final class SQLExporter extends E if (cols.getBoolean("NON_UNIQUE")) { // We only process non-unique indexes here. // The unique indexes are already covered as UNIQUE constraints in the CREATE TABLE above - String idxname = cols.getString(colIndexNm); + final String idxname = cols.getString(colIndexNm); if (idxname != null && !idxname.endsWith("_fkey")) { out.print("CREATE INDEX " + dq(idxname) + " ON " + dq(cols.getString("TABLE_NAME")) + " (" + @@ -358,8 +355,8 @@ public final class SQLExporter extends E } } - private final static int AS_IS = 0; - private final static int QUOTE = 1; + private static final short AS_IS = 0; + private static final short QUOTE = 1; /** * Helper method to dump the contents of a table in SQL INSERT INTO @@ -373,15 +370,8 @@ public final class SQLExporter extends E throws SQLException { final ResultSetMetaData rsmd = rs.getMetaData(); - String statement = "INSERT INTO "; - if (!useSchema) { - String schema = rsmd.getSchemaName(1); - if (schema != null && schema.length() > 0) - statement += dq(schema) + "."; - } - statement += dq(rsmd.getTableName(1)) + " VALUES ("; - final int cols = rsmd.getColumnCount(); + // get for each output column whether it requires quotes around the value based on data type final short[] types = new short[cols +1]; for (int i = 1; i <= cols; i++) { switch (rsmd.getColumnType(i)) { @@ -409,15 +399,24 @@ public final class SQLExporter extends E types[i] = AS_IS; break; default: - types[i] = AS_IS; + // treat all other types (such as inet,url,json,objects) as complex types requiring quotes + types[i] = QUOTE; } } final StringBuilder strbuf = new StringBuilder(1024); - strbuf.append(statement); + strbuf.append("INSERT INTO "); + if (!useSchema) { + final String schema = rsmd.getSchemaName(1); + if (schema != null && !schema.isEmpty()) + strbuf.append(dq(schema)).append("."); + } + strbuf.append(dq(rsmd.getTableName(1))).append(" VALUES ("); + final int cmdpart = strbuf.length(); + while (rs.next()) { for (int i = 1; i <= cols; i++) { - String val = rs.getString(i); + final String val = rs.getString(i); if (i > 1) strbuf.append(", "); if (val == null || rs.wasNull()) { @@ -429,7 +428,7 @@ public final class SQLExporter extends E strbuf.append(");"); out.println(strbuf.toString()); // clear the variable part of the buffer contents for next data row - strbuf.setLength(statement.length()); + strbuf.setLength(cmdpart); } } @@ -451,9 +450,9 @@ public final class SQLExporter extends E final int[] width = new int[cols + 1]; final boolean[] isSigned = new boolean[cols + 1]; // used for controlling left or right alignment of data for (int j = 1; j < width.length; j++) { - int coldisplaysize = md.getColumnDisplaySize(j); - int collabellength = md.getColumnLabel(j).length(); - int maxwidth = (coldisplaysize > collabellength) ? coldisplaysize : collabellength; + final int coldisplaysize = md.getColumnDisplaySize(j); + final int collabellength = md.getColumnLabel(j).length(); + final int maxwidth = (coldisplaysize > collabellength) ? coldisplaysize : collabellength; // the minimum width should be 4 to represent: "NULL" width[j] = (maxwidth > 4) ? maxwidth : 4; isSigned[j] = md.isSigned(j); @@ -472,7 +471,7 @@ public final class SQLExporter extends E strbuf.setLength(0); // clear the buffer strbuf.append('|'); for (int j = 1; j < width.length; j++) { - String colLabel = md.getColumnLabel(j); + final String colLabel = md.getColumnLabel(j); strbuf.append(' '); strbuf.append(colLabel); strbuf.append(repeat(' ', width[j] - colLabel.length()));
--- a/src/main/java/nl/cwi/monetdb/util/SQLRestore.java +++ b/src/main/java/nl/cwi/monetdb/util/SQLRestore.java @@ -10,20 +10,17 @@ 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.MCLException; import nl.cwi.monetdb.mcl.io.BufferedMCLReader; import nl.cwi.monetdb.mcl.io.BufferedMCLWriter; import nl.cwi.monetdb.mcl.net.MapiSocket; -import nl.cwi.monetdb.mcl.parser.MCLParseException; /** * Use this class to restore an SQL dump file. */ -public class SQLRestore { +public final class SQLRestore { private final String _host; private final int _port; @@ -31,7 +28,7 @@ public class SQLRestore { private final String _password; private final String _dbName; - public SQLRestore(String host, int port, String user, String password, String dbName) throws IOException { + public SQLRestore(final String host, final int port, final String user, final String password, final String dbName) throws IOException { if (host == null || user == null || password == null || dbName == null) throw new NullPointerException(); _host = host; @@ -41,22 +38,22 @@ public class SQLRestore { _dbName = dbName; } - private static class ServerResponseReader implements Runnable { + private static final class ServerResponseReader implements Runnable { private final BufferedMCLReader _is; private final AtomicBoolean _errorState = new AtomicBoolean(false); private String _errorMessage = null; - ServerResponseReader(BufferedMCLReader is) { + ServerResponseReader(final BufferedMCLReader is) { _is = is; } public void run() { try { while (true) { - String line = _is.readLine(); + final String line = _is.readLine(); if (line == null) break; - int result = _is.getLineType(); + final int result = _is.getLineType(); switch (result) { case BufferedMCLReader.ERROR: _errorMessage = line; @@ -101,28 +98,28 @@ public class SQLRestore { * @param source file object * @throws IOException when IO exception occurred */ - public void restore(File source) throws IOException { - MapiSocket ms = new MapiSocket(); + public void restore(final File source) throws IOException { + final MapiSocket ms = new MapiSocket(); try { ms.setLanguage("sql"); ms.setDatabase(_dbName); ms.connect(_host, _port, _user, _password); - BufferedMCLWriter os = ms.getWriter(); - BufferedMCLReader reader = ms.getReader(); + final BufferedMCLWriter os = ms.getWriter(); + final BufferedMCLReader reader = ms.getReader(); - ServerResponseReader srr = new ServerResponseReader(reader); + final ServerResponseReader srr = new ServerResponseReader(reader); - Thread responseReaderThread = new Thread(srr); + final 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)); + final BufferedReader sourceData = new BufferedReader(new java.io.FileReader(source)); try { os.write('s'); // signal that a new statement (or series of) is coming while(!srr.inErrorState()) { - char[] buf = new char[4096]; - int result = sourceData.read(buf); + final char[] buf = new char[4096]; + final int result = sourceData.read(buf); if (result < 0) break; os.write(buf, 0, result); @@ -145,9 +142,9 @@ public class SQLRestore { throw new IOException(srr.getErrorMessage()); } } - } catch (MCLException e) { + } catch (nl.cwi.monetdb.mcl.MCLException e) { throw new IOException(e.getMessage()); - } catch (MCLParseException e) { + } catch (nl.cwi.monetdb.mcl.parser.MCLParseException e) { throw new IOException(e.getMessage()); } finally { ms.close(); @@ -167,12 +164,12 @@ public class SQLRestore { } // parse arguments - String host = args[0]; - int port = Integer.parseInt(args[1]); // FIXME: catch NumberFormatException - String user = args[2]; - String password = args[3]; - String dbName = args[4]; - File dumpFile = new File(args[5]); + final String host = args[0]; + final int port = Integer.parseInt(args[1]); // FIXME: catch NumberFormatException + final String user = args[2]; + final String password = args[3]; + final String dbName = args[4]; + final File dumpFile = new File(args[5]); // check arguments if (!dumpFile.isFile() || !dumpFile.canRead()) { @@ -180,7 +177,7 @@ public class SQLRestore { System.exit(1); } - SQLRestore md = new SQLRestore(host, port, user, password, dbName); + final SQLRestore md = new SQLRestore(host, port, user, password, dbName); try { System.out.println("Start restoring " + dumpFile); long duration = -System.currentTimeMillis();
--- a/src/main/java/nl/cwi/monetdb/util/XMLExporter.java +++ b/src/main/java/nl/cwi/monetdb/util/XMLExporter.java @@ -8,38 +8,36 @@ package nl.cwi.monetdb.util; -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 final class XMLExporter extends Exporter { private boolean useNil; - public final static int TYPE_NIL = 1; - public final static int VALUE_OMIT = 0; - public final static int VALUE_XSI = 1; + public static final short TYPE_NIL = 1; + public static final short VALUE_OMIT = 0; + public static final short VALUE_XSI = 1; public XMLExporter(final java.io.PrintWriter out) { super(out); } public void dumpSchema( - final DatabaseMetaData dbmd, + final java.sql.DatabaseMetaData dbmd, final String type, final String catalog, final String schema, final String name) throws SQLException { + // handle views directly if (type.indexOf("VIEW") != -1) { final String[] types = new String[1]; types[0] = type; + final ResultSet tbl = dbmd.getTables(catalog, schema, name, types); if (!tbl.next()) throw new SQLException("Whoops no data for " + name); @@ -57,7 +55,7 @@ public final class XMLExporter extends E final ResultSet cols = dbmd.getColumns(catalog, schema, name, null); String ident; - final Set<String> types = new HashSet<String>(); + final java.util.HashSet<String> types = new java.util.HashSet<String>(); // walk through the ResultSet and create the types // for a bit of a clue on the types, see this url: // http://books.xmlschemata.org/relaxng/relax-CHP-19.html @@ -352,7 +350,7 @@ public final class XMLExporter extends E */ public void dumpResultSet(final ResultSet rs) throws SQLException { // write simple XML serialisation - final ResultSetMetaData rsmd = rs.getMetaData(); + final java.sql.ResultSetMetaData rsmd = rs.getMetaData(); if (!useSchema) out.println("<" + rsmd.getSchemaName(1) + ">"); out.println("<" + rsmd.getTableName(1) + ">"); @@ -362,7 +360,7 @@ public final class XMLExporter extends E for (int i = 1; i <= rsmd.getColumnCount(); i++) { switch (rsmd.getColumnType(i)) { case Types.TIMESTAMP: - Timestamp ts = rs.getTimestamp(i); + final Timestamp ts = rs.getTimestamp(i); if ("timestamptz".equals(rsmd.getColumnTypeName(i))) { data = xsd_tstz.format(ts).toString(); } else { @@ -397,7 +395,8 @@ public final class XMLExporter extends E out.println(" </row>"); } out.println("</" + rsmd.getTableName(1) + ">"); - if (!useSchema) out.println("</" + rsmd.getSchemaName(1) + ">"); + if (!useSchema) + out.println("</" + rsmd.getSchemaName(1) + ">"); } public void setProperty(final int type, final int value) throws Exception {