Package org.hsqldb.cmdline.sqltool

Examples of org.hsqldb.cmdline.sqltool.Token


    synchronized protected void scanpass(TokenSource ts)
                                     throws SqlToolError, SQLException {
        boolean rollbackUncoms = true;
        String nestingCommand;
        Matcher inlineNestMatcher;
        Token token = null;
        sqlExpandMode = null;

        try {
            while (true) try {
                if (preempt) {
                    token = buffer;
                    preempt = false;
                } else {
                    token = ts.yylex();
                    logger.finest("SqlFile got new token:  " + token);
                }
                if (token == null) break;

                inlineNestMatcher = inlineNestMatcher(token);
                if (inlineNestMatcher != null) {
                    processInlineBlock(token,
                            inlineNestMatcher.group(1),
                            inlineNestMatcher.group(2));
                    processBlock(token);
                    continue;
                }

                nestingCommand = nestingCommand(token);
                if (nestingCommand != null) {
                    if (token.nestedBlock == null)
                        token.nestedBlock = seekTokenSource(nestingCommand);
                        /* This command (and the same recursive call inside
                         * of the seekTokenSource() method) ensure that all
                         * "blocks" are tokenized immediately as block
                         * commands are encountered, and the blocks are
                         * tokenized in their entirety all the way to the
                         * leaves.
                         */
                    processBlock(token);
                        /* processBlock recurses through scanpass(),
                         * which processes the nested commands which have
                         * (in all cases) already beeen tokenized.
                         */
                    continue;
                }

                switch (token.type) {
                    case Token.SYNTAX_ERR_TYPE:
                        throw new SqlToolError(
                                SqltoolRB.input_malformat.getString());
                        // Will get here if Scanner can't match input to any
                        // known command type.
                        // An easy way to get here is to start a command with
                        // quotes.
                    case Token.UNTERM_TYPE:
                        throw new SqlToolError(
                                SqltoolRB.input_unterminated.getString(
                                token.val));
                    case Token.RAW_TYPE:
                    case Token.RAWEXEC_TYPE:
                        /*
                         * A real problem in this block is that the Scanner
                         * has already displayed the next prompt at this
                         * point.  We handle this specially within this
                         * block, but if we throw, the handler will not
                         * know that the prompt has to be re-displayed.
                         * I.e., KNOWN ISSUE:  For some errors caught during
                         * raw command execution, interactive users will not
                         * get a prompt to tell them to proceed.
                         */
                        if (token.val == null) token.val = "";
                        /*
                         * Don't have time know to figure out whether it would
                         * ever be useful to send just (non-zero) whitespace
                         * to the DB.  Prohibiting for now.
                         */
                        if (token.val.trim().length() < 1)
                            throw new SqlToolError(
                                    SqltoolRB.raw_empty.getString());
                        int receivedType = token.type;
                        token.type = Token.SQL_TYPE;
                        if (setBuf(token) && receivedType == Token.RAW_TYPE
                                && interactive) {
                            stdprintln("");
                            stdprintln(SqltoolRB.raw_movedtobuffer.getString());
                            stdprint(primaryPrompt);
                            // All of these stdprint*'s are to work around a
                            // very complicated issue where the Scanner
                            // has already displayed the next prompt before
                            // we can display our status message.
                        }
                        if (receivedType == Token.RAWEXEC_TYPE) {
                            historize();
                            ResultSet rs = null;
                            Statement statement = processSQL();
                            if (statement != null) {
                                try {
                                    rs = statement.getResultSet();
                                    displaySqlResults(
                                            statement, rs, null, null, true);
                                } finally {
                                    assert statement != null;
                                    try {
                                        statement.close();
                                    } catch (SQLException nse) {
                                        // Purposefully doing nothing
                                    } finally {
                                        statement = null;
                                    }
                                }
                            }
                        }
                        continue;
                    case Token.MACRO_TYPE:
                        processMacro(token);
                        continue;
                    case Token.PL_TYPE:
                        // Storing prevToken as an attempted hack
                        prevToken = buffer;
                        setBuf(token);
                        historize();
                        processPL();
                        continue;
                    case Token.SPECIAL_TYPE:
                        // Storing prevToken as an attempted hack
                        prevToken = buffer;
                        setBuf(token);
                        historize();
                        processSpecial(null);
                        continue;
                    case Token.EDIT_TYPE:
                        // Scanner only returns EDIT_TYPEs in interactive mode
                        processBuffHist(token);
                        continue;
                    case Token.BUFFER_TYPE:
                        token.type = Token.SQL_TYPE;
                        if (setBuf(token))
                            stdprintln(
                                    SqltoolRB.input_movedtobuffer.getString());
                        continue;
                    case Token.SQL_TYPE:
                        if (token.val == null) token.val = "";
                        setBuf(token);
                        historize();
                        ResultSet rs = null;
                        Statement statement = processSQL();
                        if (statement != null) {
                            try {
                                rs = statement.getResultSet();
                                displaySqlResults(
                                        statement, rs, null, null, true);
                            } finally {
                                assert statement != null;
                                try {
                                    statement.close();
                                } catch (SQLException nse) {
                                    // Purposefully doing nothing
                                } finally {
                                    statement = null;
                                }
                            }
                        }
                        continue;
                    default:
                        assert false :
                            "Internal assertion failed. Unexpected token type: "
                            + token.getTypeString();
                }
            } catch (BadSpecial bs) {
                // BadSpecials ALWAYS have non-null getMessage().
                assert token != null;
                errprintln(SqltoolRB.errorat.getString(
                        inputStreamLabel,
                        Integer.toString(token.line),
                        token.reconstitute(),
                        bs.getMessage(), bs.getMessage()));
                Throwable cause = bs.getCause();
                if (cause != null)
                    errprintln(SqltoolRB.causereport.getString(cause));

                if (!continueOnError) throw new SqlToolError(bs);
            } catch (SQLException se) {
                //se.printStackTrace();
                assert token != null;
                errprintln("SQL " + SqltoolRB.errorat.getString(
                        inputStreamLabel, Integer.toString(token.line),
                        lastSqlStatement,
                        se.getMessage()));
                // It's possible that we could have
                // SQLException.getMessage() == null, but if so, I think
                // it reasonable to show "null".  That's a DB inadequacy.

                if (!continueOnError) throw se;
            } catch (BreakException be) {
                String msg = be.getMessage();

                if (recursed != null) {
                    rollbackUncoms = false;
                    // Recursion level will exit by rethrowing the BE.
                    // We set rollbackUncoms to false because only the
                    // top level should detect break errors and
                    // possibly roll back.
                } else if (msg == null || msg.equals("file")) {
                    break;
                } else {
                    errprintln(SqltoolRB.break_unsatisfied.getString(msg));
                }

                if (recursed  != null || !continueOnError) throw be;
            } catch (ContinueException ce) {
                String msg = ce.getMessage();

                if (recursed != null) {
                    rollbackUncoms = false;
                } else {
                    errprintln(SqltoolRB.continue_unsatisfied.getString(msg));
                }

                if (recursed != null || !continueOnError) throw ce;
            } catch (QuitNow qn) {
                throw qn;
            } catch (SqlToolError ste) {
                assert token != null;
                StringBuffer sb = new StringBuffer(SqltoolRB.errorat.getString(
                    /* WARNING:  I have removed an extra LS appended to
                     * non-null ste.getMessages() below because I believe that
                     * it is unnecessary (and causes inconsistent blank lines
                     * to be written).
                     * If I am wrong and this is needed for Scanner display or
                     * something, restore it.
                     */
                    (new String[] {
                        inputStreamLabel, Integer.toString(token.line),
                        ((token.val == null) ? "" : token.reconstitute()),
                        ((ste.getMessage() == null)
                                ? "" : ste.getMessage())
                     })
                ));
                Throwable cause = ste.getCause();
View Full Code Here


            // groups.  Unfortunately, there's no way to guarantee that :( .
        commandChar = ((hm.group(2) == null || hm.group(2).length() < 1)
                ? '\0' : hm.group(2).charAt(0));
        other = ((commandChar == '\0') ? null : hm.group(2).substring(1));
        if (other != null && other.trim().length() < 1) other = null;
        Token targetCommand = ((histNum == null)
                ? null : commandFromHistory(histNum.intValue()));
        // Every command below depends upon buffer content.

        switch (commandChar) {
            case '\0' // Special token set above.  Just history recall.
                setBuf(targetCommand);
                stdprintln(SqltoolRB.buffer_restored.getString(
                        buffer.reconstitute()));
                return;

            case ';' :
                if (other != null)
                    throw new BadSpecial(
                            SqltoolRB.special_extrachars.getString(";", other));

                if (targetCommand != null) setBuf(targetCommand);
                if (buffer == null) throw new BadSpecial(
                        SqltoolRB.nobuffer_yet.getString());
                stdprintln(SqltoolRB.buffer_executing.getString(
                        buffer.reconstitute()));
                preempt = true;
                return;

            case 'a' :
                if (targetCommand == null) targetCommand = buffer;
                if (targetCommand == null) throw new BadSpecial(
                        SqltoolRB.nobuffer_yet.getString());
                boolean doExec = false;

                if (other != null) {
                    if (other.trim().charAt(other.trim().length() - 1) == ';') {
                        other = other.substring(0, other.lastIndexOf(';'));
                        if (other.trim().length() < 1)
                            throw new BadSpecial(
                                    SqltoolRB.append_empty.getString());
                        doExec = true;
                    }
                }
                Token newToken = new Token(targetCommand.type,
                        targetCommand.val, targetCommand.line);
                if (other != null) newToken.val += other;
                setBuf(newToken);
                if (doExec) {
                    stdprintln(SqltoolRB.buffer_executing.getString(
                            buffer.reconstitute()));
                    preempt = true;
                    return;
                }

                if (interactive) scanner.setMagicPrefix(
                        newToken.reconstitute());

                switch (newToken.type) {
                    case Token.SQL_TYPE:
                        scanner.setRequestedState(SqlFileScanner.SQL);
                        break;
                    case Token.SPECIAL_TYPE:
                        scanner.setRequestedState(SqlFileScanner.SPECIAL);
                        break;
                    case Token.PL_TYPE:
                        scanner.setRequestedState(SqlFileScanner.PL);
                        break;
                    default:
                        assert false: "Internal assertion failed.  "
                            + "Appending to unexpected type: "
                            + newToken.getTypeString();
                }
                scanner.setCommandBuffer(newToken.val);

                return;

            case 'w' :
                if (targetCommand == null) targetCommand = buffer;
                if (targetCommand == null) throw new BadSpecial(
                        SqltoolRB.nobuffer_yet.getString());
                if (other == null)
                    throw new BadSpecial(SqltoolRB.destfile_demand.getString());
                String targetFile =
                        dereferenceAt(dereference(other.trim(), false));
                // Dereference and trim the target file name
                // This is the only case where we dereference a : command.

                PrintWriter pw = null;
                try {
                    pw = new PrintWriter(
                            new OutputStreamWriter(
                            new FileOutputStream(targetFile, true),
                            (shared.encoding == null)
                            ? DEFAULT_FILE_ENCODING : shared.encoding)
                            // Appendmode so can append to an SQL script.
                    );

                    pw.println(targetCommand.reconstitute(true));
                    pw.flush();
                } catch (Exception e) {
                    throw new BadSpecial(SqltoolRB.file_appendfail.getString(
                            targetFile), e);
                } finally {
                    if (pw != null) try {
                        pw.close();
                    } finally {
                        pw = null; // Encourage GC of buffers
                    }
                }

                return;

            case 's' :
                boolean modeExecute = false;
                boolean modeGlobal = false;
                if (targetCommand == null) targetCommand = buffer;
                if (targetCommand == null) throw new BadSpecial(
                        SqltoolRB.nobuffer_yet.getString());

                try {
                    if (other == null || other.length() < 3)
                        throw new BadSubst(
                                SqltoolRB.substitution_malformat.getString());
                    Matcher m = substitutionPattern.matcher(other);
                    if (!m.matches())
                        throw new BadSubst(
                                SqltoolRB.substitution_malformat.getString());

                    // Note that this pattern does not include the leading ':'.
                    assert m.groupCount() > 2 && m.groupCount() < 5 :
                        "Internal assertion failed.  "
                        + "Matched substitution pattern, but captured "
                        + m.groupCount() + " groups";
                    String optionGroup = (
                            (m.groupCount() > 3 && m.group(4) != null)
                            ? m.group(4) : null);

                    if (optionGroup != null) {
                        if (optionGroup.indexOf(';') > -1) {
                            modeExecute = true;
                            optionGroup = optionGroup.replaceFirst(";", "");
                        }
                        if (optionGroup.indexOf('g') > -1) {
                            modeGlobal = true;
                            optionGroup = optionGroup.replaceFirst("g", "");
                        }
                    }

                    Matcher bufferMatcher = Pattern.compile("(?s"
                            + ((optionGroup == null) ? "" : optionGroup)
                            + ')' + m.group(2)).matcher(targetCommand.val);
                    Token newBuffer = new Token(targetCommand.type,
                            (modeGlobal
                                ? bufferMatcher.replaceAll(m.group(3))
                                : bufferMatcher.replaceFirst(m.group(3))),
                                targetCommand.line);
                    if (newBuffer.val.equals(targetCommand.val)) {
View Full Code Here

                origVals[i] = shared.userVars.get(vars[i]);
            TokenList dupNesteds = token.nestedBlock.dup();
            if (dupNesteds.size() < 2)
                // TODO: Define message
                throw new BadSpecial("Empty forrows loop");
            Token queryToken = dupNesteds.remove(0);
            if (queryToken.type != Token.SQL_TYPE)
                // TODO: Define message
                throw new BadSpecial("*forrows command not followed "
                        + "immediately by an SQL statement");
            setBuf(queryToken);
            List<String[]> rowData = new ArrayList<String[]>();
            ResultSet rs = null;
            int colCount = 0;
            Statement statement = processSQL();
            if (statement == null)
                // TODO: Define message
                throw new BadSpecial("Failed to prepare SQL for loop");
            try {
                rs = statement.getResultSet();
                ResultSetMetaData rsmd = rs.getMetaData();
                colCount = rsmd.getColumnCount();
                if (vars != null && vars.length > colCount)
                    // TODO: Define message
                    throw new BadSpecial("*forrows command specifies "
                            + vars.length
                            + " variables, but query pulled only "
                            + colCount + " columns");
                if (colCount < 1) return;
                String[] rowCells;
                while (rs.next()) {
                    rowCells = new String[colCount];
                    rowData.add(rowCells);
                    for (int i = 1; i <= colCount; i++)
                        rowCells[i-1] = rs.getString(i);
                }
            } finally {
                try {
                    if (rs != null) rs.close();
                } catch (SQLException nse) {
                    // Purposefully doing nothing
                } finally {
                    rs = null;
                }
                try {
                    statement.close();
                } catch (SQLException nse) {
                    // Purposefully doing nothing
                } finally {
                    statement = null;
                }
            }
            lastSqlStatement = null;
            // Done with SQL

            if (rowData.size() > 0) {
                String firstVal = rowData.get(0)[0];
                String lastVal = rowData.get(rowData.size()-1)[colCount - 1];
                shared.userVars.put("?",
                        (lastVal == null) ? nullRepToken : lastVal);
                if (fetchingVar != null) {
                    if (firstVal == null)
                        shared.userVars.remove(fetchingVar);
                    else
                        shared.userVars.put(fetchingVar, firstVal);
                    updateUserSettings();
                    sqlExpandMode = null;
                    fetchingVar = null;
                }
            } else {
                shared.userVars.put("?", "");
            }
            StringBuilder rowBuilder = new StringBuilder();
            String rowVal;
            try {
                for (String[] cells : rowData) {
                    if (cells.length == 1) {
                        rowVal = (cells[0] == null) ? nullRepToken : cells[0];
                    } else {
                        rowBuilder.setLength(0);
                        for (String s : cells) {
                            if (rowBuilder.length() > 0)
                                rowBuilder.append(dsvColDelim);
                            rowBuilder.append((s == null) ? nullRepToken : s);
                        }
                        rowVal = rowBuilder.toString();
                    }
                    shared.userVars.put("*ROW", rowVal);

                    if (vars != null) for (int i = 0; i < vars.length; i++)
                        if (cells[i] == null)
                            shared.userVars.remove(vars[i]);
                        else
                            shared.userVars.put(vars[i], cells[i]);
                    updateUserSettings();

                    Recursion origRecursed = recursed;
                    recursed = Recursion.FORROWS;
                    try {
                        scanpass(dupNesteds.dup());
                    } catch (ContinueException ce) {
                        String ceMessage = ce.getMessage();

                        if (ceMessage != null
                                && !ceMessage.equals("forrows")) throw ce;
                    } finally {
                        recursed = origRecursed;
                    }
                }
            } catch (BreakException be) {
                String beMessage = be.getMessage();

                // Handle "forrows" and plain breaks (by doing nothing)
                if (beMessage != null && !beMessage.equals("forrows")) throw be;
            } catch (QuitNow qn) {
                throw qn;
            } catch (RuntimeException re) {
                throw re;  // Unrecoverable
            } catch (Exception e) {
                throw new BadSpecial(SqltoolRB.pl_block_fail.getString(), e);
            } finally {
                shared.userVars.remove("*ROW");
                if (origVals != null) for (int i = 1; i < origVals.length; i++)
                    if (origVals[i] == null)
                        shared.userVars.remove(vars[i]);
                    else
                        shared.userVars.put(vars[i], origVals[i]);
                updateUserSettings();
                sqlExpandMode = null;
            }
            return;
        }

        if (tokens[0].equals("foreach")) {
            Matcher foreachM = foreachPattern.matcher(
                    dereference(token.val, false));
            if (!foreachM.matches())
                throw new BadSpecial(
                        SqltoolRB.pl_malformat_specific.getString("foreach"));
            if (foreachM.groupCount() != 2)
            assert foreachM.groupCount() == 2:
                "Internal assertion failed.  "
                + "foreach pattern matched, but captured "
                + foreachM.groupCount() + " groups";

            String varName   = foreachM.group(1);
            if (varName.indexOf(':') > -1)
                throw new BadSpecial(SqltoolRB.plvar_nocolon.getString());
            if (!varPattern.matcher(varName).matches())
                errprintln(SqltoolRB.varname_warning.getString(varName));
            String[] values = foreachM.group(2).split("\\s+", -1);

            String origval = shared.userVars.get(varName);

            try {
                for (String val : values) {
                    // val may never be null
                    shared.userVars.put(varName, val);
                    updateUserSettings();

                    Recursion origRecursed = recursed;
                    recursed = Recursion.FOREACH;
                    try {
                        scanpass(token.nestedBlock.dup());
                    } catch (ContinueException ce) {
                        String ceMessage = ce.getMessage();

                        if (ceMessage != null
                                && !ceMessage.equals("foreach")) throw ce;
                    } finally {
                        recursed = origRecursed;
                    }
                }
            } catch (BreakException be) {
                String beMessage = be.getMessage();

                // Handle "foreach" and plain breaks (by doing nothing)
                if (beMessage != null && !beMessage.equals("foreach")) throw be;
            } catch (QuitNow qn) {
                throw qn;
            } catch (RuntimeException re) {
                throw re;  // Unrecoverable
            } catch (Exception e) {
                throw new BadSpecial(SqltoolRB.pl_block_fail.getString(), e);
            } finally {
                if (origval == null) {
                    shared.userVars.remove(varName);
                } else {
                    shared.userVars.put(varName, origval);
                }
                updateUserSettings();
                sqlExpandMode = null;
            }

            return;
        }

        if (tokens[0].equals("if") || tokens[0].equals("while")) {
            Matcher ifwhileM= ifwhilePattern.matcher(
                    dereference(token.val, false));
            if (!ifwhileM.matches())
                throw new BadSpecial(SqltoolRB.ifwhile_malformat.getString());
            assert ifwhileM.groupCount() == 1:
                "Internal assertion failed.  "
                + "if/while pattern matched, but captured "
                + ifwhileM.groupCount() + " groups";

            String[] values =
                    ifwhileM.group(1).replaceAll("!([a-zA-Z0-9*])", "! $1").
                        replaceAll("([a-zA-Z0-9*])!", "$1 !").split("\\s+", -1);

            if (tokens[0].equals("if")) {
                try {
                    // Provisionally 'else'.  Will be nulled if it is not:
                    Token elseToken = (token.nestedBlock.size() < 1)
                            ? null
                            : token.nestedBlock.get(
                                    token.nestedBlock.size() - 1);
                    if (elseToken != null && (elseToken.type != Token.PL_TYPE ||
                            !elseToken.val.equals("else"))) elseToken = null;
                    //if (elseToken != null)
                        //token.nestedBlock.remove(token.nestedBlock.size() - 1);
                    Token recurseToken = eval(values) ? token : elseToken;
                    if (recurseToken != null) {
                        Recursion origRecursed = recursed;
                        recursed = Recursion.IF;
                        try {
                            scanpass(recurseToken.nestedBlock.dup());
View Full Code Here

    synchronized protected void scanpass(TokenSource ts)
                                     throws SqlToolError, SQLException {
        boolean rollbackUncoms = true;
        String nestingCommand;
        Token token = null;

        if (shared.userVars.size() > 0) {
            plMode = true;
        }

        try {
            while (true) try {
                if (preempt) {
                    token = buffer;
                    preempt = false;
                } else {
                    token = ts.yylex();
                    logger.finest("SqlFile got new token:  " + token);
                }
                if (token == null) break;

                nestingCommand = nestingCommand(token);
                if (nestingCommand != null) {
                    if (token.nestedBlock == null) {
                        token.nestedBlock = seekTokenSource(nestingCommand);
                        /* This command (and the same recursive call inside
                         * of the seekTokenSource() method) ensure that all
                         * "blocks" are tokenized immediately as block
                         * commands are encountered, and the blocks are
                         * tokenized in their entirety all the way to the
                         * leaves.
                         */
                    }
                    processBlock(token);
                        /* processBlock recurses through scanpass(),
                         * which processes the nested commands which have
                         * (in all cases) already beeen tokenized.
                         */
                    continue;
                }

                switch (token.type) {
                    case Token.SYNTAX_ERR_TYPE:
                        throw new SqlToolError(SqltoolRB.input_malformat.getString());
                        // Will get here if Scanner can't match input to any
                        // known command type.
                        // An easy way to get here is to start a command with
                        // quotes.
                    case Token.UNTERM_TYPE:
                        throw new SqlToolError(
                                SqltoolRB.input_unterminated.getString(
                                token.val));
                    case Token.RAW_TYPE:
                    case Token.RAWEXEC_TYPE:
                        /*
                         * A real problem in this block is that the Scanner
                         * has already displayed the next prompt at this
                         * point.  We handle this specially within this
                         * block, but if we throw, the handler will not
                         * know that the prompt has to be re-displayed.
                         * I.e., KNOWN ISSUE:  For some errors caught during
                         * raw command execution, interactive users will not
                         * get a prompt to tell them to proceed.
                         */
                        if (token.val == null) token.val = "";
                        /*
                         * Don't have time know to figure out whether it would
                         * ever be useful to send just (non-zero) whitespace
                         * to the DB.  Prohibiting for now.
                         */
                        if (token.val.trim().length() < 1) {
                            throw new SqlToolError(
                                    SqltoolRB.raw_empty.getString());
                        }
                        int receivedType = token.type;
                        token.type = Token.SQL_TYPE;
                        if (setBuf(token) && receivedType == Token.RAW_TYPE
                                && interactive) {
                            stdprintln("");
                            stdprintln(SqltoolRB.raw_movedtobuffer.getString());
                            stdprint(primaryPrompt);
                            // All of these stdprint*'s are to work around a
                            // very complicated issue where the Scanner
                            // has already displayed the next prompt before
                            // we can display our status message.
                        }
                        if (receivedType == Token.RAWEXEC_TYPE) {
                            historize();
                            processSQL();
                        }
                        continue;
                    case Token.MACRO_TYPE:
                        processMacro(token);
                        continue;
                    case Token.PL_TYPE:
                        setBuf(token);
                        historize();
                        processPL(null);
                        continue;
                    case Token.SPECIAL_TYPE:
                        setBuf(token);
                        historize();
                        processSpecial(null);
                        continue;
                    case Token.EDIT_TYPE:
                        // Scanner only returns EDIT_TYPEs in interactive mode
                        processBuffHist(token);
                        continue;
                    case Token.BUFFER_TYPE:
                        token.type = Token.SQL_TYPE;
                        if (setBuf(token)) {
                            stdprintln(
                                    SqltoolRB.input_movedtobuffer.getString());
                        }
                        continue;
                    case Token.SQL_TYPE:
                        if (token.val == null) token.val = "";
                        setBuf(token);
                        historize();
                        processSQL();
                        continue;
                    default:
                        throw new RuntimeException(
                                "Internal assertion failed.  "
                                + "Unexpected token type: "
                                + token.getTypeString());
                }
            } catch (BadSpecial bs) {
                // BadSpecials ALWAYS have non-null getMessage().
                if (token == null) {
                    errprintln(SqltoolRB.errorat.getString(
                            inputStreamLabel, "?", "?", bs.getMessage()));
                } else {
                    errprintln(SqltoolRB.errorat.getString(
                            inputStreamLabel,
                            Integer.toString(token.line),
                            token.reconstitute(),
                            bs.getMessage(), bs.getMessage()));
                }
                Throwable cause = bs.getCause();
                if (cause != null) {
                    errprintln(SqltoolRB.causereport.getString(
                            cause.toString()));

                }

                if (!continueOnError) {
                    throw new SqlToolError(bs);
                }
            } catch (SQLException se) {
                //se.printStackTrace();
                errprintln("SQL " + SqltoolRB.errorat.getString(
                        inputStreamLabel,
                        ((token == null) ? "?"
                                         : Integer.toString(token.line)),
                        lastSqlStatement,
                        se.getMessage()));
                // It's possible that we could have
                // SQLException.getMessage() == null, but if so, I think
                // it reasonable to show "null".  That's a DB inadequacy.

                if (!continueOnError) {
                    throw se;
                }
            } catch (BreakException be) {
                String msg = be.getMessage();

                if (recursed) {
                    rollbackUncoms = false;
                    // Recursion level will exit by rethrowing the BE.
                    // We set rollbackUncoms to false because only the
                    // top level should detect break errors and
                    // possibly roll back.
                } else if (msg == null || msg.equals("file")) {
                    break;
                } else {
                    errprintln(SqltoolRB.break_unsatisfied.getString(msg));
                }

                if (recursed ||!continueOnError) {
                    throw be;
                }
            } catch (ContinueException ce) {
                String msg = ce.getMessage();

                if (recursed) {
                    rollbackUncoms = false;
                } else {
                    errprintln(SqltoolRB.continue_unsatisfied.getString(msg));
                }

                if (recursed ||!continueOnError) {
                    throw ce;
                }
            } catch (QuitNow qn) {
                throw qn;
            } catch (SqlToolError ste) {
                StringBuffer sb = new StringBuffer(SqltoolRB.errorat.getString(
                    /* WARNING:  I have removed an extra LS appended to
                     * non-null ste.getMessages() below because I believe that
                     * it is unnecessary (and causes inconsistent blank lines
                     * to be written).
                     * If I am wrong and this is needed for Scanner display or
                     * something, restore it.
                     */
                    ((token == null)
                            ? (new String[] {
                                inputStreamLabel, "?", "?",
                                ((ste.getMessage() == null)
                                        ? "" : ste.getMessage())
                              })
                            : (new String[] {
                                inputStreamLabel, Integer.toString(token.line),
                                ((token.val == null) ? "" : token.reconstitute()),
                                ((ste.getMessage() == null)
                                        ? "" : ste.getMessage())
                              }))
                ));
                Throwable cause = ste.getCause();
View Full Code Here

        }
        commandChar = ((hm.group(2) == null || hm.group(2).length() < 1)
                ? '\0' : hm.group(2).charAt(0));
        other = ((commandChar == '\0') ? null : hm.group(2).substring(1));
        if (other != null && other.length() < 1) other = null;
        Token targetCommand = ((histNum == null)
                ? null : commandFromHistory(histNum.intValue()));
        // Every command below depends upon buffer content.

        switch (commandChar) {
            case '\0' // Special token set above.  Just history recall.
                setBuf(targetCommand);
                stdprintln(SqltoolRB.buffer_restored.getString(
                        buffer.reconstitute()));
                return;

            case ';' :
                enforce1charBH(other, ';');

                if (targetCommand != null) setBuf(targetCommand);
                if (buffer == null) throw new BadSpecial(
                        SqltoolRB.nobuffer_yet.getString());
                stdprintln(SqltoolRB.buffer_executing.getString(
                        buffer.reconstitute()));
                preempt = true;
                return;

            case 'a' :
                if (targetCommand == null) targetCommand = buffer;
                if (targetCommand == null) throw new BadSpecial(
                        SqltoolRB.nobuffer_yet.getString());
                boolean doExec = false;

                if (other != null) {
                    if (other.trim().charAt(other.trim().length() - 1) == ';') {
                        other = other.substring(0, other.lastIndexOf(';'));
                        if (other.trim().length() < 1)
                            throw new BadSpecial(
                                    SqltoolRB.append_empty.getString());
                        doExec = true;
                    }
                }
                Token newToken = new Token(targetCommand.type,
                        targetCommand.val, targetCommand.line);
                if (other != null) newToken.val += other;
                setBuf(newToken);
                if (doExec) {
                    stdprintln(SqltoolRB.buffer_executing.getString(
                            buffer.reconstitute()));
                    preempt = true;
                    return;
                }

                if (interactive) scanner.setMagicPrefix(
                        newToken.reconstitute());

                switch (newToken.type) {
                    case Token.SQL_TYPE:
                        scanner.setRequestedState(SqlFileScanner.SQL);
                        break;
                    case Token.SPECIAL_TYPE:
                        scanner.setRequestedState(SqlFileScanner.SPECIAL);
                        break;
                    case Token.PL_TYPE:
                        scanner.setRequestedState(SqlFileScanner.PL);
                        break;
                    default:
                        throw new RuntimeException(
                            "Internal assertion failed.  "
                            + "Appending to unexpected type: "
                            + newToken.getTypeString());
                }
                scanner.setCommandBuffer(newToken.val);

                return;

            case 'w' :
                if (targetCommand == null) targetCommand = buffer;
                if (targetCommand == null) throw new BadSpecial(
                        SqltoolRB.nobuffer_yet.getString());
                if (other == null) {
                    throw new BadSpecial(SqltoolRB.destfile_demand.getString());
                }
                String targetFile =
                        dereferenceAt(dereference(other.trim(), false));
                // Dereference and trim the target file name
                // This is the only case where we dereference a : command.

                PrintWriter pw = null;
                try {
                    pw = new PrintWriter(
                            new OutputStreamWriter(
                            new FileOutputStream(targetFile, true),
                            (shared.encoding == null)
                            ? DEFAULT_FILE_ENCODING : shared.encoding)
                            // Appendmode so can append to an SQL script.
                    );

                    pw.println(targetCommand.reconstitute(true));
                    pw.flush();
                } catch (Exception e) {
                    throw new BadSpecial(SqltoolRB.file_appendfail.getString(
                            targetFile), e);
                } finally {
                    if (pw != null) {
                        try {
                            pw.close();
                        } finally {
                            pw = null; // Encourage GC of buffers
                        }
                    }
                }

                return;

            case 's' :
                boolean modeExecute = false;
                boolean modeGlobal = false;
                if (targetCommand == null) targetCommand = buffer;
                if (targetCommand == null) throw new BadSpecial(
                        SqltoolRB.nobuffer_yet.getString());

                try {
                    if (other == null || other.length() < 3) {
                        throw new BadSubst(
                                SqltoolRB.substitution_malformat.getString());
                    }
                    Matcher m = substitutionPattern.matcher(other);
                    if (!m.matches()) {
                        throw new BadSubst(
                                SqltoolRB.substitution_malformat.getString());
                    }

                    // Note that this pattern does not include the leading :.
                    if (m.groupCount() < 3 || m.groupCount() > 4) {
                        throw new RuntimeException(
                                "Internal assertion failed.  "
                                + "Matched substitution "
                                + "pattern, but captured "
                                + m.groupCount() + " groups");
                    }
                    String optionGroup = (
                            (m.groupCount() > 3 && m.group(4) != null)
                            ? (new String(m.group(4))) : null);

                    if (optionGroup != null) {
                        if (optionGroup.indexOf(';') > -1) {
                            modeExecute = true;
                            optionGroup = optionGroup.replaceFirst(";", "");
                        }
                        if (optionGroup.indexOf('g') > -1) {
                            modeGlobal = true;
                            optionGroup = optionGroup.replaceFirst("g", "");
                        }
                    }

                    Matcher bufferMatcher = Pattern.compile("(?s"
                            + ((optionGroup == null) ? "" : optionGroup)
                            + ')' + m.group(2)).matcher(targetCommand.val);
                    Token newBuffer = new Token(targetCommand.type,
                            (modeGlobal
                                ? bufferMatcher.replaceAll(m.group(3))
                                : bufferMatcher.replaceFirst(m.group(3))),
                                targetCommand.line);
                    if (newBuffer.val.equals(targetCommand.val)) {
View Full Code Here

            throw new BadSpecial(SqltoolRB.history_none.getString());
        }
        if (shared.psStd == null) return;
          // Input can be dual-purpose, i.e. the script can be intended for
          // both interactive and non-interactive usage.
        Token token;
        for (int i = 0; i < history.size(); i++) {
            token = history.get(i);
            shared.psStd.println("#" + (i + oldestHist) + " or "
                    + (i - history.size()) + ':');
            shared.psStd.println(token.reconstitute());
        }
        if (buffer != null) {
            shared.psStd.println(SqltoolRB.editbuffer_contents.getString(
                    buffer.reconstitute()));
        }
View Full Code Here

                throw new RuntimeException(
                        "Internal assertion failed.  "
                        + "Attempted to add command type "
                        + newBuffer.getTypeString() + " to buffer");
        }
        buffer = new Token(newBuffer.type, new String(newBuffer.val),
                newBuffer.line);
        // System.err.println("Buffer is now (" + buffer + ')');
        return true;
    }
View Full Code Here

     * a seekTokenSource exception to be handled at a level other than
     * the very top.
     */
    private TokenList seekTokenSource(String nestingCommand)
            throws BadSpecial, IOException {
        Token token;
        TokenList newTS = new TokenList();
        Pattern endPattern = Pattern.compile("end\\s+" + nestingCommand);
        String subNestingCommand;

        while ((token = scanner.yylex()) != null) {
View Full Code Here

     * Leading space should probably not be trimmed, but it is trimmed now
     * (by the Scanner).
     */
    private void processMacro(Token defToken) throws BadSpecial {
        Matcher matcher;
        Token macroToken;

        if (defToken.val.length() < 1) {
            throw new BadSpecial(SqltoolRB.macro_tip.getString());
        }
        switch (defToken.val.charAt(0)) {
            case '?':
                stdprintln(SqltoolRB.macro_help.getString());
                break;
            case '=':
                String defString = defToken.val;
                defString = defString.substring(1).trim();
                if (defString.length() < 1) {
                    for (Map.Entry<String, Token> entry
                            : shared.macros.entrySet()) {
                        stdprintln(entry.getKey() + " = "
                                + entry.getValue().reconstitute());
                    }
                    break;
                }

                int newType = -1;
                StringBuffer newVal = new StringBuffer();
                matcher = editMacroPattern.matcher(defString);
                if (matcher.matches()) {
                    if (buffer == null) {
                        stdprintln(nobufferYetString);
                        return;
                    }
                    newVal.append(buffer.val);
                    if (matcher.groupCount() > 1 && matcher.group(2) != null
                            && matcher.group(2).length() > 0)
                        newVal.append(matcher.group(2));
                    newType = buffer.type;
                } else {
                    matcher = spMacroPattern.matcher(defString);
                    if (matcher.matches()) {
                        newVal.append(matcher.group(3));
                        newType = (matcher.group(2).equals("*")
                                ?  Token.PL_TYPE : Token.SPECIAL_TYPE);
                    } else {
                        matcher = sqlMacroPattern.matcher(defString);
                        if (!matcher.matches())
                            throw new BadSpecial(
                                    SqltoolRB.macro_malformat.getString());
                        newVal.append(matcher.group(2));
                        newType = Token.SQL_TYPE;
                    }
                }
                if (newVal.length() < 1)
                    throw new BadSpecial(SqltoolRB.macrodef_empty.getString());
                if (newVal.charAt(newVal.length() - 1) == ';')
                    throw new BadSpecial(SqltoolRB.macrodef_semi.getString());
                shared.macros.put(matcher.group(1),
                        new Token(newType, newVal, defToken.line));
                break;
            default:
                matcher = useMacroPattern.matcher(defToken.val);
                if (!matcher.matches())
                    throw new BadSpecial(SqltoolRB.macro_malformat.getString());
View Full Code Here

TOP

Related Classes of org.hsqldb.cmdline.sqltool.Token

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.