Search in sources :

Example 31 with In

use of org.h2.dev.util.BinaryArithmeticStream.In in project h2database by h2database.

the class Parser method parseColumnForTable.

private Column parseColumnForTable(String columnName, boolean defaultNullable) {
    Column column;
    boolean isIdentity = readIf("IDENTITY");
    if (isIdentity || readIf("BIGSERIAL")) {
        // Check if any of them are disallowed in the current Mode
        if (isIdentity && database.getMode().disallowedTypes.contains("IDENTITY")) {
            throw DbException.get(ErrorCode.UNKNOWN_DATA_TYPE_1, currentToken);
        }
        column = new Column(columnName, Value.LONG);
        column.setOriginalSQL("IDENTITY");
        parseAutoIncrement(column);
        // PostgreSQL compatibility
        if (!database.getMode().serialColumnIsNotPK) {
            column.setPrimaryKey(true);
        }
    } else if (readIf("SERIAL")) {
        column = new Column(columnName, Value.INT);
        column.setOriginalSQL("SERIAL");
        parseAutoIncrement(column);
        // PostgreSQL compatibility
        if (!database.getMode().serialColumnIsNotPK) {
            column.setPrimaryKey(true);
        }
    } else {
        column = parseColumnWithType(columnName);
    }
    if (readIf("INVISIBLE")) {
        column.setVisible(false);
    } else if (readIf("VISIBLE")) {
        column.setVisible(true);
    }
    NullConstraintType nullConstraint = parseNotNullConstraint();
    switch(nullConstraint) {
        case NULL_IS_ALLOWED:
            column.setNullable(true);
            break;
        case NULL_IS_NOT_ALLOWED:
            column.setNullable(false);
            break;
        case NO_NULL_CONSTRAINT_FOUND:
            // domains may be defined as not nullable
            column.setNullable(defaultNullable & column.isNullable());
            break;
        default:
            throw DbException.get(ErrorCode.UNKNOWN_MODE_1, "Internal Error - unhandled case: " + nullConstraint.name());
    }
    if (readIf("AS")) {
        if (isIdentity) {
            getSyntaxError();
        }
        Expression expr = readExpression();
        column.setComputedExpression(expr);
    } else if (readIf("DEFAULT")) {
        Expression defaultExpression = readExpression();
        column.setDefaultExpression(session, defaultExpression);
    } else if (readIf("GENERATED")) {
        if (!readIf("ALWAYS")) {
            read("BY");
            read("DEFAULT");
        }
        read("AS");
        read("IDENTITY");
        long start = 1, increment = 1;
        if (readIf("(")) {
            read("START");
            readIf("WITH");
            start = readLong();
            readIf(",");
            if (readIf("INCREMENT")) {
                readIf("BY");
                increment = readLong();
            }
            read(")");
        }
        column.setPrimaryKey(true);
        column.setAutoIncrement(true, start, increment);
    }
    if (readIf("ON")) {
        read("UPDATE");
        Expression onUpdateExpression = readExpression();
        column.setOnUpdateExpression(session, onUpdateExpression);
    }
    if (NullConstraintType.NULL_IS_NOT_ALLOWED == parseNotNullConstraint()) {
        column.setNullable(false);
    }
    if (readIf("AUTO_INCREMENT") || readIf("BIGSERIAL") || readIf("SERIAL")) {
        parseAutoIncrement(column);
        parseNotNullConstraint();
    } else if (readIf("IDENTITY")) {
        parseAutoIncrement(column);
        column.setPrimaryKey(true);
        parseNotNullConstraint();
    }
    if (readIf("NULL_TO_DEFAULT")) {
        column.setConvertNullToDefault(true);
    }
    if (readIf("SEQUENCE")) {
        Sequence sequence = readSequence();
        column.setSequence(sequence);
    }
    if (readIf("SELECTIVITY")) {
        int value = readPositiveInt();
        column.setSelectivity(value);
    }
    String comment = readCommentIf();
    if (comment != null) {
        column.setComment(comment);
    }
    return column;
}
Also used : AlterTableRenameColumn(org.h2.command.ddl.AlterTableRenameColumn) AlterTableAlterColumn(org.h2.command.ddl.AlterTableAlterColumn) Column(org.h2.table.Column) ExpressionColumn(org.h2.expression.ExpressionColumn) IndexColumn(org.h2.table.IndexColumn) Expression(org.h2.expression.Expression) ValueExpression(org.h2.expression.ValueExpression) DropSequence(org.h2.command.ddl.DropSequence) CreateSequence(org.h2.command.ddl.CreateSequence) Sequence(org.h2.schema.Sequence) AlterSequence(org.h2.command.dml.AlterSequence) ValueString(org.h2.value.ValueString) AlterTableRenameConstraint(org.h2.command.ddl.AlterTableRenameConstraint) AlterTableAddConstraint(org.h2.command.ddl.AlterTableAddConstraint) AlterTableDropConstraint(org.h2.command.ddl.AlterTableDropConstraint)

Example 32 with In

use of org.h2.dev.util.BinaryArithmeticStream.In in project h2database by h2database.

the class Parser method parseCreateTable.

private CreateTable parseCreateTable(boolean temp, boolean globalTemp, boolean persistIndexes) {
    boolean ifNotExists = readIfNotExists();
    String tableName = readIdentifierWithSchema();
    if (temp && globalTemp && equalsToken("SESSION", schemaName)) {
        // support weird syntax: declare global temporary table session.xy
        // (...) not logged
        schemaName = session.getCurrentSchemaName();
        globalTemp = false;
    }
    Schema schema = getSchema();
    CreateTable command = new CreateTable(session, schema);
    command.setPersistIndexes(persistIndexes);
    command.setTemporary(temp);
    command.setGlobalTemporary(globalTemp);
    command.setIfNotExists(ifNotExists);
    command.setTableName(tableName);
    command.setComment(readCommentIf());
    if (readIf("(")) {
        if (!readIf(")")) {
            do {
                parseTableColumnDefinition(command, schema, tableName);
            } while (readIfMore(false));
        }
    }
    // Allows "COMMENT='comment'" in DDL statements (MySQL syntax)
    if (readIf("COMMENT")) {
        if (readIf("=")) {
            // read the complete string comment, but nothing with it for now
            readString();
        }
    }
    if (readIf("ENGINE")) {
        if (readIf("=")) {
            // map MySQL engine types onto H2 behavior
            String tableEngine = readUniqueIdentifier();
            if ("InnoDb".equalsIgnoreCase(tableEngine)) {
            // ok
            } else if (!"MyISAM".equalsIgnoreCase(tableEngine)) {
                throw DbException.getUnsupportedException(tableEngine);
            }
        } else {
            command.setTableEngine(readUniqueIdentifier());
        }
    }
    if (readIf("WITH")) {
        command.setTableEngineParams(readTableEngineParams());
    }
    // MySQL compatibility
    if (readIf("AUTO_INCREMENT")) {
        read("=");
        if (currentTokenType != VALUE || currentValue.getType() != Value.INT) {
            throw DbException.getSyntaxError(sqlCommand, parseIndex, "integer");
        }
        read();
    }
    readIf("DEFAULT");
    if (readIf("CHARSET")) {
        read("=");
        if (!readIf("UTF8")) {
            read("UTF8MB4");
        }
    }
    if (temp) {
        if (readIf("ON")) {
            read("COMMIT");
            if (readIf("DROP")) {
                command.setOnCommitDrop();
            } else if (readIf("DELETE")) {
                read("ROWS");
                command.setOnCommitTruncate();
            }
        } else if (readIf("NOT")) {
            if (readIf("PERSISTENT")) {
                command.setPersistData(false);
            } else {
                read("LOGGED");
            }
        }
        if (readIf("TRANSACTIONAL")) {
            command.setTransactional(true);
        }
    } else if (!persistIndexes && readIf("NOT")) {
        read("PERSISTENT");
        command.setPersistData(false);
    }
    if (readIf("HIDDEN")) {
        command.setHidden(true);
    }
    if (readIf("AS")) {
        if (readIf("SORTED")) {
            command.setSortedInsertMode(true);
        }
        command.setQuery(parseSelect());
    }
    // for MySQL compatibility
    if (readIf("ROW_FORMAT")) {
        if (readIf("=")) {
            readColumnIdentifier();
        }
    }
    return command;
}
Also used : DropSchema(org.h2.command.ddl.DropSchema) CreateSchema(org.h2.command.ddl.CreateSchema) Schema(org.h2.schema.Schema) CreateTable(org.h2.command.ddl.CreateTable) ValueString(org.h2.value.ValueString)

Example 33 with In

use of org.h2.dev.util.BinaryArithmeticStream.In in project h2database by h2database.

the class Parser method parseSingleCommonTableExpression.

private TableView parseSingleCommonTableExpression(boolean isPersistent) {
    String cteViewName = readIdentifierWithSchema();
    Schema schema = getSchema();
    Table recursiveTable = null;
    ArrayList<Column> columns = New.arrayList();
    String[] cols = null;
    // query, if not supplied by user
    if (readIf("(")) {
        cols = parseColumnList();
        for (String c : cols) {
            // we don't really know the type of the column, so STRING will
            // have to do, UNKNOWN does not work here
            columns.add(new Column(c, Value.STRING));
        }
    }
    Table oldViewFound = null;
    if (isPersistent) {
        oldViewFound = getSchema().findTableOrView(session, cteViewName);
    } else {
        oldViewFound = session.findLocalTempTable(cteViewName);
    }
    // this persistent check conflicts with check 10 lines down
    if (oldViewFound != null) {
        if (!(oldViewFound instanceof TableView)) {
            throw DbException.get(ErrorCode.TABLE_OR_VIEW_ALREADY_EXISTS_1, cteViewName);
        }
        TableView tv = (TableView) oldViewFound;
        if (!tv.isTableExpression()) {
            throw DbException.get(ErrorCode.TABLE_OR_VIEW_ALREADY_EXISTS_1, cteViewName);
        }
        if (isPersistent) {
            oldViewFound.lock(session, true, true);
            database.removeSchemaObject(session, oldViewFound);
        } else {
            session.removeLocalTempTable(oldViewFound);
        }
        oldViewFound = null;
    }
    /*
         * This table is created as a workaround because recursive table
         * expressions need to reference something that look like themselves to
         * work (its removed after creation in this method). Only create table
         * data and table if we don't have a working CTE already.
         */
    recursiveTable = TableView.createShadowTableForRecursiveTableExpression(isPersistent, session, cteViewName, schema, columns, database);
    List<Column> columnTemplateList;
    String[] querySQLOutput = { null };
    try {
        read("AS");
        read("(");
        Query withQuery = parseSelect();
        if (isPersistent) {
            withQuery.session = session;
        }
        read(")");
        columnTemplateList = TableView.createQueryColumnTemplateList(cols, withQuery, querySQLOutput);
    } finally {
        TableView.destroyShadowTableForRecursiveExpression(isPersistent, session, recursiveTable);
    }
    return createCTEView(cteViewName, querySQLOutput[0], columnTemplateList, true, /* allowRecursiveQueryDetection */
    true, /* add to session */
    isPersistent, session);
}
Also used : RangeTable(org.h2.table.RangeTable) TruncateTable(org.h2.command.ddl.TruncateTable) CreateTable(org.h2.command.ddl.CreateTable) FunctionTable(org.h2.table.FunctionTable) CreateLinkedTable(org.h2.command.ddl.CreateLinkedTable) Table(org.h2.table.Table) DropTable(org.h2.command.ddl.DropTable) Query(org.h2.command.dml.Query) AlterTableRenameColumn(org.h2.command.ddl.AlterTableRenameColumn) AlterTableAlterColumn(org.h2.command.ddl.AlterTableAlterColumn) Column(org.h2.table.Column) ExpressionColumn(org.h2.expression.ExpressionColumn) IndexColumn(org.h2.table.IndexColumn) DropSchema(org.h2.command.ddl.DropSchema) CreateSchema(org.h2.command.ddl.CreateSchema) Schema(org.h2.schema.Schema) ValueString(org.h2.value.ValueString) TableView(org.h2.table.TableView)

Example 34 with In

use of org.h2.dev.util.BinaryArithmeticStream.In in project h2database by h2database.

the class Parser method parseSelectSimpleFromPart.

private void parseSelectSimpleFromPart(Select command) {
    do {
        TableFilter filter = readTableFilter();
        parseJoinTableFilter(filter, command);
    } while (readIf(","));
    // to get the order as it was in the original query.
    if (session.isForceJoinOrder()) {
        sortTableFilters(command.getTopFilters());
    }
}
Also used : TableFilter(org.h2.table.TableFilter)

Example 35 with In

use of org.h2.dev.util.BinaryArithmeticStream.In in project h2database by h2database.

the class Parser method parseMergeUsing.

private MergeUsing parseMergeUsing(Merge oldCommand, int start) {
    MergeUsing command = new MergeUsing(oldCommand);
    currentPrepared = command;
    if (readIf("(")) {
        /* a select query is supplied */
        if (isSelect()) {
            command.setQuery(parseSelect());
            read(")");
        }
        command.setQueryAlias(readFromAlias(null, Collections.singletonList("ON")));
        String[] querySQLOutput = { null };
        List<Column> columnTemplateList = TableView.createQueryColumnTemplateList(null, command.getQuery(), querySQLOutput);
        TableView temporarySourceTableView = createCTEView(command.getQueryAlias(), querySQLOutput[0], columnTemplateList, false, /* no recursion */
        false, /* do not add to session */
        false, /* isPersistent */
        session);
        TableFilter sourceTableFilter = new TableFilter(session, temporarySourceTableView, command.getQueryAlias(), rightsChecked, (Select) command.getQuery(), 0, null);
        command.setSourceTableFilter(sourceTableFilter);
    } else {
        /* Its a table name, simulate a query by building a select query for the table */
        List<String> excludeIdentifiers = Collections.singletonList("ON");
        TableFilter sourceTableFilter = readSimpleTableFilter(0, excludeIdentifiers);
        command.setSourceTableFilter(sourceTableFilter);
        StringBuilder buff = new StringBuilder("SELECT * FROM ");
        appendTableWithSchemaAndAlias(buff, sourceTableFilter.getTable(), sourceTableFilter.getTableAlias());
        Prepared preparedQuery = prepare(session, buff.toString(), null);
        command.setQuery((Select) preparedQuery);
    }
    read("ON");
    read("(");
    Expression condition = readExpression();
    command.setOnCondition(condition);
    read(")");
    if (readIfAll("WHEN", "MATCHED", "THEN")) {
        int startMatched = lastParseIndex;
        if (readIf("UPDATE")) {
            Update updateCommand = new Update(session);
            // currentPrepared = updateCommand;
            TableFilter filter = command.getTargetTableFilter();
            updateCommand.setTableFilter(filter);
            parseUpdateSetClause(updateCommand, filter, startMatched);
            command.setUpdateCommand(updateCommand);
        }
        startMatched = lastParseIndex;
        if (readIf("DELETE")) {
            Delete deleteCommand = new Delete(session);
            TableFilter filter = command.getTargetTableFilter();
            deleteCommand.setTableFilter(filter);
            parseDeleteGivenTable(deleteCommand, null, startMatched);
            command.setDeleteCommand(deleteCommand);
        }
    }
    if (readIfAll("WHEN", "NOT", "MATCHED", "THEN")) {
        if (readIf("INSERT")) {
            Insert insertCommand = new Insert(session);
            insertCommand.setTable(command.getTargetTable());
            parseInsertGivenTable(insertCommand, command.getTargetTable());
            command.setInsertCommand(insertCommand);
        }
    }
    setSQL(command, "MERGE", start);
    // build and prepare the targetMatchQuery ready to test each rows
    // existence in the target table (using source row to match)
    StringBuilder targetMatchQuerySQL = new StringBuilder("SELECT _ROWID_ FROM ");
    appendTableWithSchemaAndAlias(targetMatchQuerySQL, command.getTargetTable(), command.getTargetTableFilter().getTableAlias());
    targetMatchQuerySQL.append(" WHERE ").append(command.getOnCondition().getSQL());
    command.setTargetMatchQuery((Select) parse(targetMatchQuerySQL.toString()));
    return command;
}
Also used : Delete(org.h2.command.dml.Delete) ValueString(org.h2.value.ValueString) Update(org.h2.command.dml.Update) Insert(org.h2.command.dml.Insert) AlterTableRenameConstraint(org.h2.command.ddl.AlterTableRenameConstraint) AlterTableAddConstraint(org.h2.command.ddl.AlterTableAddConstraint) AlterTableDropConstraint(org.h2.command.ddl.AlterTableDropConstraint) AlterTableRenameColumn(org.h2.command.ddl.AlterTableRenameColumn) AlterTableAlterColumn(org.h2.command.ddl.AlterTableAlterColumn) Column(org.h2.table.Column) ExpressionColumn(org.h2.expression.ExpressionColumn) IndexColumn(org.h2.table.IndexColumn) TableFilter(org.h2.table.TableFilter) Expression(org.h2.expression.Expression) ValueExpression(org.h2.expression.ValueExpression) MergeUsing(org.h2.command.dml.MergeUsing) TableView(org.h2.table.TableView)

Aggregations

SQLException (java.sql.SQLException)63 Connection (java.sql.Connection)59 DbException (org.h2.message.DbException)56 PreparedStatement (java.sql.PreparedStatement)54 ResultSet (java.sql.ResultSet)47 Statement (java.sql.Statement)44 Value (org.h2.value.Value)40 IOException (java.io.IOException)39 ByteArrayInputStream (java.io.ByteArrayInputStream)30 InputStream (java.io.InputStream)29 Column (org.h2.table.Column)24 ArrayList (java.util.ArrayList)23 SimpleResultSet (org.h2.tools.SimpleResultSet)23 Random (java.util.Random)19 Expression (org.h2.expression.Expression)18 JdbcConnection (org.h2.jdbc.JdbcConnection)18 Index (org.h2.index.Index)16 ValueString (org.h2.value.ValueString)16 ByteArrayOutputStream (java.io.ByteArrayOutputStream)15 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)15