Search in sources :

Example 21 with Index

use of org.h2.index.Index in project h2database by h2database.

the class Parser method readParameter.

private Parameter readParameter() {
    // there must be no space between ? and the number
    boolean indexed = Character.isDigit(sqlCommandChars[parseIndex]);
    Parameter p;
    if (indexed) {
        readParameterIndex();
        if (indexedParameterList == null) {
            if (parameters == null) {
                // example check constraints)
                throw getSyntaxError();
            } else if (!parameters.isEmpty()) {
                throw DbException.get(ErrorCode.CANNOT_MIX_INDEXED_AND_UNINDEXED_PARAMS);
            }
            indexedParameterList = New.arrayList();
        }
        int index = currentValue.getInt() - 1;
        if (index < 0 || index >= Constants.MAX_PARAMETER_INDEX) {
            throw DbException.getInvalidValueException("parameter index", index + 1);
        }
        if (indexedParameterList.size() <= index) {
            indexedParameterList.ensureCapacity(index + 1);
            while (indexedParameterList.size() <= index) {
                indexedParameterList.add(null);
            }
        }
        p = indexedParameterList.get(index);
        if (p == null) {
            p = new Parameter(index);
            indexedParameterList.set(index, p);
        }
        read();
    } else {
        read();
        if (indexedParameterList != null) {
            throw DbException.get(ErrorCode.CANNOT_MIX_INDEXED_AND_UNINDEXED_PARAMS);
        }
        p = new Parameter(parameters.size());
    }
    parameters.add(p);
    return p;
}
Also used : Parameter(org.h2.expression.Parameter) ConditionInParameter(org.h2.expression.ConditionInParameter) AlterTableRenameConstraint(org.h2.command.ddl.AlterTableRenameConstraint) AlterTableAddConstraint(org.h2.command.ddl.AlterTableAddConstraint) AlterTableDropConstraint(org.h2.command.ddl.AlterTableDropConstraint)

Example 22 with Index

use of org.h2.index.Index in project h2database by h2database.

the class Parser method parseAlterTableAddConstraintIf.

private DefineCommand parseAlterTableAddConstraintIf(String tableName, Schema schema, boolean ifTableExists) {
    String constraintName = null, comment = null;
    boolean ifNotExists = false;
    boolean allowIndexDefinition = database.getMode().indexDefinitionInCreateTable;
    boolean allowAffinityKey = database.getMode().allowAffinityKey;
    if (readIf("CONSTRAINT")) {
        ifNotExists = readIfNotExists();
        constraintName = readIdentifierWithSchema(schema.getName());
        checkSchema(schema);
        comment = readCommentIf();
        allowIndexDefinition = true;
    }
    if (readIf("PRIMARY")) {
        read("KEY");
        AlterTableAddConstraint command = new AlterTableAddConstraint(session, schema, ifNotExists);
        command.setType(CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_PRIMARY_KEY);
        command.setComment(comment);
        command.setConstraintName(constraintName);
        command.setTableName(tableName);
        command.setIfTableExists(ifTableExists);
        if (readIf("HASH")) {
            command.setPrimaryKeyHash(true);
        }
        read("(");
        command.setIndexColumns(parseIndexColumnList());
        if (readIf("INDEX")) {
            String indexName = readIdentifierWithSchema();
            command.setIndex(getSchema().findIndex(session, indexName));
        }
        return command;
    } else if (allowIndexDefinition && (isToken("INDEX") || isToken("KEY"))) {
        // MySQL
        // need to read ahead, as it could be a column name
        int start = lastParseIndex;
        read();
        if (DataType.getTypeByName(currentToken, database.getMode()) != null) {
            // known data type
            parseIndex = start;
            read();
            return null;
        }
        CreateIndex command = new CreateIndex(session, schema);
        command.setComment(comment);
        command.setTableName(tableName);
        command.setIfTableExists(ifTableExists);
        if (!readIf("(")) {
            command.setIndexName(readUniqueIdentifier());
            read("(");
        }
        command.setIndexColumns(parseIndexColumnList());
        // MySQL compatibility
        if (readIf("USING")) {
            read("BTREE");
        }
        return command;
    } else if (allowAffinityKey && readIfAffinity()) {
        read("KEY");
        read("(");
        CreateIndex command = createAffinityIndex(schema, tableName, parseIndexColumnList());
        command.setIfTableExists(ifTableExists);
        return command;
    }
    AlterTableAddConstraint command;
    if (readIf("CHECK")) {
        command = new AlterTableAddConstraint(session, schema, ifNotExists);
        command.setType(CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_CHECK);
        command.setCheckExpression(readExpression());
    } else if (readIf("UNIQUE")) {
        readIf("KEY");
        readIf("INDEX");
        command = new AlterTableAddConstraint(session, schema, ifNotExists);
        command.setType(CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_UNIQUE);
        if (!readIf("(")) {
            constraintName = readUniqueIdentifier();
            read("(");
        }
        command.setIndexColumns(parseIndexColumnList());
        if (readIf("INDEX")) {
            String indexName = readIdentifierWithSchema();
            command.setIndex(getSchema().findIndex(session, indexName));
        }
        // MySQL compatibility
        if (readIf("USING")) {
            read("BTREE");
        }
    } else if (readIf("FOREIGN")) {
        command = new AlterTableAddConstraint(session, schema, ifNotExists);
        command.setType(CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_REFERENTIAL);
        read("KEY");
        read("(");
        command.setIndexColumns(parseIndexColumnList());
        if (readIf("INDEX")) {
            String indexName = readIdentifierWithSchema();
            command.setIndex(schema.findIndex(session, indexName));
        }
        read("REFERENCES");
        parseReferences(command, schema, tableName);
    } else {
        if (constraintName != null) {
            throw getSyntaxError();
        }
        return null;
    }
    if (readIf("NOCHECK")) {
        command.setCheckExisting(false);
    } else {
        readIf("CHECK");
        command.setCheckExisting(true);
    }
    command.setTableName(tableName);
    command.setIfTableExists(ifTableExists);
    command.setConstraintName(constraintName);
    command.setComment(comment);
    return command;
}
Also used : AlterTableAddConstraint(org.h2.command.ddl.AlterTableAddConstraint) CreateIndex(org.h2.command.ddl.CreateIndex) ValueString(org.h2.value.ValueString)

Example 23 with Index

use of org.h2.index.Index in project h2database by h2database.

the class Analyze method analyzeTable.

/**
 * Analyze this table.
 *
 * @param session the session
 * @param table the table
 * @param sample the number of sample rows
 * @param manual whether the command was called by the user
 */
public static void analyzeTable(Session session, Table table, int sample, boolean manual) {
    if (table.getTableType() != TableType.TABLE || table.isHidden() || session == null) {
        return;
    }
    if (!manual) {
        if (session.getDatabase().isSysTableLocked()) {
            return;
        }
        if (table.hasSelectTrigger()) {
            return;
        }
    }
    if (table.isTemporary() && !table.isGlobalTemporary() && session.findLocalTempTable(table.getName()) == null) {
        return;
    }
    if (table.isLockedExclusively() && !table.isLockedExclusivelyBy(session)) {
        return;
    }
    if (!session.getUser().hasRight(table, Right.SELECT)) {
        return;
    }
    if (session.getCancel() != 0) {
        // if the connection is closed and there is something to undo
        return;
    }
    Column[] columns = table.getColumns();
    if (columns.length == 0) {
        return;
    }
    Database db = session.getDatabase();
    StatementBuilder buff = new StatementBuilder("SELECT ");
    for (Column col : columns) {
        buff.appendExceptFirst(", ");
        int type = col.getType();
        if (type == Value.BLOB || type == Value.CLOB) {
            // can not index LOB columns, so calculating
            // the selectivity is not required
            buff.append("MAX(NULL)");
        } else {
            buff.append("SELECTIVITY(").append(col.getSQL()).append(')');
        }
    }
    buff.append(" FROM ").append(table.getSQL());
    if (sample > 0) {
        buff.append(" LIMIT ? SAMPLE_SIZE ? ");
    }
    String sql = buff.toString();
    Prepared command = session.prepare(sql);
    if (sample > 0) {
        ArrayList<Parameter> params = command.getParameters();
        params.get(0).setValue(ValueInt.get(1));
        params.get(1).setValue(ValueInt.get(sample));
    }
    ResultInterface result = command.query(0);
    result.next();
    for (int j = 0; j < columns.length; j++) {
        Value v = result.currentRow()[j];
        if (v != ValueNull.INSTANCE) {
            int selectivity = v.getInt();
            columns[j].setSelectivity(selectivity);
        }
    }
    db.updateMeta(session, table);
}
Also used : ResultInterface(org.h2.result.ResultInterface) Column(org.h2.table.Column) StatementBuilder(org.h2.util.StatementBuilder) Database(org.h2.engine.Database) Prepared(org.h2.command.Prepared) Value(org.h2.value.Value) Parameter(org.h2.expression.Parameter)

Example 24 with Index

use of org.h2.index.Index in project h2database by h2database.

the class Bnf method parse.

private void parse(Reader reader) throws SQLException, IOException {
    Rule functions = null;
    statements = New.arrayList();
    Csv csv = new Csv();
    csv.setLineCommentCharacter('#');
    ResultSet rs = csv.read(reader, null);
    while (rs.next()) {
        String section = rs.getString("SECTION").trim();
        if (section.startsWith("System")) {
            continue;
        }
        String topic = rs.getString("TOPIC");
        syntax = rs.getString("SYNTAX").trim();
        currentTopic = section;
        tokens = tokenize();
        index = 0;
        Rule rule = parseRule();
        if (section.startsWith("Command")) {
            rule = new RuleList(rule, new RuleElement(";\n\n", currentTopic), false);
        }
        RuleHead head = addRule(topic, section, rule);
        if (section.startsWith("Function")) {
            if (functions == null) {
                functions = rule;
            } else {
                functions = new RuleList(rule, functions, true);
            }
        } else if (section.startsWith("Commands")) {
            statements.add(head);
        }
    }
    addRule("@func@", "Function", functions);
    addFixedRule("@ymd@", RuleFixed.YMD);
    addFixedRule("@hms@", RuleFixed.HMS);
    addFixedRule("@nanos@", RuleFixed.NANOS);
    addFixedRule("anything_except_single_quote", RuleFixed.ANY_EXCEPT_SINGLE_QUOTE);
    addFixedRule("anything_except_double_quote", RuleFixed.ANY_EXCEPT_DOUBLE_QUOTE);
    addFixedRule("anything_until_end_of_line", RuleFixed.ANY_UNTIL_EOL);
    addFixedRule("anything_until_end_comment", RuleFixed.ANY_UNTIL_END);
    addFixedRule("anything_except_two_dollar_signs", RuleFixed.ANY_EXCEPT_2_DOLLAR);
    addFixedRule("anything", RuleFixed.ANY_WORD);
    addFixedRule("@hex_start@", RuleFixed.HEX_START);
    addFixedRule("@concat@", RuleFixed.CONCAT);
    addFixedRule("@az_@", RuleFixed.AZ_UNDERSCORE);
    addFixedRule("@af@", RuleFixed.AF);
    addFixedRule("@digit@", RuleFixed.DIGIT);
    addFixedRule("@open_bracket@", RuleFixed.OPEN_BRACKET);
    addFixedRule("@close_bracket@", RuleFixed.CLOSE_BRACKET);
}
Also used : Csv(org.h2.tools.Csv) ResultSet(java.sql.ResultSet) DbContextRule(org.h2.bnf.context.DbContextRule)

Example 25 with Index

use of org.h2.index.Index in project h2database by h2database.

the class Bnf method visit.

/**
 * Parse the syntax and let the rule call the visitor.
 *
 * @param visitor the visitor
 * @param s the syntax to parse
 */
public void visit(BnfVisitor visitor, String s) {
    this.syntax = s;
    tokens = tokenize();
    index = 0;
    Rule rule = parseRule();
    rule.setLinks(ruleMap);
    rule.accept(visitor);
}
Also used : DbContextRule(org.h2.bnf.context.DbContextRule)

Aggregations

ResultSet (java.sql.ResultSet)77 Index (org.h2.index.Index)75 Statement (java.sql.Statement)64 SimpleResultSet (org.h2.tools.SimpleResultSet)61 SQLException (java.sql.SQLException)60 Value (org.h2.value.Value)58 DbException (org.h2.message.DbException)57 Connection (java.sql.Connection)56 PreparedStatement (java.sql.PreparedStatement)56 Column (org.h2.table.Column)53 IndexColumn (org.h2.table.IndexColumn)45 ArrayList (java.util.ArrayList)31 ValueString (org.h2.value.ValueString)29 Constraint (org.h2.constraint.Constraint)25 Row (org.h2.result.Row)22 MultiVersionIndex (org.h2.index.MultiVersionIndex)19 JdbcConnection (org.h2.jdbc.JdbcConnection)19 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)18 Table (org.h2.table.Table)18 HashSet (java.util.HashSet)17