Search in sources :

Example 1 with DbSchema

use of org.h2.bnf.context.DbSchema in project h2database by h2database.

the class DbContextRule method autoCompleteProcedure.

private void autoCompleteProcedure(Sentence sentence) {
    DbSchema schema = sentence.getLastMatchedSchema();
    if (schema == null) {
        schema = contents.getDefaultSchema();
    }
    String incompleteSentence = sentence.getQueryUpper();
    String incompleteFunctionName = incompleteSentence;
    if (incompleteSentence.contains("(")) {
        incompleteFunctionName = incompleteSentence.substring(0, incompleteSentence.indexOf('(')).trim();
    }
    // Common elements
    RuleElement openBracket = new RuleElement("(", "Function");
    RuleElement closeBracket = new RuleElement(")", "Function");
    RuleElement comma = new RuleElement(",", "Function");
    // Fetch all elements
    for (DbProcedure procedure : schema.getProcedures()) {
        final String procName = procedure.getName();
        if (procName.startsWith(incompleteFunctionName)) {
            // That's it, build a RuleList from this function
            RuleElement procedureElement = new RuleElement(procName, "Function");
            RuleList rl = new RuleList(procedureElement, openBracket, false);
            // Go further only if the user use open bracket
            if (incompleteSentence.contains("(")) {
                for (DbColumn parameter : procedure.getParameters()) {
                    if (parameter.getPosition() > 1) {
                        rl = new RuleList(rl, comma, false);
                    }
                    DbContextRule columnRule = new DbContextRule(contents, COLUMN);
                    String parameterType = parameter.getDataType();
                    // Remove precision
                    if (parameterType.contains("(")) {
                        parameterType = parameterType.substring(0, parameterType.indexOf('('));
                    }
                    columnRule.setColumnType(parameterType);
                    rl = new RuleList(rl, columnRule, false);
                }
                rl = new RuleList(rl, closeBracket, false);
            }
            rl.autoComplete(sentence);
        }
    }
}
Also used : RuleList(org.h2.bnf.RuleList) RuleElement(org.h2.bnf.RuleElement)

Example 2 with DbSchema

use of org.h2.bnf.context.DbSchema in project h2database by h2database.

the class WebApp method addTablesAndViews.

private int addTablesAndViews(DbSchema schema, boolean mainSchema, StringBuilder buff, int treeIndex) throws SQLException {
    if (schema == null) {
        return treeIndex;
    }
    Connection conn = session.getConnection();
    DatabaseMetaData meta = session.getMetaData();
    int level = mainSchema ? 0 : 1;
    boolean showColumns = mainSchema || !schema.isSystem;
    String indentation = ", " + level + ", " + (showColumns ? "1" : "2") + ", ";
    String indentNode = ", " + (level + 1) + ", 2, ";
    DbTableOrView[] tables = schema.getTables();
    if (tables == null) {
        return treeIndex;
    }
    boolean isOracle = schema.getContents().isOracle();
    boolean notManyTables = tables.length < SysProperties.CONSOLE_MAX_TABLES_LIST_INDEXES;
    for (DbTableOrView table : tables) {
        if (table.isView()) {
            continue;
        }
        int tableId = treeIndex;
        String tab = table.getQuotedName();
        if (!mainSchema) {
            tab = schema.quotedName + "." + tab;
        }
        tab = escapeIdentifier(tab);
        buff.append("setNode(").append(treeIndex).append(indentation).append(" 'table', '").append(PageParser.escapeJavaScript(table.getName())).append("', 'javascript:ins(\\'").append(tab).append("\\',true)');\n");
        treeIndex++;
        if (mainSchema || showColumns) {
            StringBuilder columnsBuffer = new StringBuilder();
            treeIndex = addColumns(mainSchema, table, buff, treeIndex, notManyTables, columnsBuffer);
            if (!isOracle && notManyTables) {
                treeIndex = addIndexes(mainSchema, meta, table.getName(), schema.name, buff, treeIndex);
            }
            buff.append("addTable('").append(PageParser.escapeJavaScript(table.getName())).append("', '").append(PageParser.escapeJavaScript(columnsBuffer.toString())).append("', ").append(tableId).append(");\n");
        }
    }
    tables = schema.getTables();
    for (DbTableOrView view : tables) {
        if (!view.isView()) {
            continue;
        }
        int tableId = treeIndex;
        String tab = view.getQuotedName();
        if (!mainSchema) {
            tab = view.getSchema().quotedName + "." + tab;
        }
        tab = escapeIdentifier(tab);
        buff.append("setNode(").append(treeIndex).append(indentation).append(" 'view', '").append(PageParser.escapeJavaScript(view.getName())).append("', 'javascript:ins(\\'").append(tab).append("\\',true)');\n");
        treeIndex++;
        if (mainSchema) {
            StringBuilder columnsBuffer = new StringBuilder();
            treeIndex = addColumns(mainSchema, view, buff, treeIndex, notManyTables, columnsBuffer);
            if (schema.getContents().isH2()) {
                try (PreparedStatement prep = conn.prepareStatement("SELECT * FROM " + "INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME=?")) {
                    prep.setString(1, view.getName());
                    ResultSet rs = prep.executeQuery();
                    if (rs.next()) {
                        String sql = rs.getString("SQL");
                        buff.append("setNode(").append(treeIndex).append(indentNode).append(" 'type', '").append(PageParser.escapeJavaScript(sql)).append("', null);\n");
                        treeIndex++;
                    }
                    rs.close();
                }
            }
            buff.append("addTable('").append(PageParser.escapeJavaScript(view.getName())).append("', '").append(PageParser.escapeJavaScript(columnsBuffer.toString())).append("', ").append(tableId).append(");\n");
        }
    }
    return treeIndex;
}
Also used : Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) SimpleResultSet(org.h2.tools.SimpleResultSet) DbTableOrView(org.h2.bnf.context.DbTableOrView) PreparedStatement(java.sql.PreparedStatement) DatabaseMetaData(java.sql.DatabaseMetaData)

Example 3 with DbSchema

use of org.h2.bnf.context.DbSchema in project h2database by h2database.

the class WebApp method tables.

private String tables() {
    DbContents contents = session.getContents();
    boolean isH2 = false;
    try {
        String url = (String) session.get("url");
        Connection conn = session.getConnection();
        contents.readContents(url, conn);
        session.loadBnf();
        isH2 = contents.isH2();
        StringBuilder buff = new StringBuilder().append("setNode(0, 0, 0, 'database', '").append(PageParser.escapeJavaScript(url)).append("', null);\n");
        int treeIndex = 1;
        DbSchema defaultSchema = contents.getDefaultSchema();
        treeIndex = addTablesAndViews(defaultSchema, true, buff, treeIndex);
        DbSchema[] schemas = contents.getSchemas();
        for (DbSchema schema : schemas) {
            if (schema == defaultSchema || schema == null) {
                continue;
            }
            buff.append("setNode(").append(treeIndex).append(", 0, 1, 'folder', '").append(PageParser.escapeJavaScript(schema.name)).append("', null);\n");
            treeIndex++;
            treeIndex = addTablesAndViews(schema, false, buff, treeIndex);
        }
        if (isH2) {
            try (Statement stat = conn.createStatement()) {
                ResultSet rs = stat.executeQuery("SELECT * FROM " + "INFORMATION_SCHEMA.SEQUENCES ORDER BY SEQUENCE_NAME");
                for (int i = 0; rs.next(); i++) {
                    if (i == 0) {
                        buff.append("setNode(").append(treeIndex).append(", 0, 1, 'sequences', '${text.tree.sequences}', null);\n");
                        treeIndex++;
                    }
                    String name = rs.getString("SEQUENCE_NAME");
                    String current = rs.getString("CURRENT_VALUE");
                    String increment = rs.getString("INCREMENT");
                    buff.append("setNode(").append(treeIndex).append(", 1, 1, 'sequence', '").append(PageParser.escapeJavaScript(name)).append("', null);\n");
                    treeIndex++;
                    buff.append("setNode(").append(treeIndex).append(", 2, 2, 'type', '${text.tree.current}: ").append(PageParser.escapeJavaScript(current)).append("', null);\n");
                    treeIndex++;
                    if (!"1".equals(increment)) {
                        buff.append("setNode(").append(treeIndex).append(", 2, 2, 'type', '${text.tree.increment}: ").append(PageParser.escapeJavaScript(increment)).append("', null);\n");
                        treeIndex++;
                    }
                }
                rs.close();
                rs = stat.executeQuery("SELECT * FROM " + "INFORMATION_SCHEMA.USERS ORDER BY NAME");
                for (int i = 0; rs.next(); i++) {
                    if (i == 0) {
                        buff.append("setNode(").append(treeIndex).append(", 0, 1, 'users', '${text.tree.users}', null);\n");
                        treeIndex++;
                    }
                    String name = rs.getString("NAME");
                    String admin = rs.getString("ADMIN");
                    buff.append("setNode(").append(treeIndex).append(", 1, 1, 'user', '").append(PageParser.escapeJavaScript(name)).append("', null);\n");
                    treeIndex++;
                    if (admin.equalsIgnoreCase("TRUE")) {
                        buff.append("setNode(").append(treeIndex).append(", 2, 2, 'type', '${text.tree.admin}', null);\n");
                        treeIndex++;
                    }
                }
                rs.close();
            }
        }
        DatabaseMetaData meta = session.getMetaData();
        String version = meta.getDatabaseProductName() + " " + meta.getDatabaseProductVersion();
        buff.append("setNode(").append(treeIndex).append(", 0, 0, 'info', '").append(PageParser.escapeJavaScript(version)).append("', null);\n").append("refreshQueryTables();");
        session.put("tree", buff.toString());
    } catch (Exception e) {
        session.put("tree", "");
        session.put("error", getStackTrace(0, e, isH2));
    }
    return "tables.jsp";
}
Also used : DbContents(org.h2.bnf.context.DbContents) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) DbSchema(org.h2.bnf.context.DbSchema) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) SimpleResultSet(org.h2.tools.SimpleResultSet) DatabaseMetaData(java.sql.DatabaseMetaData) DbException(org.h2.message.DbException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SQLException(java.sql.SQLException) JdbcSQLException(org.h2.jdbc.JdbcSQLException)

Example 4 with DbSchema

use of org.h2.bnf.context.DbSchema in project h2database by h2database.

the class TestBnf method testProcedures.

private void testProcedures(Connection conn, boolean isMySQLMode) throws Exception {
    // Register a procedure and check if it is present in DbContents
    conn.createStatement().execute("DROP ALIAS IF EXISTS CUSTOM_PRINT");
    conn.createStatement().execute("CREATE ALIAS CUSTOM_PRINT " + "AS $$ void print(String s) { System.out.println(s); } $$");
    conn.createStatement().execute("DROP TABLE IF EXISTS " + "TABLE_WITH_STRING_FIELD");
    conn.createStatement().execute("CREATE TABLE " + "TABLE_WITH_STRING_FIELD (STRING_FIELD VARCHAR(50), INT_FIELD integer)");
    DbContents dbContents = new DbContents();
    dbContents.readContents("jdbc:h2:test", conn);
    assertTrue(dbContents.isH2());
    assertFalse(dbContents.isDerby());
    assertFalse(dbContents.isFirebird());
    assertEquals(null, dbContents.quoteIdentifier(null));
    if (isMySQLMode) {
        assertTrue(dbContents.isH2ModeMySQL());
        assertEquals("TEST", dbContents.quoteIdentifier("TEST"));
        assertEquals("TEST", dbContents.quoteIdentifier("Test"));
        assertEquals("TEST", dbContents.quoteIdentifier("test"));
    } else {
        assertFalse(dbContents.isH2ModeMySQL());
        assertEquals("TEST", dbContents.quoteIdentifier("TEST"));
        assertEquals("\"Test\"", dbContents.quoteIdentifier("Test"));
        assertEquals("\"test\"", dbContents.quoteIdentifier("test"));
    }
    assertFalse(dbContents.isMSSQLServer());
    assertFalse(dbContents.isMySQL());
    assertFalse(dbContents.isOracle());
    assertFalse(dbContents.isPostgreSQL());
    assertFalse(dbContents.isSQLite());
    DbSchema defaultSchema = dbContents.getDefaultSchema();
    DbProcedure[] procedures = defaultSchema.getProcedures();
    Set<String> procedureName = new HashSet<>(procedures.length);
    for (DbProcedure procedure : procedures) {
        assertTrue(defaultSchema == procedure.getSchema());
        procedureName.add(procedure.getName());
    }
    if (isMySQLMode) {
        assertTrue(procedureName.contains("custom_print"));
    } else {
        assertTrue(procedureName.contains("CUSTOM_PRINT"));
    }
    if (isMySQLMode) {
        return;
    }
    // Test completion
    Bnf bnf = Bnf.getInstance(null);
    DbContextRule columnRule = new DbContextRule(dbContents, DbContextRule.COLUMN);
    bnf.updateTopic("column_name", columnRule);
    bnf.updateTopic("user_defined_function_name", new DbContextRule(dbContents, DbContextRule.PROCEDURE));
    bnf.linkStatements();
    // Test partial
    Map<String, String> tokens;
    tokens = bnf.getNextTokenList("SELECT CUSTOM_PR");
    assertTrue(tokens.values().contains("INT"));
    // Test identifiers are working
    tokens = bnf.getNextTokenList("create table \"test\" as s" + "el");
    assertTrue(tokens.values().contains("E" + "CT"));
    tokens = bnf.getNextTokenList("create table test as s" + "el");
    assertTrue(tokens.values().contains("E" + "CT"));
    // Test || with and without spaces
    tokens = bnf.getNextTokenList("select 1||f");
    assertFalse(tokens.values().contains("R" + "OM"));
    tokens = bnf.getNextTokenList("select 1 || f");
    assertFalse(tokens.values().contains("R" + "OM"));
    tokens = bnf.getNextTokenList("select 1 || 2 ");
    assertTrue(tokens.values().contains("FROM"));
    tokens = bnf.getNextTokenList("select 1||2");
    assertTrue(tokens.values().contains("FROM"));
    tokens = bnf.getNextTokenList("select 1 || 2");
    assertTrue(tokens.values().contains("FROM"));
    // Test keyword
    tokens = bnf.getNextTokenList("SELECT LE" + "AS");
    assertTrue(tokens.values().contains("T"));
    // Test parameters
    tokens = bnf.getNextTokenList("SELECT CUSTOM_PRINT(");
    assertTrue(tokens.values().contains("STRING_FIELD"));
    assertFalse(tokens.values().contains("INT_FIELD"));
    // Test parameters with spaces
    tokens = bnf.getNextTokenList("SELECT CUSTOM_PRINT ( ");
    assertTrue(tokens.values().contains("STRING_FIELD"));
    assertFalse(tokens.values().contains("INT_FIELD"));
    // Test parameters with close bracket
    tokens = bnf.getNextTokenList("SELECT CUSTOM_PRINT ( STRING_FIELD");
    assertTrue(tokens.values().contains(")"));
}
Also used : DbProcedure(org.h2.bnf.context.DbProcedure) DbContents(org.h2.bnf.context.DbContents) DbSchema(org.h2.bnf.context.DbSchema) Bnf(org.h2.bnf.Bnf) DbContextRule(org.h2.bnf.context.DbContextRule) HashSet(java.util.HashSet)

Aggregations

Connection (java.sql.Connection)2 DatabaseMetaData (java.sql.DatabaseMetaData)2 PreparedStatement (java.sql.PreparedStatement)2 ResultSet (java.sql.ResultSet)2 DbContents (org.h2.bnf.context.DbContents)2 DbSchema (org.h2.bnf.context.DbSchema)2 SimpleResultSet (org.h2.tools.SimpleResultSet)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 SQLException (java.sql.SQLException)1 Statement (java.sql.Statement)1 HashSet (java.util.HashSet)1 Bnf (org.h2.bnf.Bnf)1 RuleElement (org.h2.bnf.RuleElement)1 RuleList (org.h2.bnf.RuleList)1 DbContextRule (org.h2.bnf.context.DbContextRule)1 DbProcedure (org.h2.bnf.context.DbProcedure)1 DbTableOrView (org.h2.bnf.context.DbTableOrView)1 JdbcSQLException (org.h2.jdbc.JdbcSQLException)1 DbException (org.h2.message.DbException)1