You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hive.apache.org by ha...@apache.org on 2013/03/12 18:48:02 UTC
svn commit: r1455648 [2/3] - in /hive/trunk: beeline/ beeline/src/
beeline/src/java/ beeline/src/java/org/ beeline/src/java/org/apache/
beeline/src/java/org/apache/hive/ beeline/src/java/org/apache/hive/beeline/
beeline/src/java/org/apache/hive/beeline...
Added: hive/trunk/beeline/src/java/org/apache/hive/beeline/BeeLineOpts.java
URL: http://svn.apache.org/viewvc/hive/trunk/beeline/src/java/org/apache/hive/beeline/BeeLineOpts.java?rev=1455648&view=auto
==============================================================================
--- hive/trunk/beeline/src/java/org/apache/hive/beeline/BeeLineOpts.java (added)
+++ hive/trunk/beeline/src/java/org/apache/hive/beeline/BeeLineOpts.java Tue Mar 12 17:48:00 2013
@@ -0,0 +1,437 @@
+/*
+ * Copyright (c) 2002,2003,2004,2005 Marc Prud'hommeaux
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms,
+ * with or without modification, are permitted provided
+ * that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ * Neither the name of the <ORGANIZATION> nor the names
+ * of its contributors may be used to endorse or promote
+ * products derived from this software without specific
+ * prior written permission.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+ * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * This software is hosted by SourceForge.
+ * SourceForge is a trademark of VA Linux Systems, Inc.
+ */
+
+/*
+ * This source file is based on code taken from SQLLine 1.0.2
+ * The license above originally appeared in src/sqlline/SqlLine.java
+ * http://sqlline.sourceforge.net/
+ */
+package org.apache.hive.beeline;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Properties;
+import java.util.TreeSet;
+
+import jline.Completor;
+import jline.SimpleCompletor;
+import jline.Terminal;
+
+
+class BeeLineOpts implements Completor {
+ public static final int DEFAULT_MAX_WIDTH = 80;
+ public static final int DEFAULT_MAX_HEIGHT = 80;
+ public static final int DEFAULT_HEADER_INTERVAL = 100;
+ public static final String DEFAULT_ISOLATION_LEVEL =
+ "TRANSACTION_REPEATABLE_READ";
+ public static final String PROPERTY_PREFIX = "beeline.";
+ public static final String PROPERTY_NAME_EXIT =
+ PROPERTY_PREFIX + "system.exit";
+
+ private final BeeLine beeLine;
+ private boolean autosave = false;
+ private boolean silent = false;
+ private boolean color = false;
+ private boolean showHeader = true;
+ private int headerInterval = 100;
+ private boolean fastConnect = true;
+ private boolean autoCommit = false;
+ private boolean verbose = false;
+ private boolean force = false;
+ private boolean incremental = false;
+ private boolean showWarnings = false;
+ private boolean showNestedErrs = false;
+ private boolean showElapsedTime = true;
+ private String numberFormat = "default";
+ private final Terminal terminal = Terminal.setupTerminal();
+ private int maxWidth = DEFAULT_MAX_WIDTH;
+ private int maxHeight = DEFAULT_MAX_HEIGHT;
+ private int maxColumnWidth = 15;
+ int timeout = -1;
+ private String isolation = DEFAULT_ISOLATION_LEVEL;
+ private String outputFormat = "table";
+ private boolean trimScripts = true;
+
+ private final File rcFile = new File(saveDir(), "beeline.properties");
+ private String historyFile = new File(saveDir(), "history").getAbsolutePath();
+
+
+ public BeeLineOpts(BeeLine beeLine, Properties props) {
+ this.beeLine = beeLine;
+ if (terminal.getTerminalWidth() > 0) {
+ maxWidth = terminal.getTerminalWidth();
+ }
+ if (terminal.getTerminalHeight() > 0) {
+ maxHeight = terminal.getTerminalHeight();
+ }
+ loadProperties(props);
+ }
+
+
+ public Completor[] optionCompletors() {
+ return new Completor[] {this};
+ }
+
+ public String[] possibleSettingValues() {
+ List<String> vals = new LinkedList<String>();
+ vals.addAll(Arrays.asList(new String[] {"yes", "no"}));
+ return vals.toArray(new String[vals.size()]);
+ }
+
+
+ /**
+ * The save directory if HOME/.beeline/ on UNIX, and
+ * HOME/beeline/ on Windows.
+ */
+ public File saveDir() {
+ String dir = System.getProperty("beeline.rcfile");
+ if (dir != null && dir.length() > 0) {
+ return new File(dir);
+ }
+
+ File f = new File(System.getProperty("user.home"),
+ (System.getProperty("os.name").toLowerCase()
+ .indexOf("windows") != -1 ? "" : ".") + "beeline")
+ .getAbsoluteFile();
+ try {
+ f.mkdirs();
+ } catch (Exception e) {
+ }
+ return f;
+ }
+
+
+ @Override
+ public int complete(String buf, int pos, List cand) {
+ try {
+ return new SimpleCompletor(propertyNames()).complete(buf, pos, cand);
+ } catch (Throwable t) {
+ return -1;
+ }
+ }
+
+
+ public void save() throws IOException {
+ OutputStream out = new FileOutputStream(rcFile);
+ save(out);
+ out.close();
+ }
+
+ public void save(OutputStream out) throws IOException {
+ try {
+ Properties props = toProperties();
+ // don't save maxwidth: it is automatically set based on
+ // the terminal configuration
+ props.remove(PROPERTY_PREFIX + "maxwidth");
+ props.store(out, beeLine.getApplicationTitle());
+ } catch (Exception e) {
+ beeLine.handleException(e);
+ }
+ }
+
+ String[] propertyNames()
+ throws IllegalAccessException, InvocationTargetException {
+ TreeSet<String> names = new TreeSet<String>();
+
+ // get all the values from getXXX methods
+ Method[] m = getClass().getDeclaredMethods();
+ for (int i = 0; m != null && i < m.length; i++) {
+ if (!(m[i].getName().startsWith("get"))) {
+ continue;
+ }
+ if (m[i].getParameterTypes().length != 0) {
+ continue;
+ }
+ String propName = m[i].getName().substring(3).toLowerCase();
+ names.add(propName);
+ }
+ return names.toArray(new String[names.size()]);
+ }
+
+
+ public Properties toProperties()
+ throws IllegalAccessException, InvocationTargetException,
+ ClassNotFoundException {
+ Properties props = new Properties();
+
+ String[] names = propertyNames();
+ for (int i = 0; names != null && i < names.length; i++) {
+ props.setProperty(PROPERTY_PREFIX + names[i],
+ beeLine.getReflector().invoke(this, "get" + names[i], new Object[0])
+ .toString());
+ }
+ beeLine.debug("properties: " + props.toString());
+ return props;
+ }
+
+
+ public void load() throws IOException {
+ InputStream in = new FileInputStream(rcFile);
+ load(in);
+ in.close();
+ }
+
+
+ public void load(InputStream fin) throws IOException {
+ Properties p = new Properties();
+ p.load(fin);
+ loadProperties(p);
+ }
+
+
+ public void loadProperties(Properties props) {
+ for (Object element : props.keySet()) {
+ String key = element.toString();
+ if (key.equals(PROPERTY_NAME_EXIT)) {
+ // fix for sf.net bug 879422
+ continue;
+ }
+ if (key.startsWith(PROPERTY_PREFIX)) {
+ set(key.substring(PROPERTY_PREFIX.length()),
+ props.getProperty(key));
+ }
+ }
+ }
+
+ public void set(String key, String value) {
+ set(key, value, false);
+ }
+
+ public boolean set(String key, String value, boolean quiet) {
+ try {
+ beeLine.getReflector().invoke(this, "set" + key, new Object[] {value});
+ return true;
+ } catch (Exception e) {
+ if (!quiet) {
+ beeLine.error(beeLine.loc("error-setting", new Object[] {key, e}));
+ }
+ return false;
+ }
+ }
+
+ public void setFastConnect(boolean fastConnect) {
+ this.fastConnect = fastConnect;
+ }
+
+
+ public boolean getFastConnect() {
+ return fastConnect;
+ }
+
+ public void setAutoCommit(boolean autoCommit) {
+ this.autoCommit = autoCommit;
+ }
+
+ public boolean getAutoCommit() {
+ return autoCommit;
+ }
+
+ public void setVerbose(boolean verbose) {
+ this.verbose = verbose;
+ }
+
+ public boolean getVerbose() {
+ return verbose;
+ }
+
+ public void setShowWarnings(boolean showWarnings) {
+ this.showWarnings = showWarnings;
+ }
+
+ public boolean getShowWarnings() {
+ return showWarnings;
+ }
+
+ public void setShowNestedErrs(boolean showNestedErrs) {
+ this.showNestedErrs = showNestedErrs;
+ }
+
+ public boolean getShowNestedErrs() {
+ return showNestedErrs;
+ }
+
+ public void setShowElapsedTime(boolean showElapsedTime) {
+ this.showElapsedTime = showElapsedTime;
+ }
+
+ public boolean getShowElapsedTime() {
+ return showElapsedTime;
+ }
+
+ public void setNumberFormat(String numberFormat) {
+ this.numberFormat = numberFormat;
+ }
+
+ public String getNumberFormat() {
+ return numberFormat;
+ }
+
+ public void setMaxWidth(int maxWidth) {
+ this.maxWidth = maxWidth;
+ }
+
+ public int getMaxWidth() {
+ return maxWidth;
+ }
+
+ public void setMaxColumnWidth(int maxColumnWidth) {
+ this.maxColumnWidth = maxColumnWidth;
+ }
+
+ public int getMaxColumnWidth() {
+ return maxColumnWidth;
+ }
+
+ public void setTimeout(int timeout) {
+ this.timeout = timeout;
+ }
+
+ public int getTimeout() {
+ return timeout;
+ }
+
+ public void setIsolation(String isolation) {
+ this.isolation = isolation;
+ }
+
+ public String getIsolation() {
+ return isolation;
+ }
+
+ public void setHistoryFile(String historyFile) {
+ this.historyFile = historyFile;
+ }
+
+ public String getHistoryFile() {
+ return historyFile;
+ }
+
+ public void setColor(boolean color) {
+ this.color = color;
+ }
+
+ public boolean getColor() {
+ return color;
+ }
+
+ public void setShowHeader(boolean showHeader) {
+ this.showHeader = showHeader;
+ }
+
+ public boolean getShowHeader() {
+ return showHeader;
+ }
+
+ public void setHeaderInterval(int headerInterval) {
+ this.headerInterval = headerInterval;
+ }
+
+ public int getHeaderInterval() {
+ return headerInterval;
+ }
+
+ public void setForce(boolean force) {
+ this.force = force;
+ }
+
+ public boolean getForce() {
+ return force;
+ }
+
+ public void setIncremental(boolean incremental) {
+ this.incremental = incremental;
+ }
+
+ public boolean getIncremental() {
+ return incremental;
+ }
+
+ public void setSilent(boolean silent) {
+ this.silent = silent;
+ }
+
+ public boolean isSilent() {
+ return silent;
+ }
+
+ public void setAutosave(boolean autosave) {
+ this.autosave = autosave;
+ }
+
+ public boolean getAutosave() {
+ return autosave;
+ }
+
+ public void setOutputFormat(String outputFormat) {
+ this.outputFormat = outputFormat;
+ }
+
+ public String getOutputFormat() {
+ return outputFormat;
+ }
+
+ public void setTrimScripts(boolean trimScripts) {
+ this.trimScripts = trimScripts;
+ }
+
+ public boolean getTrimScripts() {
+ return trimScripts;
+ }
+
+ public void setMaxHeight(int maxHeight) {
+ this.maxHeight = maxHeight;
+ }
+
+ public int getMaxHeight() {
+ return maxHeight;
+ }
+
+ public File getPropertiesFile() {
+ return rcFile;
+ }
+}
Added: hive/trunk/beeline/src/java/org/apache/hive/beeline/BeeLineSignalHandler.java
URL: http://svn.apache.org/viewvc/hive/trunk/beeline/src/java/org/apache/hive/beeline/BeeLineSignalHandler.java?rev=1455648&view=auto
==============================================================================
--- hive/trunk/beeline/src/java/org/apache/hive/beeline/BeeLineSignalHandler.java (added)
+++ hive/trunk/beeline/src/java/org/apache/hive/beeline/BeeLineSignalHandler.java Tue Mar 12 17:48:00 2013
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2002,2003,2004,2005 Marc Prud'hommeaux
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms,
+ * with or without modification, are permitted provided
+ * that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ * Neither the name of the <ORGANIZATION> nor the names
+ * of its contributors may be used to endorse or promote
+ * products derived from this software without specific
+ * prior written permission.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+ * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * This software is hosted by SourceForge.
+ * SourceForge is a trademark of VA Linux Systems, Inc.
+ */
+
+/*
+ * This source file is based on code taken from SQLLine 1.0.2
+ * The license above originally appeared in src/sqlline/SqlLine.java
+ * http://sqlline.sourceforge.net/
+ */
+
+package org.apache.hive.beeline;
+
+import java.sql.Statement;
+
+
+/**
+ * BeeLineSignalHandler.
+ *
+ */
+public interface BeeLineSignalHandler {
+ public void setStatement(Statement stmt);
+}
Added: hive/trunk/beeline/src/java/org/apache/hive/beeline/BufferedRows.java
URL: http://svn.apache.org/viewvc/hive/trunk/beeline/src/java/org/apache/hive/beeline/BufferedRows.java?rev=1455648&view=auto
==============================================================================
--- hive/trunk/beeline/src/java/org/apache/hive/beeline/BufferedRows.java (added)
+++ hive/trunk/beeline/src/java/org/apache/hive/beeline/BufferedRows.java Tue Mar 12 17:48:00 2013
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2002,2003,2004,2005 Marc Prud'hommeaux
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms,
+ * with or without modification, are permitted provided
+ * that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ * Neither the name of the <ORGANIZATION> nor the names
+ * of its contributors may be used to endorse or promote
+ * products derived from this software without specific
+ * prior written permission.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+ * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * This software is hosted by SourceForge.
+ * SourceForge is a trademark of VA Linux Systems, Inc.
+ */
+
+/*
+ * This source file is based on code taken from SQLLine 1.0.2
+ * The license above originally appeared in src/sqlline/SqlLine.java
+ * http://sqlline.sourceforge.net/
+ */
+package org.apache.hive.beeline;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Iterator;
+import java.util.LinkedList;
+
+/**
+ * Rows implementation which buffers all rows in a linked list.
+ */
+class BufferedRows extends Rows {
+ private final LinkedList<Row> list;
+ private final Iterator<Row> iterator;
+
+ BufferedRows(BeeLine beeLine, ResultSet rs) throws SQLException {
+ super(beeLine, rs);
+ list = new LinkedList<Row>();
+ int count = rsMeta.getColumnCount();
+ list.add(new Row(count));
+ while (rs.next()) {
+ list.add(new Row(count, rs));
+ }
+ iterator = list.iterator();
+ }
+
+ public boolean hasNext() {
+ return iterator.hasNext();
+ }
+
+ public Object next() {
+ return iterator.next();
+ }
+
+ @Override
+ void normalizeWidths() {
+ int[] max = null;
+ for (Row row : list) {
+ if (max == null) {
+ max = new int[row.values.length];
+ }
+ for (int j = 0; j < max.length; j++) {
+ max[j] = Math.max(max[j], row.sizes[j] + 1);
+ }
+ }
+ for (Row row : list) {
+ row.sizes = max;
+ }
+ }
+
+}
Added: hive/trunk/beeline/src/java/org/apache/hive/beeline/ColorBuffer.java
URL: http://svn.apache.org/viewvc/hive/trunk/beeline/src/java/org/apache/hive/beeline/ColorBuffer.java?rev=1455648&view=auto
==============================================================================
--- hive/trunk/beeline/src/java/org/apache/hive/beeline/ColorBuffer.java (added)
+++ hive/trunk/beeline/src/java/org/apache/hive/beeline/ColorBuffer.java Tue Mar 12 17:48:00 2013
@@ -0,0 +1,261 @@
+/*
+ * Copyright (c) 2002,2003,2004,2005 Marc Prud'hommeaux
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms,
+ * with or without modification, are permitted provided
+ * that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ * Neither the name of the <ORGANIZATION> nor the names
+ * of its contributors may be used to endorse or promote
+ * products derived from this software without specific
+ * prior written permission.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+ * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * This software is hosted by SourceForge.
+ * SourceForge is a trademark of VA Linux Systems, Inc.
+ */
+
+/*
+ * This source file is based on code taken from SQLLine 1.0.2
+ * The license above originally appeared in src/sqlline/SqlLine.java
+ * http://sqlline.sourceforge.net/
+ */
+package org.apache.hive.beeline;
+
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * A buffer that can output segments using ANSI color.
+ *
+ */
+final class ColorBuffer implements Comparable<Object> {
+ private static final ColorBuffer.ColorAttr BOLD = new ColorAttr("\033[1m");
+ private static final ColorBuffer.ColorAttr NORMAL = new ColorAttr("\033[m");
+ private static final ColorBuffer.ColorAttr REVERS = new ColorAttr("\033[7m");
+ private static final ColorBuffer.ColorAttr LINED = new ColorAttr("\033[4m");
+ private static final ColorBuffer.ColorAttr GREY = new ColorAttr("\033[1;30m");
+ private static final ColorBuffer.ColorAttr RED = new ColorAttr("\033[1;31m");
+ private static final ColorBuffer.ColorAttr GREEN = new ColorAttr("\033[1;32m");
+ private static final ColorBuffer.ColorAttr BLUE = new ColorAttr("\033[1;34m");
+ private static final ColorBuffer.ColorAttr CYAN = new ColorAttr("\033[1;36m");
+ private static final ColorBuffer.ColorAttr YELLOW = new ColorAttr("\033[1;33m");
+ private static final ColorBuffer.ColorAttr MAGENTA = new ColorAttr("\033[1;35m");
+ private static final ColorBuffer.ColorAttr INVISIBLE = new ColorAttr("\033[8m");
+
+ private final List<Object> parts = new LinkedList<Object>();
+ private int visibleLength = 0;
+
+ private final boolean useColor;
+
+
+ public ColorBuffer(boolean useColor) {
+ this.useColor = useColor;
+ append("");
+ }
+
+ public ColorBuffer(String str, boolean useColor) {
+ this.useColor = useColor;
+ append(str);
+ }
+
+ /**
+ * Pad the specified String with spaces to the indicated length
+ *
+ * @param str
+ * the String to pad
+ * @param len
+ * the length we want the return String to be
+ * @return the passed in String with spaces appended until the
+ * length matches the specified length.
+ */
+ ColorBuffer pad(ColorBuffer str, int len) {
+ while (str.getVisibleLength() < len) {
+ str.append(" ");
+ }
+ return append(str);
+ }
+
+ ColorBuffer center(String str, int len) {
+ StringBuilder buf = new StringBuilder(str);
+ while (buf.length() < len) {
+ buf.append(" ");
+ if (buf.length() < len) {
+ buf.insert(0, " ");
+ }
+ }
+ return append(buf.toString());
+ }
+
+ ColorBuffer pad(String str, int len) {
+ if (str == null) {
+ str = "";
+ }
+ return pad(new ColorBuffer(str, false), len);
+ }
+
+ public String getColor() {
+ return getBuffer(useColor);
+ }
+
+ public String getMono() {
+ return getBuffer(false);
+ }
+
+ String getBuffer(boolean color) {
+ StringBuilder buf = new StringBuilder();
+ for (Object part : parts) {
+ if (!color && part instanceof ColorBuffer.ColorAttr) {
+ continue;
+ }
+ buf.append(part.toString());
+ }
+ return buf.toString();
+ }
+
+
+ /**
+ * Truncate the ColorBuffer to the specified length and return
+ * the new ColorBuffer. Any open color tags will be closed.
+ * Do nothing if the specified length is <= 0.
+ */
+ public ColorBuffer truncate(int len) {
+ if (len <= 0) {
+ return this;
+ }
+ ColorBuffer cbuff = new ColorBuffer(useColor);
+ ColorBuffer.ColorAttr lastAttr = null;
+ for (Iterator<Object> i = parts.iterator(); cbuff.getVisibleLength() < len && i.hasNext();) {
+ Object next = i.next();
+ if (next instanceof ColorBuffer.ColorAttr) {
+ lastAttr = (ColorBuffer.ColorAttr) next;
+ cbuff.append((ColorBuffer.ColorAttr) next);
+ continue;
+ }
+ String val = next.toString();
+ if (cbuff.getVisibleLength() + val.length() > len) {
+ int partLen = len - cbuff.getVisibleLength();
+ val = val.substring(0, partLen);
+ }
+ cbuff.append(val);
+ }
+
+ // close off the buffer with a normal tag
+ if (lastAttr != null && lastAttr != NORMAL) {
+ cbuff.append(NORMAL);
+ }
+
+ return cbuff;
+ }
+
+
+ @Override
+ public String toString() {
+ return getColor();
+ }
+
+ public ColorBuffer append(String str) {
+ parts.add(str);
+ visibleLength += str.length();
+ return this;
+ }
+
+ public ColorBuffer append(ColorBuffer buf) {
+ parts.addAll(buf.parts);
+ visibleLength += buf.getVisibleLength();
+ return this;
+ }
+
+ private ColorBuffer append(ColorBuffer.ColorAttr attr) {
+ parts.add(attr);
+ return this;
+ }
+
+ public int getVisibleLength() {
+ return visibleLength;
+ }
+
+ private ColorBuffer append(ColorBuffer.ColorAttr attr, String val) {
+ parts.add(attr);
+ parts.add(val);
+ parts.add(NORMAL);
+ visibleLength += val.length();
+ return this;
+ }
+
+ public ColorBuffer bold(String str) {
+ return append(BOLD, str);
+ }
+
+ public ColorBuffer lined(String str) {
+ return append(LINED, str);
+ }
+
+ public ColorBuffer grey(String str) {
+ return append(GREY, str);
+ }
+
+ public ColorBuffer red(String str) {
+ return append(RED, str);
+ }
+
+ public ColorBuffer blue(String str) {
+ return append(BLUE, str);
+ }
+
+ public ColorBuffer green(String str) {
+ return append(GREEN, str);
+ }
+
+ public ColorBuffer cyan(String str) {
+ return append(CYAN, str);
+ }
+
+ public ColorBuffer yellow(String str) {
+ return append(YELLOW, str);
+ }
+
+ public ColorBuffer magenta(String str) {
+ return append(MAGENTA, str);
+ }
+
+ private static class ColorAttr {
+ private final String attr;
+
+ public ColorAttr(String attr) {
+ this.attr = attr;
+ }
+
+ @Override
+ public String toString() {
+ return attr;
+ }
+ }
+
+ public int compareTo(Object other) {
+ return getMono().compareTo(((ColorBuffer) other).getMono());
+ }
+}
\ No newline at end of file
Added: hive/trunk/beeline/src/java/org/apache/hive/beeline/CommandHandler.java
URL: http://svn.apache.org/viewvc/hive/trunk/beeline/src/java/org/apache/hive/beeline/CommandHandler.java?rev=1455648&view=auto
==============================================================================
--- hive/trunk/beeline/src/java/org/apache/hive/beeline/CommandHandler.java (added)
+++ hive/trunk/beeline/src/java/org/apache/hive/beeline/CommandHandler.java Tue Mar 12 17:48:00 2013
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2002,2003,2004,2005 Marc Prud'hommeaux
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms,
+ * with or without modification, are permitted provided
+ * that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ * Neither the name of the <ORGANIZATION> nor the names
+ * of its contributors may be used to endorse or promote
+ * products derived from this software without specific
+ * prior written permission.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+ * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * This software is hosted by SourceForge.
+ * SourceForge is a trademark of VA Linux Systems, Inc.
+ */
+
+/*
+ * This source file is based on code taken from SQLLine 1.0.2
+ * The license above originally appeared in src/sqlline/SqlLine.java
+ * http://sqlline.sourceforge.net/
+ */
+package org.apache.hive.beeline;
+
+import jline.Completor;
+
+/**
+ * A generic command to be executed. Execution of the command
+ * should be dispatched to the {@link #execute(java.lang.String)} method after determining that
+ * the command is appropriate with
+ * the {@link #matches(java.lang.String)} method.
+ *
+ */
+interface CommandHandler {
+ /**
+ * @return the name of the command
+ */
+ public String getName();
+
+
+ /**
+ * @return all the possible names of this command.
+ */
+ public String[] getNames();
+
+
+ /**
+ * @return the short help description for this command.
+ */
+ public String getHelpText();
+
+
+ /**
+ * Check to see if the specified string can be dispatched to this
+ * command.
+ *
+ * @param line
+ * the command line to check.
+ * @return the command string that matches, or null if it no match
+ */
+ public String matches(String line);
+
+
+ /**
+ * Execute the specified command.
+ *
+ * @param line
+ * the full command line to execute.
+ */
+ public boolean execute(String line);
+
+
+ /**
+ * Returns the completors that can handle parameters.
+ */
+ public Completor[] getParameterCompletors();
+}
\ No newline at end of file
Added: hive/trunk/beeline/src/java/org/apache/hive/beeline/Commands.java
URL: http://svn.apache.org/viewvc/hive/trunk/beeline/src/java/org/apache/hive/beeline/Commands.java?rev=1455648&view=auto
==============================================================================
--- hive/trunk/beeline/src/java/org/apache/hive/beeline/Commands.java (added)
+++ hive/trunk/beeline/src/java/org/apache/hive/beeline/Commands.java Tue Mar 12 17:48:00 2013
@@ -0,0 +1,1298 @@
+/*
+ * Copyright (c) 2002,2003,2004,2005 Marc Prud'hommeaux
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms,
+ * with or without modification, are permitted provided
+ * that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ * Neither the name of the <ORGANIZATION> nor the names
+ * of its contributors may be used to endorse or promote
+ * products derived from this software without specific
+ * prior written permission.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+ * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * This software is hosted by SourceForge.
+ * SourceForge is a trademark of VA Linux Systems, Inc.
+ */
+
+/*
+ * This source file is based on code taken from SQLLine 1.0.2
+ * The license above originally appeared in src/sqlline/SqlLine.java
+ * http://sqlline.sourceforge.net/
+ */
+package org.apache.hive.beeline;
+
+import java.io.BufferedReader;
+import java.io.FileInputStream;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.lang.reflect.Method;
+import java.sql.CallableStatement;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.Driver;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
+import java.util.TreeSet;
+
+
+public class Commands {
+ private final BeeLine beeLine;
+
+ /**
+ * @param beeLine
+ */
+ Commands(BeeLine beeLine) {
+ this.beeLine = beeLine;
+ }
+
+
+ public boolean metadata(String line) {
+ beeLine.debug(line);
+
+ String[] parts = beeLine.split(line);
+ List<String> params = new LinkedList<String>(Arrays.asList(parts));
+ if (parts == null || parts.length == 0) {
+ return dbinfo("");
+ }
+
+ params.remove(0);
+ params.remove(0);
+ beeLine.debug(params.toString());
+ return metadata(parts[1],
+ params.toArray(new String[0]));
+ }
+
+
+ public boolean metadata(String cmd, String[] args) {
+ try {
+ Method[] m = beeLine.getDatabaseConnection().getDatabaseMetaData().getClass().getMethods();
+ Set<String> methodNames = new TreeSet<String>();
+ Set<String> methodNamesUpper = new TreeSet<String>();
+ for (int i = 0; i < m.length; i++) {
+ methodNames.add(m[i].getName());
+ methodNamesUpper.add(m[i].getName().toUpperCase());
+ }
+
+ if (!methodNamesUpper.contains(cmd.toUpperCase())) {
+ beeLine.error(beeLine.loc("no-such-method", cmd));
+ beeLine.error(beeLine.loc("possible-methods"));
+ for (Iterator<String> i = methodNames.iterator(); i.hasNext();) {
+ beeLine.error(" " + i.next());
+ }
+ return false;
+ }
+
+ Object res = beeLine.getReflector().invoke(beeLine.getDatabaseConnection().getDatabaseMetaData(),
+ DatabaseMetaData.class, cmd, Arrays.asList(args));
+
+ if (res instanceof ResultSet) {
+ ResultSet rs = (ResultSet) res;
+ if (rs != null) {
+ try {
+ beeLine.print(rs);
+ } finally {
+ rs.close();
+ }
+ }
+ } else if (res != null) {
+ beeLine.output(res.toString());
+ }
+ } catch (Exception e) {
+ return beeLine.error(e);
+ }
+
+ return true;
+ }
+
+
+ public boolean history(String line) {
+ List hist = beeLine.getConsoleReader().getHistory().getHistoryList();
+ int index = 1;
+ for (Iterator i = hist.iterator(); i.hasNext(); index++) {
+ beeLine.output(beeLine.getColorBuffer().pad(index + ".", 6)
+ .append(i.next().toString()));
+ }
+ return true;
+ }
+
+
+ String arg1(String line, String paramname) {
+ return arg1(line, paramname, null);
+ }
+
+
+ String arg1(String line, String paramname, String def) {
+ String[] ret = beeLine.split(line);
+
+ if (ret == null || ret.length != 2) {
+ if (def != null) {
+ return def;
+ }
+ throw new IllegalArgumentException(beeLine.loc("arg-usage",
+ new Object[] {ret.length == 0 ? "" : ret[0],
+ paramname}));
+ }
+ return ret[1];
+ }
+
+
+ public boolean indexes(String line) throws Exception {
+ return metadata("getIndexInfo", new String[] {
+ beeLine.getConnection().getCatalog(), null,
+ arg1(line, "table name"),
+ false + "",
+ true + ""});
+ }
+
+
+ public boolean primarykeys(String line) throws Exception {
+ return metadata("getPrimaryKeys", new String[] {
+ beeLine.getConnection().getCatalog(), null,
+ arg1(line, "table name"),});
+ }
+
+
+ public boolean exportedkeys(String line) throws Exception {
+ return metadata("getExportedKeys", new String[] {
+ beeLine.getConnection().getCatalog(), null,
+ arg1(line, "table name"),});
+ }
+
+
+ public boolean importedkeys(String line) throws Exception {
+ return metadata("getImportedKeys", new String[] {
+ beeLine.getConnection().getCatalog(), null,
+ arg1(line, "table name"),});
+ }
+
+
+ public boolean procedures(String line) throws Exception {
+ return metadata("getProcedures", new String[] {
+ beeLine.getConnection().getCatalog(), null,
+ arg1(line, "procedure name pattern", "%"),});
+ }
+
+
+ public boolean tables(String line) throws Exception {
+ return metadata("getTables", new String[] {
+ beeLine.getConnection().getCatalog(), null,
+ arg1(line, "table name", "%"), null});
+ }
+
+
+ public boolean typeinfo(String line) throws Exception {
+ return metadata("getTypeInfo", new String[0]);
+ }
+
+
+ public boolean nativesql(String sql) throws Exception {
+ if (sql.startsWith(BeeLine.COMMAND_PREFIX)) {
+ sql = sql.substring(1);
+ }
+ if (sql.startsWith("native")) {
+ sql = sql.substring("native".length() + 1);
+ }
+ String nat = beeLine.getDatabaseConnection().getConnection().nativeSQL(sql);
+ beeLine.output(nat);
+ return true;
+ }
+
+
+ public boolean columns(String line) throws Exception {
+ return metadata("getColumns", new String[] {
+ beeLine.getConnection().getCatalog(), null,
+ arg1(line, "table name"), "%"});
+ }
+
+
+ public boolean dropall(String line) {
+ if (beeLine.getDatabaseConnection() == null || beeLine.getDatabaseConnection().getUrl() == null) {
+ return beeLine.error(beeLine.loc("no-current-connection"));
+ }
+ try {
+ if (!(beeLine.getConsoleReader().readLine(beeLine.loc("really-drop-all")).equals("y"))) {
+ return beeLine.error("abort-drop-all");
+ }
+
+ List<String> cmds = new LinkedList<String>();
+ ResultSet rs = beeLine.getTables();
+ try {
+ while (rs.next()) {
+ cmds.add("DROP TABLE "
+ + rs.getString("TABLE_NAME") + ";");
+ }
+ } finally {
+ try {
+ rs.close();
+ } catch (Exception e) {
+ }
+ }
+ // run as a batch
+ return beeLine.runCommands(cmds) == cmds.size();
+ } catch (Exception e) {
+ return beeLine.error(e);
+ }
+ }
+
+
+ public boolean reconnect(String line) {
+ if (beeLine.getDatabaseConnection() == null || beeLine.getDatabaseConnection().getUrl() == null) {
+ return beeLine.error(beeLine.loc("no-current-connection"));
+ }
+ beeLine.info(beeLine.loc("reconnecting", beeLine.getDatabaseConnection().getUrl()));
+ try {
+ beeLine.getDatabaseConnection().reconnect();
+ } catch (Exception e) {
+ return beeLine.error(e);
+ }
+ return true;
+ }
+
+
+ public boolean scan(String line) throws IOException {
+ TreeSet<String> names = new TreeSet<String>();
+
+ if (beeLine.getDrivers() == null) {
+ beeLine.setDrivers(Arrays.asList(beeLine.scanDrivers(line)));
+ }
+
+ beeLine.info(beeLine.loc("drivers-found-count", beeLine.getDrivers().size()));
+
+ // unique the list
+ for (Iterator<Driver> i = beeLine.getDrivers().iterator(); i.hasNext();) {
+ names.add(i.next().getClass().getName());
+ }
+
+ beeLine.output(beeLine.getColorBuffer()
+ .bold(beeLine.getColorBuffer().pad(beeLine.loc("compliant"), 10).getMono())
+ .bold(beeLine.getColorBuffer().pad(beeLine.loc("jdbc-version"), 8).getMono())
+ .bold(beeLine.getColorBuffer(beeLine.loc("driver-class")).getMono()));
+
+ for (Iterator<String> i = names.iterator(); i.hasNext();) {
+ String name = i.next().toString();
+ try {
+ Driver driver = (Driver) Class.forName(name).newInstance();
+ ColorBuffer msg = beeLine.getColorBuffer()
+ .pad(driver.jdbcCompliant() ? "yes" : "no", 10)
+ .pad(driver.getMajorVersion() + "."
+ + driver.getMinorVersion(), 8)
+ .append(name);
+ if (driver.jdbcCompliant()) {
+ beeLine.output(msg);
+ } else {
+ beeLine.output(beeLine.getColorBuffer().red(msg.getMono()));
+ }
+ } catch (Throwable t) {
+ beeLine.output(beeLine.getColorBuffer().red(name)); // error with driver
+ }
+ }
+ return true;
+ }
+
+
+ public boolean save(String line) throws IOException {
+ beeLine.info(beeLine.loc("saving-options", beeLine.getOpts().getPropertiesFile()));
+ beeLine.getOpts().save();
+ return true;
+ }
+
+
+ public boolean load(String line) throws IOException {
+ beeLine.getOpts().load();
+ beeLine.info(beeLine.loc("loaded-options", beeLine.getOpts().getPropertiesFile()));
+ return true;
+ }
+
+
+ public boolean config(String line) {
+ try {
+ Properties props = beeLine.getOpts().toProperties();
+ Set keys = new TreeSet(props.keySet());
+ for (Iterator i = keys.iterator(); i.hasNext();) {
+ String key = (String) i.next();
+ beeLine.output(beeLine.getColorBuffer()
+ .green(beeLine.getColorBuffer().pad(key.substring(
+ beeLine.getOpts().PROPERTY_PREFIX.length()), 20)
+ .getMono())
+ .append(props.getProperty(key)));
+ }
+ } catch (Exception e) {
+ return beeLine.error(e);
+ }
+ return true;
+ }
+
+
+ public boolean set(String line) {
+ if (line == null || line.trim().equals("set")
+ || line.length() == 0) {
+ return config(null);
+ }
+
+ String[] parts = beeLine.split(line, 3, "Usage: set <key> <value>");
+ if (parts == null) {
+ return false;
+ }
+
+ String key = parts[1];
+ String value = parts[2];
+ boolean success = beeLine.getOpts().set(key, value, false);
+ // if we autosave, then save
+ if (success && beeLine.getOpts().getAutosave()) {
+ try {
+ beeLine.getOpts().save();
+ } catch (Exception saveException) {
+ }
+ }
+ return success;
+ }
+
+
+ public boolean commit(String line) throws SQLException {
+ if (!(beeLine.assertConnection())) {
+ return false;
+ }
+ if (!(beeLine.assertAutoCommit())) {
+ return false;
+ }
+ try {
+ long start = System.currentTimeMillis();
+ beeLine.getDatabaseConnection().getConnection().commit();
+ long end = System.currentTimeMillis();
+ beeLine.showWarnings();
+ beeLine.info(beeLine.loc("commit-complete")
+ + " " + beeLine.locElapsedTime(end - start));
+ return true;
+ } catch (Exception e) {
+ return beeLine.error(e);
+ }
+ }
+
+
+ public boolean rollback(String line) throws SQLException {
+ if (!(beeLine.assertConnection())) {
+ return false;
+ }
+ if (!(beeLine.assertAutoCommit())) {
+ return false;
+ }
+ try {
+ long start = System.currentTimeMillis();
+ beeLine.getDatabaseConnection().getConnection().rollback();
+ long end = System.currentTimeMillis();
+ beeLine.showWarnings();
+ beeLine.info(beeLine.loc("rollback-complete")
+ + " " + beeLine.locElapsedTime(end - start));
+ return true;
+ } catch (Exception e) {
+ return beeLine.error(e);
+ }
+ }
+
+
+ public boolean autocommit(String line) throws SQLException {
+ if (!(beeLine.assertConnection())) {
+ return false;
+ }
+ if (line.endsWith("on")) {
+ beeLine.getDatabaseConnection().getConnection().setAutoCommit(true);
+ } else if (line.endsWith("off")) {
+ beeLine.getDatabaseConnection().getConnection().setAutoCommit(false);
+ }
+ beeLine.showWarnings();
+ beeLine.autocommitStatus(beeLine.getDatabaseConnection().getConnection());
+ return true;
+ }
+
+
+ public boolean dbinfo(String line) {
+ if (!(beeLine.assertConnection())) {
+ return false;
+ }
+
+ beeLine.showWarnings();
+ int padlen = 50;
+
+ String[] m = new String[] {
+ "allProceduresAreCallable",
+ "allTablesAreSelectable",
+ "dataDefinitionCausesTransactionCommit",
+ "dataDefinitionIgnoredInTransactions",
+ "doesMaxRowSizeIncludeBlobs",
+ "getCatalogSeparator",
+ "getCatalogTerm",
+ "getDatabaseProductName",
+ "getDatabaseProductVersion",
+ "getDefaultTransactionIsolation",
+ "getDriverMajorVersion",
+ "getDriverMinorVersion",
+ "getDriverName",
+ "getDriverVersion",
+ "getExtraNameCharacters",
+ "getIdentifierQuoteString",
+ "getMaxBinaryLiteralLength",
+ "getMaxCatalogNameLength",
+ "getMaxCharLiteralLength",
+ "getMaxColumnNameLength",
+ "getMaxColumnsInGroupBy",
+ "getMaxColumnsInIndex",
+ "getMaxColumnsInOrderBy",
+ "getMaxColumnsInSelect",
+ "getMaxColumnsInTable",
+ "getMaxConnections",
+ "getMaxCursorNameLength",
+ "getMaxIndexLength",
+ "getMaxProcedureNameLength",
+ "getMaxRowSize",
+ "getMaxSchemaNameLength",
+ "getMaxStatementLength",
+ "getMaxStatements",
+ "getMaxTableNameLength",
+ "getMaxTablesInSelect",
+ "getMaxUserNameLength",
+ "getNumericFunctions",
+ "getProcedureTerm",
+ "getSchemaTerm",
+ "getSearchStringEscape",
+ "getSQLKeywords",
+ "getStringFunctions",
+ "getSystemFunctions",
+ "getTimeDateFunctions",
+ "getURL",
+ "getUserName",
+ "isCatalogAtStart",
+ "isReadOnly",
+ "nullPlusNonNullIsNull",
+ "nullsAreSortedAtEnd",
+ "nullsAreSortedAtStart",
+ "nullsAreSortedHigh",
+ "nullsAreSortedLow",
+ "storesLowerCaseIdentifiers",
+ "storesLowerCaseQuotedIdentifiers",
+ "storesMixedCaseIdentifiers",
+ "storesMixedCaseQuotedIdentifiers",
+ "storesUpperCaseIdentifiers",
+ "storesUpperCaseQuotedIdentifiers",
+ "supportsAlterTableWithAddColumn",
+ "supportsAlterTableWithDropColumn",
+ "supportsANSI92EntryLevelSQL",
+ "supportsANSI92FullSQL",
+ "supportsANSI92IntermediateSQL",
+ "supportsBatchUpdates",
+ "supportsCatalogsInDataManipulation",
+ "supportsCatalogsInIndexDefinitions",
+ "supportsCatalogsInPrivilegeDefinitions",
+ "supportsCatalogsInProcedureCalls",
+ "supportsCatalogsInTableDefinitions",
+ "supportsColumnAliasing",
+ "supportsConvert",
+ "supportsCoreSQLGrammar",
+ "supportsCorrelatedSubqueries",
+ "supportsDataDefinitionAndDataManipulationTransactions",
+ "supportsDataManipulationTransactionsOnly",
+ "supportsDifferentTableCorrelationNames",
+ "supportsExpressionsInOrderBy",
+ "supportsExtendedSQLGrammar",
+ "supportsFullOuterJoins",
+ "supportsGroupBy",
+ "supportsGroupByBeyondSelect",
+ "supportsGroupByUnrelated",
+ "supportsIntegrityEnhancementFacility",
+ "supportsLikeEscapeClause",
+ "supportsLimitedOuterJoins",
+ "supportsMinimumSQLGrammar",
+ "supportsMixedCaseIdentifiers",
+ "supportsMixedCaseQuotedIdentifiers",
+ "supportsMultipleResultSets",
+ "supportsMultipleTransactions",
+ "supportsNonNullableColumns",
+ "supportsOpenCursorsAcrossCommit",
+ "supportsOpenCursorsAcrossRollback",
+ "supportsOpenStatementsAcrossCommit",
+ "supportsOpenStatementsAcrossRollback",
+ "supportsOrderByUnrelated",
+ "supportsOuterJoins",
+ "supportsPositionedDelete",
+ "supportsPositionedUpdate",
+ "supportsSchemasInDataManipulation",
+ "supportsSchemasInIndexDefinitions",
+ "supportsSchemasInPrivilegeDefinitions",
+ "supportsSchemasInProcedureCalls",
+ "supportsSchemasInTableDefinitions",
+ "supportsSelectForUpdate",
+ "supportsStoredProcedures",
+ "supportsSubqueriesInComparisons",
+ "supportsSubqueriesInExists",
+ "supportsSubqueriesInIns",
+ "supportsSubqueriesInQuantifieds",
+ "supportsTableCorrelationNames",
+ "supportsTransactions",
+ "supportsUnion",
+ "supportsUnionAll",
+ "usesLocalFilePerTable",
+ "usesLocalFiles",
+ };
+
+ for (int i = 0; i < m.length; i++) {
+ try {
+ beeLine.output(beeLine.getColorBuffer().pad(m[i], padlen).append(
+ "" + beeLine.getReflector().invoke(beeLine.getDatabaseConnection().getDatabaseMetaData(),
+ m[i], new Object[0])));
+ } catch (Exception e) {
+ beeLine.handleException(e);
+ }
+ }
+ return true;
+ }
+
+
+ public boolean verbose(String line) {
+ beeLine.info("verbose: on");
+ return set("set verbose true");
+ }
+
+
+ public boolean outputformat(String line) {
+ return set("set " + line);
+ }
+
+
+ public boolean brief(String line) {
+ beeLine.info("verbose: off");
+ return set("set verbose false");
+ }
+
+
+ public boolean isolation(String line) throws SQLException {
+ if (!(beeLine.assertConnection())) {
+ return false;
+ }
+
+ int i;
+
+ if (line.endsWith("TRANSACTION_NONE")) {
+ i = Connection.TRANSACTION_NONE;
+ } else if (line.endsWith("TRANSACTION_READ_COMMITTED")) {
+ i = Connection.TRANSACTION_READ_COMMITTED;
+ } else if (line.endsWith("TRANSACTION_READ_UNCOMMITTED")) {
+ i = Connection.TRANSACTION_READ_UNCOMMITTED;
+ } else if (line.endsWith("TRANSACTION_REPEATABLE_READ")) {
+ i = Connection.TRANSACTION_REPEATABLE_READ;
+ } else if (line.endsWith("TRANSACTION_SERIALIZABLE")) {
+ i = Connection.TRANSACTION_SERIALIZABLE;
+ } else {
+ return beeLine.error("Usage: isolation <TRANSACTION_NONE "
+ + "| TRANSACTION_READ_COMMITTED "
+ + "| TRANSACTION_READ_UNCOMMITTED "
+ + "| TRANSACTION_REPEATABLE_READ "
+ + "| TRANSACTION_SERIALIZABLE>");
+ }
+
+ beeLine.getDatabaseConnection().getConnection().setTransactionIsolation(i);
+
+ int isol = beeLine.getDatabaseConnection().getConnection().getTransactionIsolation();
+ final String isoldesc;
+ switch (i)
+ {
+ case Connection.TRANSACTION_NONE:
+ isoldesc = "TRANSACTION_NONE";
+ break;
+ case Connection.TRANSACTION_READ_COMMITTED:
+ isoldesc = "TRANSACTION_READ_COMMITTED";
+ break;
+ case Connection.TRANSACTION_READ_UNCOMMITTED:
+ isoldesc = "TRANSACTION_READ_UNCOMMITTED";
+ break;
+ case Connection.TRANSACTION_REPEATABLE_READ:
+ isoldesc = "TRANSACTION_REPEATABLE_READ";
+ break;
+ case Connection.TRANSACTION_SERIALIZABLE:
+ isoldesc = "TRANSACTION_SERIALIZABLE";
+ break;
+ default:
+ isoldesc = "UNKNOWN";
+ }
+
+ beeLine.info(beeLine.loc("isolation-status", isoldesc));
+ return true;
+ }
+
+
+ public boolean batch(String line) {
+ if (!(beeLine.assertConnection())) {
+ return false;
+ }
+ if (beeLine.getBatch() == null) {
+ beeLine.setBatch(new LinkedList<String>());
+ beeLine.info(beeLine.loc("batch-start"));
+ return true;
+ } else {
+ beeLine.info(beeLine.loc("running-batch"));
+ try {
+ beeLine.runBatch(beeLine.getBatch());
+ return true;
+ } catch (Exception e) {
+ return beeLine.error(e);
+ } finally {
+ beeLine.setBatch(null);
+ }
+ }
+ }
+
+ public boolean sql(String line) {
+ return execute(line, false);
+ }
+
+ public boolean call(String line) {
+ return execute(line, true);
+ }
+
+ private boolean execute(String line, boolean call) {
+ if (line == null || line.length() == 0) {
+ return false; // ???
+ }
+
+ // ### FIXME: doing the multi-line handling down here means
+ // higher-level logic never sees the extra lines. So,
+ // for example, if a script is being saved, it won't include
+ // the continuation lines! This is logged as sf.net
+ // bug 879518.
+
+ // use multiple lines for statements not terminated by ";"
+ try {
+ while (!(line.trim().endsWith(";"))) {
+ StringBuilder prompt = new StringBuilder(beeLine.getPrompt());
+ for (int i = 0; i < prompt.length() - 1; i++) {
+ if (prompt.charAt(i) != '>') {
+ prompt.setCharAt(i, i % 2 == 0 ? '.' : ' ');
+ }
+ }
+
+ String extra = beeLine.getConsoleReader().readLine(prompt.toString());
+ if (!beeLine.isComment(extra)) {
+ line += " " + extra;
+ }
+ }
+ } catch (Exception e) {
+ beeLine.handleException(e);
+ }
+
+ if (line.endsWith(";")) {
+ line = line.substring(0, line.length() - 1);
+ }
+
+ if (!(beeLine.assertConnection())) {
+ return false;
+ }
+
+ String sql = line;
+
+ if (sql.startsWith(BeeLine.COMMAND_PREFIX)) {
+ sql = sql.substring(1);
+ }
+
+ String prefix = call ? "call" : "sql";
+
+ if (sql.startsWith(prefix)) {
+ sql = sql.substring(prefix.length());
+ }
+
+ // batch statements?
+ if (beeLine.getBatch() != null) {
+ beeLine.getBatch().add(sql);
+ return true;
+ }
+
+ try {
+ Statement stmnt = null;
+ boolean hasResults;
+
+ try {
+ long start = System.currentTimeMillis();
+
+ if (call) {
+ stmnt = beeLine.getDatabaseConnection().getConnection().prepareCall(sql);
+ hasResults = ((CallableStatement) stmnt).execute();
+ } else {
+ stmnt = beeLine.createStatement();
+ hasResults = stmnt.execute(sql);
+ }
+
+ beeLine.showWarnings();
+
+ if (hasResults) {
+ do {
+ ResultSet rs = stmnt.getResultSet();
+ try {
+ int count = beeLine.print(rs);
+ long end = System.currentTimeMillis();
+
+ beeLine.info(beeLine.loc("rows-selected", count) + " "
+ + beeLine.locElapsedTime(end - start));
+ } finally {
+ rs.close();
+ }
+ } while (BeeLine.getMoreResults(stmnt));
+ } else {
+ int count = stmnt.getUpdateCount();
+ long end = System.currentTimeMillis();
+ beeLine.info(beeLine.loc("rows-affected", count)
+ + " " + beeLine.locElapsedTime(end - start));
+ }
+ } catch (Exception e) {
+ beeLine.error(e);
+ throw e;
+ } finally {
+ if (stmnt != null) {
+ stmnt.close();
+ }
+ }
+ } catch (Exception e) {
+ return beeLine.error(e);
+ }
+ beeLine.showWarnings();
+ return true;
+ }
+
+
+ public boolean quit(String line) {
+ beeLine.setExit(true);
+ close(null);
+ return true;
+ }
+
+
+ /**
+ * Close all connections.
+ */
+ public boolean closeall(String line) {
+ if (close(null)) {
+ while (close(null)) {
+ ;
+ }
+ return true;
+ }
+ return false;
+ }
+
+
+ /**
+ * Close the current connection.
+ */
+ public boolean close(String line) {
+ if (beeLine.getDatabaseConnection() == null) {
+ return false;
+ }
+ try {
+ if (beeLine.getDatabaseConnection().getConnection() != null
+ && !(beeLine.getDatabaseConnection().getConnection().isClosed())) {
+ beeLine.info(beeLine.loc("closing",
+ beeLine.getDatabaseConnection().getConnection().getClass().getName()));
+ beeLine.getDatabaseConnection().getConnection().close();
+ } else {
+ beeLine.info(beeLine.loc("already-closed"));
+ }
+ } catch (Exception e) {
+ return beeLine.error(e);
+ }
+ beeLine.getDatabaseConnections().remove();
+ return true;
+ }
+
+
+ /**
+ * Connect to the database defined in the specified properties file.
+ */
+ public boolean properties(String line) throws Exception {
+ String example = "";
+ example += "Usage: properties <properties file>" + BeeLine.getSeparator();
+
+ String[] parts = beeLine.split(line);
+ if (parts.length < 2) {
+ return beeLine.error(example);
+ }
+
+ int successes = 0;
+
+ for (int i = 1; i < parts.length; i++) {
+ Properties props = new Properties();
+ props.load(new FileInputStream(parts[i]));
+ if (connect(props)) {
+ successes++;
+ }
+ }
+
+ if (successes != (parts.length - 1)) {
+ return false;
+ } else {
+ return true;
+ }
+ }
+
+
+ public boolean connect(String line) throws Exception {
+ String example = "Usage: connect <url> <username> <password> [driver]"
+ + BeeLine.getSeparator();
+
+ String[] parts = beeLine.split(line);
+ if (parts == null) {
+ return false;
+ }
+
+ if (parts.length < 2) {
+ return beeLine.error(example);
+ }
+
+ String url = parts.length < 2 ? null : parts[1];
+ String user = parts.length < 3 ? null : parts[2];
+ String pass = parts.length < 4 ? null : parts[3];
+ String driver = parts.length < 5 ? null : parts[4];
+
+ Properties props = new Properties();
+ if (url != null) {
+ props.setProperty("url", url);
+ }
+ if (driver != null) {
+ props.setProperty("driver", driver);
+ }
+ if (user != null) {
+ props.setProperty("user", user);
+ }
+ if (pass != null) {
+ props.setProperty("password", pass);
+ }
+ return connect(props);
+ }
+
+
+ private String getProperty(Properties props, String[] keys) {
+ for (int i = 0; i < keys.length; i++) {
+ String val = props.getProperty(keys[i]);
+ if (val != null) {
+ return val;
+ }
+ }
+
+ for (Iterator i = props.keySet().iterator(); i.hasNext();) {
+ String key = (String) i.next();
+ for (int j = 0; j < keys.length; j++) {
+ if (key.endsWith(keys[j])) {
+ return props.getProperty(key);
+ }
+ }
+ }
+
+ return null;
+ }
+
+
+ public boolean connect(Properties props) throws IOException {
+ String url = getProperty(props, new String[] {
+ "url",
+ "javax.jdo.option.ConnectionURL",
+ "ConnectionURL",
+ });
+ String driver = getProperty(props, new String[] {
+ "driver",
+ "javax.jdo.option.ConnectionDriverName",
+ "ConnectionDriverName",
+ });
+ String username = getProperty(props, new String[] {
+ "user",
+ "javax.jdo.option.ConnectionUserName",
+ "ConnectionUserName",
+ });
+ String password = getProperty(props, new String[] {
+ "password",
+ "javax.jdo.option.ConnectionPassword",
+ "ConnectionPassword",
+ });
+
+ if (url == null || url.length() == 0) {
+ return beeLine.error("Property \"url\" is required");
+ }
+ if (driver == null || driver.length() == 0) {
+ if (!beeLine.scanForDriver(url)) {
+ return beeLine.error(beeLine.loc("no-driver", url));
+ }
+ }
+
+ beeLine.info("Connecting to " + url);
+
+ if (username == null) {
+ username = beeLine.getConsoleReader().readLine("Enter username for " + url + ": ");
+ }
+ if (password == null) {
+ password = beeLine.getConsoleReader().readLine("Enter password for " + url + ": ",
+ new Character('*'));
+ }
+
+ try {
+ beeLine.getDatabaseConnections().setConnection(
+ new DatabaseConnection(beeLine, driver, url, username, password));
+ beeLine.getDatabaseConnection().getConnection();
+
+ beeLine.setCompletions();
+ return true;
+ } catch (SQLException sqle) {
+ return beeLine.error(sqle);
+ } catch (IOException ioe) {
+ return beeLine.error(ioe);
+ }
+ }
+
+
+ public boolean rehash(String line) {
+ try {
+ if (!(beeLine.assertConnection())) {
+ return false;
+ }
+ if (beeLine.getDatabaseConnection() != null) {
+ beeLine.getDatabaseConnection().setCompletions(false);
+ }
+ return true;
+ } catch (Exception e) {
+ return beeLine.error(e);
+ }
+ }
+
+
+ /**
+ * List the current connections
+ */
+ public boolean list(String line) {
+ int index = 0;
+ beeLine.info(beeLine.loc("active-connections", beeLine.getDatabaseConnections().size()));
+
+ for (Iterator<DatabaseConnection> i = beeLine.getDatabaseConnections().iterator(); i.hasNext(); index++) {
+ DatabaseConnection c = i.next();
+ boolean closed = false;
+ try {
+ closed = c.getConnection().isClosed();
+ } catch (Exception e) {
+ closed = true;
+ }
+
+ beeLine.output(beeLine.getColorBuffer().pad(" #" + index + "", 5)
+ .pad(closed ? beeLine.loc("closed") : beeLine.loc("open"), 9)
+ .append(c.getUrl()));
+ }
+
+ return true;
+ }
+
+
+ public boolean all(String line) {
+ int index = beeLine.getDatabaseConnections().getIndex();
+ boolean success = true;
+
+ for (int i = 0; i < beeLine.getDatabaseConnections().size(); i++) {
+ beeLine.getDatabaseConnections().setIndex(i);
+ beeLine.output(beeLine.loc("executing-con", beeLine.getDatabaseConnection()));
+ // ### FIXME: this is broken for multi-line SQL
+ success = sql(line.substring("all ".length())) && success;
+ }
+
+ // restore index
+ beeLine.getDatabaseConnections().setIndex(index);
+ return success;
+ }
+
+
+ public boolean go(String line) {
+ String[] parts = beeLine.split(line, 2, "Usage: go <connection index>");
+ if (parts == null) {
+ return false;
+ }
+ int index = Integer.parseInt(parts[1]);
+ if (!(beeLine.getDatabaseConnections().setIndex(index))) {
+ beeLine.error(beeLine.loc("invalid-connection", "" + index));
+ list(""); // list the current connections
+ return false;
+ }
+ return true;
+ }
+
+
+ /**
+ * Save or stop saving a script to a file
+ */
+ public boolean script(String line) {
+ if (beeLine.getScriptOutputFile() == null) {
+ return startScript(line);
+ } else {
+ return stopScript(line);
+ }
+ }
+
+
+ /**
+ * Stop writing to the script file and close the script.
+ */
+ private boolean stopScript(String line) {
+ try {
+ beeLine.getScriptOutputFile().close();
+ } catch (Exception e)
+ {
+ beeLine.handleException(e);
+ }
+
+ beeLine.output(beeLine.loc("script-closed", beeLine.getScriptOutputFile()));
+ beeLine.setScriptOutputFile(null);
+ return true;
+ }
+
+
+ /**
+ * Start writing to the specified script file.
+ */
+ private boolean startScript(String line) {
+ if (beeLine.getScriptOutputFile() != null) {
+ return beeLine.error(beeLine.loc("script-already-running", beeLine.getScriptOutputFile()));
+ }
+
+ String[] parts = beeLine.split(line, 2, "Usage: script <filename>");
+ if (parts == null) {
+ return false;
+ }
+
+ try {
+ beeLine.setScriptOutputFile(new OutputFile(parts[1]));
+ beeLine.output(beeLine.loc("script-started", beeLine.getScriptOutputFile()));
+ return true;
+ } catch (Exception e) {
+ return beeLine.error(e);
+ }
+ }
+
+
+ /**
+ * Run a script from the specified file.
+ */
+ public boolean run(String line) {
+ String[] parts = beeLine.split(line, 2, "Usage: run <scriptfile>");
+ if (parts == null) {
+ return false;
+ }
+
+ List<String> cmds = new LinkedList<String>();
+
+ try {
+ BufferedReader reader = new BufferedReader(new FileReader(
+ parts[1]));
+ try {
+ // ### NOTE: fix for sf.net bug 879427
+ StringBuilder cmd = null;
+ for (;;) {
+ String scriptLine = reader.readLine();
+
+ if (scriptLine == null) {
+ break;
+ }
+
+ String trimmedLine = scriptLine.trim();
+ if (beeLine.getOpts().getTrimScripts()) {
+ scriptLine = trimmedLine;
+ }
+
+ if (cmd != null) {
+ // we're continuing an existing command
+ cmd.append(" \n");
+ cmd.append(scriptLine);
+ if (trimmedLine.endsWith(";")) {
+ // this command has terminated
+ cmds.add(cmd.toString());
+ cmd = null;
+ }
+ } else {
+ // we're starting a new command
+ if (beeLine.needsContinuation(scriptLine)) {
+ // multi-line
+ cmd = new StringBuilder(scriptLine);
+ } else {
+ // single-line
+ cmds.add(scriptLine);
+ }
+ }
+ }
+
+ if (cmd != null) {
+ // ### REVIEW: oops, somebody left the last command
+ // unterminated; should we fix it for them or complain?
+ // For now be nice and fix it.
+ cmd.append(";");
+ cmds.add(cmd.toString());
+ }
+ } finally {
+ reader.close();
+ }
+
+ // success only if all the commands were successful
+ return beeLine.runCommands(cmds) == cmds.size();
+ } catch (Exception e) {
+ return beeLine.error(e);
+ }
+ }
+
+
+ /**
+ * Save or stop saving all output to a file.
+ */
+ public boolean record(String line) {
+ if (beeLine.getRecordOutputFile() == null) {
+ return startRecording(line);
+ } else {
+ return stopRecording(line);
+ }
+ }
+
+
+ /**
+ * Stop writing output to the record file.
+ */
+ private boolean stopRecording(String line) {
+ try {
+ beeLine.getRecordOutputFile().close();
+ } catch (Exception e) {
+ beeLine.handleException(e);
+ }
+ beeLine.output(beeLine.loc("record-closed", beeLine.getRecordOutputFile()));
+ beeLine.setRecordOutputFile(null);
+ return true;
+ }
+
+
+ /**
+ * Start writing to the specified record file.
+ */
+ private boolean startRecording(String line) {
+ if (beeLine.getRecordOutputFile() != null) {
+ return beeLine.error(beeLine.loc("record-already-running", beeLine.getRecordOutputFile()));
+ }
+
+ String[] parts = beeLine.split(line, 2, "Usage: record <filename>");
+ if (parts == null) {
+ return false;
+ }
+
+ try {
+ beeLine.setRecordOutputFile(new OutputFile(parts[1]));
+ beeLine.output(beeLine.loc("record-started", beeLine.getRecordOutputFile()));
+ return true;
+ } catch (Exception e) {
+ return beeLine.error(e);
+ }
+ }
+
+
+
+
+ public boolean describe(String line) throws SQLException {
+ String[] table = beeLine.split(line, 2, "Usage: describe <table name>");
+ if (table == null) {
+ return false;
+ }
+
+ ResultSet rs;
+
+ if (table[1].equals("tables")) {
+ rs = beeLine.getTables();
+ } else {
+ rs = beeLine.getColumns(table[1]);
+ }
+
+ if (rs == null) {
+ return false;
+ }
+
+ beeLine.print(rs);
+ rs.close();
+ return true;
+ }
+
+
+ public boolean help(String line) {
+ String[] parts = beeLine.split(line);
+ String cmd = parts.length > 1 ? parts[1] : "";
+ int count = 0;
+ TreeSet<ColorBuffer> clist = new TreeSet<ColorBuffer>();
+
+ for (int i = 0; i < beeLine.commandHandlers.length; i++) {
+ if (cmd.length() == 0 ||
+ Arrays.asList(beeLine.commandHandlers[i].getNames()).contains(cmd)) {
+ clist.add(beeLine.getColorBuffer().pad("!" + beeLine.commandHandlers[i].getName(), 20)
+ .append(beeLine.wrap(beeLine.commandHandlers[i].getHelpText(), 60, 20)));
+ }
+ }
+
+ for (Iterator<ColorBuffer> i = clist.iterator(); i.hasNext();) {
+ beeLine.output(i.next());
+ }
+
+ if (cmd.length() == 0) {
+ beeLine.output("");
+ beeLine.output(beeLine.loc("comments", beeLine.getApplicationContactInformation()));
+ }
+
+ return true;
+ }
+
+
+ public boolean manual(String line) throws IOException {
+ InputStream in = BeeLine.class.getResourceAsStream("manual.txt");
+ if (in == null) {
+ return beeLine.error(beeLine.loc("no-manual"));
+ }
+
+ BufferedReader breader = new BufferedReader(
+ new InputStreamReader(in));
+ String man;
+ int index = 0;
+ while ((man = breader.readLine()) != null) {
+ index++;
+ beeLine.output(man);
+
+ // silly little pager
+ if (index % (beeLine.getOpts().getMaxHeight() - 1) == 0) {
+ String ret = beeLine.getConsoleReader().readLine(beeLine.loc("enter-for-more"));
+ if (ret != null && ret.startsWith("q")) {
+ break;
+ }
+ }
+ }
+ breader.close();
+ return true;
+ }
+}
Added: hive/trunk/beeline/src/java/org/apache/hive/beeline/DatabaseConnection.java
URL: http://svn.apache.org/viewvc/hive/trunk/beeline/src/java/org/apache/hive/beeline/DatabaseConnection.java?rev=1455648&view=auto
==============================================================================
--- hive/trunk/beeline/src/java/org/apache/hive/beeline/DatabaseConnection.java (added)
+++ hive/trunk/beeline/src/java/org/apache/hive/beeline/DatabaseConnection.java Tue Mar 12 17:48:00 2013
@@ -0,0 +1,318 @@
+/*
+ * Copyright (c) 2002,2003,2004,2005 Marc Prud'hommeaux
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms,
+ * with or without modification, are permitted provided
+ * that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ * Neither the name of the <ORGANIZATION> nor the names
+ * of its contributors may be used to endorse or promote
+ * products derived from this software without specific
+ * prior written permission.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+ * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * This software is hosted by SourceForge.
+ * SourceForge is a trademark of VA Linux Systems, Inc.
+ */
+
+/*
+ * This source file is based on code taken from SQLLine 1.0.2
+ * The license above originally appeared in src/sqlline/SqlLine.java
+ * http://sqlline.sourceforge.net/
+ */
+package org.apache.hive.beeline;
+
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+
+import jline.ArgumentCompletor;
+import jline.Completor;
+
+class DatabaseConnection {
+ private final BeeLine beeLine;
+ private Connection connection;
+ private DatabaseMetaData meta;
+ private final String driver;
+ private final String url;
+ private final String username;
+ private final String password;
+ private Schema schema = null;
+ private Completor sqlCompletor = null;
+
+
+ public DatabaseConnection(BeeLine beeLine, String driver, String url,
+ String username, String password) throws SQLException {
+ this.beeLine = beeLine;
+ this.driver = driver;
+ this.url = url;
+ this.username = username;
+ this.password = password;
+ }
+
+
+ @Override
+ public String toString() {
+ return getUrl() + "";
+ }
+
+
+ void setCompletions(boolean skipmeta) throws SQLException, IOException {
+ final String extraNameCharacters =
+ getDatabaseMetaData() == null || getDatabaseMetaData().getExtraNameCharacters() == null ? ""
+ : getDatabaseMetaData().getExtraNameCharacters();
+
+ // setup the completor for the database
+ sqlCompletor = new ArgumentCompletor(
+ new SQLCompletor(beeLine, skipmeta),
+ new ArgumentCompletor.AbstractArgumentDelimiter() {
+ // delimiters for SQL statements are any
+ // non-letter-or-number characters, except
+ // underscore and characters that are specified
+ // by the database to be valid name identifiers.
+ @Override
+ public boolean isDelimiterChar(String buf, int pos) {
+ char c = buf.charAt(pos);
+ if (Character.isWhitespace(c)) {
+ return true;
+ }
+ return !(Character.isLetterOrDigit(c))
+ && c != '_'
+ && extraNameCharacters.indexOf(c) == -1;
+ }
+ });
+
+ // not all argument elements need to hold true
+ ((ArgumentCompletor) sqlCompletor).setStrict(false);
+ }
+
+
+ /**
+ * Connection to the specified data source.
+ *
+ * @param driver
+ * the driver class
+ * @param url
+ * the connection URL
+ * @param username
+ * the username
+ * @param password
+ * the password
+ */
+ boolean connect() throws SQLException {
+ try {
+ if (driver != null && driver.length() != 0) {
+ Class.forName(driver);
+ }
+ } catch (ClassNotFoundException cnfe) {
+ return beeLine.error(cnfe);
+ }
+
+ boolean foundDriver = false;
+ try {
+ foundDriver = DriverManager.getDriver(getUrl()) != null;
+ } catch (Exception e) {
+ }
+
+ try {
+ close();
+ } catch (Exception e) {
+ return beeLine.error(e);
+ }
+
+ setConnection(DriverManager.getConnection(getUrl(), username, password));
+ setDatabaseMetaData(getConnection().getMetaData());
+
+ try {
+ beeLine.info(beeLine.loc("connected", new Object[] {
+ getDatabaseMetaData().getDatabaseProductName(),
+ getDatabaseMetaData().getDatabaseProductVersion()}));
+ } catch (Exception e) {
+ beeLine.handleException(e);
+ }
+
+ try {
+ beeLine.info(beeLine.loc("driver", new Object[] {
+ getDatabaseMetaData().getDriverName(),
+ getDatabaseMetaData().getDriverVersion()}));
+ } catch (Exception e) {
+ beeLine.handleException(e);
+ }
+
+ try {
+ getConnection().setAutoCommit(beeLine.getOpts().getAutoCommit());
+ // TODO: Setting autocommit should not generate an exception as long as it is set to false
+ // beeLine.autocommitStatus(getConnection());
+ } catch (Exception e) {
+ beeLine.handleException(e);
+ }
+
+ try {
+ beeLine.getCommands().isolation("isolation: " + beeLine.getOpts().getIsolation());
+ } catch (Exception e) {
+ beeLine.handleException(e);
+ }
+
+ return true;
+ }
+
+
+ public Connection getConnection() throws SQLException {
+ if (connection != null) {
+ return connection;
+ }
+ connect();
+ return connection;
+ }
+
+
+ public void reconnect() throws Exception {
+ close();
+ getConnection();
+ }
+
+
+ public void close() {
+ try {
+ try {
+ if (connection != null && !connection.isClosed()) {
+ beeLine.output(beeLine.loc("closing", connection));
+ connection.close();
+ }
+ } catch (Exception e) {
+ beeLine.handleException(e);
+ }
+ } finally {
+ setConnection(null);
+ setDatabaseMetaData(null);
+ }
+ }
+
+
+ public String[] getTableNames(boolean force) {
+ Schema.Table[] t = getSchema().getTables();
+ Set<String> names = new TreeSet<String>();
+ for (int i = 0; t != null && i < t.length; i++) {
+ names.add(t[i].getName());
+ }
+ return names.toArray(new String[names.size()]);
+ }
+
+ Schema getSchema() {
+ if (schema == null) {
+ schema = new Schema();
+ }
+ return schema;
+ }
+
+ void setConnection(Connection connection) {
+ this.connection = connection;
+ }
+
+ DatabaseMetaData getDatabaseMetaData() {
+ return meta;
+ }
+
+ void setDatabaseMetaData(DatabaseMetaData meta) {
+ this.meta = meta;
+ }
+
+ String getUrl() {
+ return url;
+ }
+
+ Completor getSQLCompletor() {
+ return sqlCompletor;
+ }
+
+ class Schema {
+ private Table[] tables = null;
+
+ Table[] getTables() {
+ if (tables != null) {
+ return tables;
+ }
+
+ List<Table> tnames = new LinkedList<Table>();
+
+ try {
+ ResultSet rs = getDatabaseMetaData().getTables(getConnection().getCatalog(),
+ null, "%", new String[] {"TABLE"});
+ try {
+ while (rs.next()) {
+ tnames.add(new Table(rs.getString("TABLE_NAME")));
+ }
+ } finally {
+ try {
+ rs.close();
+ } catch (Exception e) {
+ }
+ }
+ } catch (Throwable t) {
+ }
+ return tables = tnames.toArray(new Table[0]);
+ }
+
+ Table getTable(String name) {
+ Table[] t = getTables();
+ for (int i = 0; t != null && i < t.length; i++) {
+ if (name.equalsIgnoreCase(t[i].getName())) {
+ return t[i];
+ }
+ }
+ return null;
+ }
+
+ class Table {
+ final String name;
+ Column[] columns;
+
+ public Table(String name) {
+ this.name = name;
+ }
+
+
+ public String getName() {
+ return name;
+ }
+
+ class Column {
+ final String name;
+ boolean isPrimaryKey;
+
+ public Column(String name) {
+ this.name = name;
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
Added: hive/trunk/beeline/src/java/org/apache/hive/beeline/DatabaseConnections.java
URL: http://svn.apache.org/viewvc/hive/trunk/beeline/src/java/org/apache/hive/beeline/DatabaseConnections.java?rev=1455648&view=auto
==============================================================================
--- hive/trunk/beeline/src/java/org/apache/hive/beeline/DatabaseConnections.java (added)
+++ hive/trunk/beeline/src/java/org/apache/hive/beeline/DatabaseConnections.java Tue Mar 12 17:48:00 2013
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2002,2003,2004,2005 Marc Prud'hommeaux
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms,
+ * with or without modification, are permitted provided
+ * that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ * Neither the name of the <ORGANIZATION> nor the names
+ * of its contributors may be used to endorse or promote
+ * products derived from this software without specific
+ * prior written permission.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+ * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * This software is hosted by SourceForge.
+ * SourceForge is a trademark of VA Linux Systems, Inc.
+ */
+
+/*
+ * This source file is based on code taken from SQLLine 1.0.2
+ * The license above originally appeared in src/sqlline/SqlLine.java
+ * http://sqlline.sourceforge.net/
+ */
+package org.apache.hive.beeline;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+class DatabaseConnections {
+ private final List<DatabaseConnection> connections = new ArrayList<DatabaseConnection>();
+ private int index = -1;
+
+ public DatabaseConnection current() {
+ if (index != -1) {
+ return connections.get(index);
+ }
+ return null;
+ }
+
+ public int size() {
+ return connections.size();
+ }
+
+ public Iterator<DatabaseConnection> iterator() {
+ return connections.iterator();
+ }
+
+ public void remove() {
+ if (index != -1) {
+ connections.remove(index);
+ }
+ while (index >= connections.size()) {
+ index--;
+ }
+ }
+
+ public void setConnection(DatabaseConnection connection) {
+ if (connections.indexOf(connection) == -1) {
+ connections.add(connection);
+ }
+ index = connections.indexOf(connection);
+ }
+
+ public int getIndex() {
+ return index;
+ }
+
+
+ public boolean setIndex(int index) {
+ if (index < 0 || index >= connections.size()) {
+ return false;
+ }
+ this.index = index;
+ return true;
+ }
+}
\ No newline at end of file
Added: hive/trunk/beeline/src/java/org/apache/hive/beeline/DriverInfo.java
URL: http://svn.apache.org/viewvc/hive/trunk/beeline/src/java/org/apache/hive/beeline/DriverInfo.java?rev=1455648&view=auto
==============================================================================
--- hive/trunk/beeline/src/java/org/apache/hive/beeline/DriverInfo.java (added)
+++ hive/trunk/beeline/src/java/org/apache/hive/beeline/DriverInfo.java Tue Mar 12 17:48:00 2013
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2002,2003,2004,2005 Marc Prud'hommeaux
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms,
+ * with or without modification, are permitted provided
+ * that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ * Neither the name of the <ORGANIZATION> nor the names
+ * of its contributors may be used to endorse or promote
+ * products derived from this software without specific
+ * prior written permission.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+ * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * This software is hosted by SourceForge.
+ * SourceForge is a trademark of VA Linux Systems, Inc.
+ */
+
+/*
+ * This source file is based on code taken from SQLLine 1.0.2
+ * The license above originally appeared in src/sqlline/SqlLine.java
+ * http://sqlline.sourceforge.net/
+ */
+package org.apache.hive.beeline;
+
+import java.io.IOException;
+import java.util.Properties;
+
+public class DriverInfo {
+ public String sampleURL;
+
+ public DriverInfo(String name) throws IOException {
+ Properties props = new Properties();
+ props.load(DriverInfo.class.getResourceAsStream(name));
+ fromProperties(props);
+ }
+
+ public DriverInfo(Properties props) {
+ fromProperties(props);
+ }
+
+ public void fromProperties(Properties props) {
+ }
+}
\ No newline at end of file
Added: hive/trunk/beeline/src/java/org/apache/hive/beeline/IncrementalRows.java
URL: http://svn.apache.org/viewvc/hive/trunk/beeline/src/java/org/apache/hive/beeline/IncrementalRows.java?rev=1455648&view=auto
==============================================================================
--- hive/trunk/beeline/src/java/org/apache/hive/beeline/IncrementalRows.java (added)
+++ hive/trunk/beeline/src/java/org/apache/hive/beeline/IncrementalRows.java Tue Mar 12 17:48:00 2013
@@ -0,0 +1,129 @@
+/*
+ * Copyright (c) 2002,2003,2004,2005 Marc Prud'hommeaux
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms,
+ * with or without modification, are permitted provided
+ * that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ * Neither the name of the <ORGANIZATION> nor the names
+ * of its contributors may be used to endorse or promote
+ * products derived from this software without specific
+ * prior written permission.
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
+ * AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+ * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * This software is hosted by SourceForge.
+ * SourceForge is a trademark of VA Linux Systems, Inc.
+ */
+
+/*
+ * This source file is based on code taken from SQLLine 1.0.2
+ * The license above originally appeared in src/sqlline/SqlLine.java
+ * http://sqlline.sourceforge.net/
+ */
+package org.apache.hive.beeline;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.NoSuchElementException;
+
+/**
+ * Rows implementation which returns rows incrementally from result set
+ * without any buffering.
+ */
+public class IncrementalRows extends Rows {
+ private final ResultSet rs;
+ private final Row labelRow;
+ private final Row maxRow;
+ private Row nextRow;
+ private boolean endOfResult;
+ private boolean normalizingWidths;
+
+
+ IncrementalRows(BeeLine beeLine, ResultSet rs) throws SQLException {
+ super(beeLine, rs);
+ this.rs = rs;
+
+ labelRow = new Row(rsMeta.getColumnCount());
+ maxRow = new Row(rsMeta.getColumnCount());
+ int maxWidth = beeLine.getOpts().getMaxColumnWidth();
+
+ // pre-compute normalization so we don't have to deal
+ // with SQLExceptions later
+ for (int i = 0; i < maxRow.sizes.length; ++i) {
+ // normalized display width is based on maximum of display size
+ // and label size
+ maxRow.sizes[i] = Math.max(
+ maxRow.sizes[i],
+ rsMeta.getColumnDisplaySize(i + 1));
+ maxRow.sizes[i] = Math.min(maxWidth, maxRow.sizes[i]);
+ }
+
+ nextRow = labelRow;
+ endOfResult = false;
+ }
+
+
+ public boolean hasNext() {
+ if (endOfResult) {
+ return false;
+ }
+
+ if (nextRow == null) {
+ try {
+ if (rs.next()) {
+ nextRow = new Row(labelRow.sizes.length, rs);
+
+ if (normalizingWidths) {
+ // perform incremental normalization
+ nextRow.sizes = labelRow.sizes;
+ }
+ } else {
+ endOfResult = true;
+ }
+ } catch (SQLException ex) {
+ throw new RuntimeException(ex.toString());
+ }
+ }
+ return (nextRow != null);
+ }
+
+ public Object next() {
+ if (!hasNext()) {
+ throw new NoSuchElementException();
+ }
+ Object ret = nextRow;
+ nextRow = null;
+ return ret;
+ }
+
+ @Override
+ void normalizeWidths() {
+ // normalize label row
+ labelRow.sizes = maxRow.sizes;
+ // and remind ourselves to perform incremental normalization
+ // for each row as it is produced
+ normalizingWidths = true;
+ }
+}