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;
        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 = 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

        if (history.size() < 1)
            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

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

     *
     * @param nestingCommand Set to null to read scanner until EOF.
     */
    private TokenList seekTokenSource(String nestingCommand)
            throws BadSpecial, IOException, SqlToolError {
        Token token;
        TokenList newTS = new TokenList();
        Pattern endPattern = null;
        Pattern elsePattern = null;
        if (nestingCommand != null)
            if (nestingCommand.equals("if")) {
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());
        int newType = -1;
        StringBuffer newVal = new StringBuffer();
        switch (defToken.val.charAt(0)) {
            case '?':
                stdprintln(SqltoolRB.macro_help.getString());
                break;
            case ':':
                matcher = editMacroPattern.matcher(defToken.val);
                if (!matcher.matches())
                    throw new BadSpecial(SqltoolRB.macro_malformat.getString());
                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;
                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(buffer.type, newVal, defToken.line));
                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;
                }

                matcher = legacyEditMacroPattern.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 = useFnPattern.matcher(defToken.val);
                if (matcher.matches()) {
                    macroToken = shared.macros.get(matcher.group(1) + ')');
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.