Search in sources :

Example 6 with ScriptReader

use of org.h2.util.ScriptReader in project h2database by h2database.

the class WebApp method query.

private String query() {
    String sql = attributes.getProperty("sql").trim();
    try {
        ScriptReader r = new ScriptReader(new StringReader(sql));
        final ArrayList<String> list = New.arrayList();
        while (true) {
            String s = r.readStatement();
            if (s == null) {
                break;
            }
            list.add(s);
        }
        final Connection conn = session.getConnection();
        if (SysProperties.CONSOLE_STREAM && server.getAllowChunked()) {
            String page = new String(server.getFile("result.jsp"), StandardCharsets.UTF_8);
            int idx = page.indexOf("${result}");
            // the first element of the list is the header, the last the
            // footer
            list.add(0, page.substring(0, idx));
            list.add(page.substring(idx + "${result}".length()));
            session.put("chunks", new Iterator<String>() {

                private int i;

                @Override
                public boolean hasNext() {
                    return i < list.size();
                }

                @Override
                public String next() {
                    String s = list.get(i++);
                    if (i == 1 || i == list.size()) {
                        return s;
                    }
                    StringBuilder b = new StringBuilder();
                    query(conn, s, i - 1, list.size() - 2, b);
                    return b.toString();
                }

                @Override
                public void remove() {
                    throw new UnsupportedOperationException();
                }
            });
            return "result.jsp";
        }
        String result;
        StringBuilder buff = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            String s = list.get(i);
            query(conn, s, i, list.size(), buff);
        }
        result = buff.toString();
        session.put("result", result);
    } catch (Throwable e) {
        session.put("result", getStackTrace(0, e, session.getContents().isH2()));
    }
    return "result.jsp";
}
Also used : StringReader(java.io.StringReader) Connection(java.sql.Connection) ScriptReader(org.h2.util.ScriptReader)

Example 7 with ScriptReader

use of org.h2.util.ScriptReader in project h2database by h2database.

the class WebApp method autoCompleteList.

private String autoCompleteList() {
    String query = (String) attributes.get("query");
    boolean lowercase = false;
    if (query.trim().length() > 0 && Character.isLowerCase(query.trim().charAt(0))) {
        lowercase = true;
    }
    try {
        String sql = query;
        if (sql.endsWith(";")) {
            sql += " ";
        }
        ScriptReader reader = new ScriptReader(new StringReader(sql));
        reader.setSkipRemarks(true);
        String lastSql = "";
        while (true) {
            String n = reader.readStatement();
            if (n == null) {
                break;
            }
            lastSql = n;
        }
        String result = "";
        if (reader.isInsideRemark()) {
            if (reader.isBlockRemark()) {
                result = "1#(End Remark)# */\n" + result;
            } else {
                result = "1#(Newline)#\n" + result;
            }
        } else {
            sql = lastSql;
            while (sql.length() > 0 && sql.charAt(0) <= ' ') {
                sql = sql.substring(1);
            }
            if (sql.trim().length() > 0 && Character.isLowerCase(sql.trim().charAt(0))) {
                lowercase = true;
            }
            Bnf bnf = session.getBnf();
            if (bnf == null) {
                return "autoCompleteList.jsp";
            }
            HashMap<String, String> map = bnf.getNextTokenList(sql);
            String space = "";
            if (sql.length() > 0) {
                char last = sql.charAt(sql.length() - 1);
                if (!Character.isWhitespace(last) && (last != '.' && last >= ' ' && last != '\'' && last != '"')) {
                    space = " ";
                }
            }
            ArrayList<String> list = new ArrayList<>(map.size());
            for (Map.Entry<String, String> entry : map.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                String type = "" + key.charAt(0);
                if (Integer.parseInt(type) > 2) {
                    continue;
                }
                key = key.substring(2);
                if (Character.isLetter(key.charAt(0)) && lowercase) {
                    key = StringUtils.toLowerEnglish(key);
                    value = StringUtils.toLowerEnglish(value);
                }
                if (key.equals(value) && !".".equals(value)) {
                    value = space + value;
                }
                key = StringUtils.urlEncode(key);
                key = key.replace('+', ' ');
                value = StringUtils.urlEncode(value);
                value = value.replace('+', ' ');
                list.add(type + "#" + key + "#" + value);
            }
            Collections.sort(list);
            if (query.endsWith("\n") || query.trim().endsWith(";")) {
                list.add(0, "1#(Newline)#\n");
            }
            StatementBuilder buff = new StatementBuilder();
            for (String s : list) {
                buff.appendExceptFirst("|");
                buff.append(s);
            }
            result = buff.toString();
        }
        session.put("autoCompleteList", result);
    } catch (Throwable e) {
        server.traceError(e);
    }
    return "autoCompleteList.jsp";
}
Also used : ArrayList(java.util.ArrayList) StatementBuilder(org.h2.util.StatementBuilder) StringReader(java.io.StringReader) Bnf(org.h2.bnf.Bnf) Map(java.util.Map) HashMap(java.util.HashMap) ScriptReader(org.h2.util.ScriptReader)

Example 8 with ScriptReader

use of org.h2.util.ScriptReader in project h2database by h2database.

the class PgServerThread method process.

private void process() throws IOException {
    int x;
    if (initDone) {
        x = dataInRaw.read();
        if (x < 0) {
            stop = true;
            return;
        }
    } else {
        x = 0;
    }
    int len = dataInRaw.readInt();
    len -= 4;
    byte[] data = Utils.newBytes(len);
    dataInRaw.readFully(data, 0, len);
    dataIn = new DataInputStream(new ByteArrayInputStream(data, 0, len));
    switch(x) {
        case 0:
            server.trace("Init");
            int version = readInt();
            if (version == 80877102) {
                server.trace("CancelRequest");
                int pid = readInt();
                int key = readInt();
                PgServerThread c = server.getThread(pid);
                if (c != null && key == c.secret) {
                    c.cancelRequest();
                } else {
                    // According to the PostgreSQL documentation, when canceling
                    // a request, if an invalid secret is provided then no
                    // exception should be sent back to the client.
                    server.trace("Invalid CancelRequest: pid=" + pid + ", key=" + key);
                }
                close();
            } else if (version == 80877103) {
                server.trace("SSLRequest");
                out.write('N');
            } else {
                server.trace("StartupMessage");
                server.trace(" version " + version + " (" + (version >> 16) + "." + (version & 0xff) + ")");
                while (true) {
                    String param = readString();
                    if (param.length() == 0) {
                        break;
                    }
                    String value = readString();
                    if ("user".equals(param)) {
                        this.userName = value;
                    } else if ("database".equals(param)) {
                        this.databaseName = server.checkKeyAndGetDatabaseName(value);
                    } else if ("client_encoding".equals(param)) {
                        // UTF8
                        clientEncoding = value;
                    } else if ("DateStyle".equals(param)) {
                        if (value.indexOf(',') < 0) {
                            value += ", MDY";
                        }
                        dateStyle = value;
                    }
                    // extra_float_digits 2
                    // geqo on (Genetic Query Optimization)
                    server.trace(" param " + param + "=" + value);
                }
                sendAuthenticationCleartextPassword();
                initDone = true;
            }
            break;
        case 'p':
            {
                server.trace("PasswordMessage");
                String password = readString();
                try {
                    Properties info = new Properties();
                    info.put("MODE", "PostgreSQL");
                    info.put("USER", userName);
                    info.put("PASSWORD", password);
                    String url = "jdbc:h2:" + databaseName;
                    ConnectionInfo ci = new ConnectionInfo(url, info);
                    String baseDir = server.getBaseDir();
                    if (baseDir == null) {
                        baseDir = SysProperties.getBaseDir();
                    }
                    if (baseDir != null) {
                        ci.setBaseDir(baseDir);
                    }
                    if (server.getIfExists()) {
                        ci.setProperty("IFEXISTS", "TRUE");
                    }
                    conn = new JdbcConnection(ci, false);
                    // can not do this because when called inside
                    // DriverManager.getConnection, a deadlock occurs
                    // conn = DriverManager.getConnection(url, userName, password);
                    initDb();
                    sendAuthenticationOk();
                } catch (Exception e) {
                    e.printStackTrace();
                    stop = true;
                }
                break;
            }
        case 'P':
            {
                server.trace("Parse");
                Prepared p = new Prepared();
                p.name = readString();
                p.sql = getSQL(readString());
                int paramTypesCount = readShort();
                int[] paramTypes = null;
                if (paramTypesCount > 0) {
                    paramTypes = new int[paramTypesCount];
                    for (int i = 0; i < paramTypesCount; i++) {
                        paramTypes[i] = readInt();
                    }
                }
                try {
                    p.prep = (JdbcPreparedStatement) conn.prepareStatement(p.sql);
                    ParameterMetaData meta = p.prep.getParameterMetaData();
                    p.paramType = new int[meta.getParameterCount()];
                    for (int i = 0; i < p.paramType.length; i++) {
                        int type;
                        if (i < paramTypesCount && paramTypes[i] != 0) {
                            type = paramTypes[i];
                            server.checkType(type);
                        } else {
                            type = PgServer.convertType(meta.getParameterType(i + 1));
                        }
                        p.paramType[i] = type;
                    }
                    prepared.put(p.name, p);
                    sendParseComplete();
                } catch (Exception e) {
                    sendErrorResponse(e);
                }
                break;
            }
        case 'B':
            {
                server.trace("Bind");
                Portal portal = new Portal();
                portal.name = readString();
                String prepName = readString();
                Prepared prep = prepared.get(prepName);
                if (prep == null) {
                    sendErrorResponse("Prepared not found");
                    break;
                }
                portal.prep = prep;
                portals.put(portal.name, portal);
                int formatCodeCount = readShort();
                int[] formatCodes = new int[formatCodeCount];
                for (int i = 0; i < formatCodeCount; i++) {
                    formatCodes[i] = readShort();
                }
                int paramCount = readShort();
                try {
                    for (int i = 0; i < paramCount; i++) {
                        setParameter(prep.prep, prep.paramType[i], i, formatCodes);
                    }
                } catch (Exception e) {
                    sendErrorResponse(e);
                    break;
                }
                int resultCodeCount = readShort();
                portal.resultColumnFormat = new int[resultCodeCount];
                for (int i = 0; i < resultCodeCount; i++) {
                    portal.resultColumnFormat[i] = readShort();
                }
                sendBindComplete();
                break;
            }
        case 'C':
            {
                char type = (char) readByte();
                String name = readString();
                server.trace("Close");
                if (type == 'S') {
                    Prepared p = prepared.remove(name);
                    if (p != null) {
                        JdbcUtils.closeSilently(p.prep);
                    }
                } else if (type == 'P') {
                    portals.remove(name);
                } else {
                    server.trace("expected S or P, got " + type);
                    sendErrorResponse("expected S or P");
                    break;
                }
                sendCloseComplete();
                break;
            }
        case 'D':
            {
                char type = (char) readByte();
                String name = readString();
                server.trace("Describe");
                if (type == 'S') {
                    Prepared p = prepared.get(name);
                    if (p == null) {
                        sendErrorResponse("Prepared not found: " + name);
                    } else {
                        try {
                            sendParameterDescription(p.prep.getParameterMetaData(), p.paramType);
                            sendRowDescription(p.prep.getMetaData());
                        } catch (Exception e) {
                            sendErrorResponse(e);
                        }
                    }
                } else if (type == 'P') {
                    Portal p = portals.get(name);
                    if (p == null) {
                        sendErrorResponse("Portal not found: " + name);
                    } else {
                        PreparedStatement prep = p.prep.prep;
                        try {
                            ResultSetMetaData meta = prep.getMetaData();
                            sendRowDescription(meta);
                        } catch (Exception e) {
                            sendErrorResponse(e);
                        }
                    }
                } else {
                    server.trace("expected S or P, got " + type);
                    sendErrorResponse("expected S or P");
                }
                break;
            }
        case 'E':
            {
                String name = readString();
                server.trace("Execute");
                Portal p = portals.get(name);
                if (p == null) {
                    sendErrorResponse("Portal not found: " + name);
                    break;
                }
                int maxRows = readShort();
                Prepared prepared = p.prep;
                JdbcPreparedStatement prep = prepared.prep;
                server.trace(prepared.sql);
                try {
                    prep.setMaxRows(maxRows);
                    setActiveRequest(prep);
                    boolean result = prep.execute();
                    if (result) {
                        try {
                            ResultSet rs = prep.getResultSet();
                            // the meta-data is sent in the prior 'Describe'
                            while (rs.next()) {
                                sendDataRow(rs, p.resultColumnFormat);
                            }
                            sendCommandComplete(prep, 0);
                        } catch (Exception e) {
                            sendErrorResponse(e);
                        }
                    } else {
                        sendCommandComplete(prep, prep.getUpdateCount());
                    }
                } catch (Exception e) {
                    if (prep.isCancelled()) {
                        sendCancelQueryResponse();
                    } else {
                        sendErrorResponse(e);
                    }
                } finally {
                    setActiveRequest(null);
                }
                break;
            }
        case 'S':
            {
                server.trace("Sync");
                sendReadyForQuery();
                break;
            }
        case 'Q':
            {
                server.trace("Query");
                String query = readString();
                ScriptReader reader = new ScriptReader(new StringReader(query));
                while (true) {
                    JdbcStatement stat = null;
                    try {
                        String s = reader.readStatement();
                        if (s == null) {
                            break;
                        }
                        s = getSQL(s);
                        stat = (JdbcStatement) conn.createStatement();
                        setActiveRequest(stat);
                        boolean result = stat.execute(s);
                        if (result) {
                            ResultSet rs = stat.getResultSet();
                            ResultSetMetaData meta = rs.getMetaData();
                            try {
                                sendRowDescription(meta);
                                while (rs.next()) {
                                    sendDataRow(rs, null);
                                }
                                sendCommandComplete(stat, 0);
                            } catch (Exception e) {
                                sendErrorResponse(e);
                                break;
                            }
                        } else {
                            sendCommandComplete(stat, stat.getUpdateCount());
                        }
                    } catch (SQLException e) {
                        if (stat != null && stat.isCancelled()) {
                            sendCancelQueryResponse();
                        } else {
                            sendErrorResponse(e);
                        }
                        break;
                    } finally {
                        JdbcUtils.closeSilently(stat);
                        setActiveRequest(null);
                    }
                }
                sendReadyForQuery();
                break;
            }
        case 'X':
            {
                server.trace("Terminate");
                close();
                break;
            }
        default:
            server.trace("Unsupported: " + x + " (" + (char) x + ")");
            break;
    }
}
Also used : SQLException(java.sql.SQLException) JdbcConnection(org.h2.jdbc.JdbcConnection) PreparedStatement(java.sql.PreparedStatement) JdbcPreparedStatement(org.h2.jdbc.JdbcPreparedStatement) DataInputStream(java.io.DataInputStream) SysProperties(org.h2.engine.SysProperties) Properties(java.util.Properties) DbException(org.h2.message.DbException) SQLException(java.sql.SQLException) IOException(java.io.IOException) EOFException(java.io.EOFException) ResultSetMetaData(java.sql.ResultSetMetaData) JdbcStatement(org.h2.jdbc.JdbcStatement) ByteArrayInputStream(java.io.ByteArrayInputStream) ResultSet(java.sql.ResultSet) JdbcResultSet(org.h2.jdbc.JdbcResultSet) StringReader(java.io.StringReader) ConnectionInfo(org.h2.engine.ConnectionInfo) JdbcPreparedStatement(org.h2.jdbc.JdbcPreparedStatement) ParameterMetaData(java.sql.ParameterMetaData) ScriptReader(org.h2.util.ScriptReader)

Example 9 with ScriptReader

use of org.h2.util.ScriptReader in project h2database by h2database.

the class PgServerThread method installPgCatalog.

private static void installPgCatalog(Statement stat) throws SQLException {
    try (Reader r = new InputStreamReader(new ByteArrayInputStream(Utils.getResource("/org/h2/server/pg/pg_catalog.sql")))) {
        ScriptReader reader = new ScriptReader(r);
        while (true) {
            String sql = reader.readStatement();
            if (sql == null) {
                break;
            }
            stat.execute(sql);
        }
        reader.close();
    } catch (IOException e) {
        throw DbException.convertIOException(e, "Can not read pg_catalog resource");
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) ScriptReader(org.h2.util.ScriptReader) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) StringReader(java.io.StringReader) IOException(java.io.IOException) ScriptReader(org.h2.util.ScriptReader)

Example 10 with ScriptReader

use of org.h2.util.ScriptReader in project h2database by h2database.

the class RunScript method process.

private void process(Connection conn, boolean continueOnError, String path, Reader reader, Charset charset) throws SQLException, IOException {
    Statement stat = conn.createStatement();
    ScriptReader r = new ScriptReader(reader);
    while (true) {
        String sql = r.readStatement();
        if (sql == null) {
            break;
        }
        String trim = sql.trim();
        if (trim.length() == 0) {
            continue;
        }
        if (trim.startsWith("@") && StringUtils.toUpperEnglish(trim).startsWith("@INCLUDE")) {
            sql = trim;
            sql = sql.substring("@INCLUDE".length()).trim();
            if (!FileUtils.isAbsolute(sql)) {
                sql = path + SysProperties.FILE_SEPARATOR + sql;
            }
            process(conn, sql, continueOnError, charset);
        } else {
            try {
                if (showResults && !trim.startsWith("-->")) {
                    out.print(sql + ";");
                }
                if (showResults || checkResults) {
                    boolean query = stat.execute(sql);
                    if (query) {
                        ResultSet rs = stat.getResultSet();
                        int columns = rs.getMetaData().getColumnCount();
                        StringBuilder buff = new StringBuilder();
                        while (rs.next()) {
                            buff.append("\n-->");
                            for (int i = 0; i < columns; i++) {
                                String s = rs.getString(i + 1);
                                if (s != null) {
                                    s = StringUtils.replaceAll(s, "\r\n", "\n");
                                    s = StringUtils.replaceAll(s, "\n", "\n-->    ");
                                    s = StringUtils.replaceAll(s, "\r", "\r-->    ");
                                }
                                buff.append(' ').append(s);
                            }
                        }
                        buff.append("\n;");
                        String result = buff.toString();
                        if (showResults) {
                            out.print(result);
                        }
                        if (checkResults) {
                            String expected = r.readStatement() + ";";
                            expected = StringUtils.replaceAll(expected, "\r\n", "\n");
                            expected = StringUtils.replaceAll(expected, "\r", "\n");
                            if (!expected.equals(result)) {
                                expected = StringUtils.replaceAll(expected, " ", "+");
                                result = StringUtils.replaceAll(result, " ", "+");
                                throw new SQLException("Unexpected output for:\n" + sql.trim() + "\nGot:\n" + result + "\nExpected:\n" + expected);
                            }
                        }
                    }
                } else {
                    stat.execute(sql);
                }
            } catch (Exception e) {
                if (continueOnError) {
                    e.printStackTrace(out);
                } else {
                    throw DbException.toSQLException(e);
                }
            }
        }
    }
}
Also used : SQLException(java.sql.SQLException) Statement(java.sql.Statement) ResultSet(java.sql.ResultSet) ScriptReader(org.h2.util.ScriptReader) IOException(java.io.IOException) DbException(org.h2.message.DbException) SQLException(java.sql.SQLException)

Aggregations

ScriptReader (org.h2.util.ScriptReader)14 StringReader (java.io.StringReader)10 IOException (java.io.IOException)5 ResultSet (java.sql.ResultSet)5 ByteArrayInputStream (java.io.ByteArrayInputStream)3 InputStreamReader (java.io.InputStreamReader)3 SQLException (java.sql.SQLException)3 Statement (java.sql.Statement)3 Connection (java.sql.Connection)2 DbException (org.h2.message.DbException)2 BufferedReader (java.io.BufferedReader)1 DataInputStream (java.io.DataInputStream)1 EOFException (java.io.EOFException)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1 FileReader (java.io.FileReader)1 InputStream (java.io.InputStream)1 LineNumberReader (java.io.LineNumberReader)1 Reader (java.io.Reader)1