Search in sources :

Example 6 with User

use of org.h2.engine.User 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 7 with User

use of org.h2.engine.User 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 8 with User

use of org.h2.engine.User 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 9 with User

use of org.h2.engine.User in project h2database by h2database.

the class CreateLinkedTable method update.

@Override
public int update() {
    session.commit(true);
    Database db = session.getDatabase();
    session.getUser().checkAdmin();
    if (getSchema().resolveTableOrView(session, tableName) != null) {
        if (ifNotExists) {
            return 0;
        }
        throw DbException.get(ErrorCode.TABLE_OR_VIEW_ALREADY_EXISTS_1, tableName);
    }
    int id = getObjectId();
    TableLink table = getSchema().createTableLink(id, tableName, driver, url, user, password, originalSchema, originalTable, emitUpdates, force);
    table.setTemporary(temporary);
    table.setGlobalTemporary(globalTemporary);
    table.setComment(comment);
    table.setReadOnly(readOnly);
    if (temporary && !globalTemporary) {
        session.addLocalTempTable(table);
    } else {
        db.addSchemaObject(session, table);
    }
    return 0;
}
Also used : Database(org.h2.engine.Database) TableLink(org.h2.table.TableLink)

Example 10 with User

use of org.h2.engine.User in project h2database by h2database.

the class ScriptCommand method query.

@Override
public ResultInterface query(int maxrows) {
    session.getUser().checkAdmin();
    reset();
    Database db = session.getDatabase();
    if (schemaNames != null) {
        for (String schemaName : schemaNames) {
            Schema schema = db.findSchema(schemaName);
            if (schema == null) {
                throw DbException.get(ErrorCode.SCHEMA_NOT_FOUND_1, schemaName);
            }
        }
    }
    try {
        result = createResult();
        deleteStore();
        openOutput();
        if (out != null) {
            buffer = new byte[Constants.IO_BUFFER_SIZE];
        }
        if (settings) {
            for (Setting setting : db.getAllSettings()) {
                if (setting.getName().equals(SetTypes.getTypeName(SetTypes.CREATE_BUILD))) {
                    // (it is only set when creating the database)
                    continue;
                }
                add(setting.getCreateSQL(), false);
            }
        }
        if (out != null) {
            add("", true);
        }
        for (User user : db.getAllUsers()) {
            add(user.getCreateSQL(passwords), false);
        }
        for (Role role : db.getAllRoles()) {
            add(role.getCreateSQL(true), false);
        }
        for (Schema schema : db.getAllSchemas()) {
            if (excludeSchema(schema)) {
                continue;
            }
            add(schema.getCreateSQL(), false);
        }
        for (UserDataType datatype : db.getAllUserDataTypes()) {
            if (drop) {
                add(datatype.getDropSQL(), false);
            }
            add(datatype.getCreateSQL(), false);
        }
        for (SchemaObject obj : db.getAllSchemaObjects(DbObject.CONSTANT)) {
            if (excludeSchema(obj.getSchema())) {
                continue;
            }
            Constant constant = (Constant) obj;
            add(constant.getCreateSQL(), false);
        }
        final ArrayList<Table> tables = db.getAllTablesAndViews(false);
        // sort by id, so that views are after tables and views on views
        // after the base views
        Collections.sort(tables, new Comparator<Table>() {

            @Override
            public int compare(Table t1, Table t2) {
                return t1.getId() - t2.getId();
            }
        });
        // Generate the DROP XXX  ... IF EXISTS
        for (Table table : tables) {
            if (excludeSchema(table.getSchema())) {
                continue;
            }
            if (excludeTable(table)) {
                continue;
            }
            if (table.isHidden()) {
                continue;
            }
            table.lock(session, false, false);
            String sql = table.getCreateSQL();
            if (sql == null) {
                // null for metadata tables
                continue;
            }
            if (drop) {
                add(table.getDropSQL(), false);
            }
        }
        for (SchemaObject obj : db.getAllSchemaObjects(DbObject.FUNCTION_ALIAS)) {
            if (excludeSchema(obj.getSchema())) {
                continue;
            }
            if (drop) {
                add(obj.getDropSQL(), false);
            }
            add(obj.getCreateSQL(), false);
        }
        for (UserAggregate agg : db.getAllAggregates()) {
            if (drop) {
                add(agg.getDropSQL(), false);
            }
            add(agg.getCreateSQL(), false);
        }
        for (SchemaObject obj : db.getAllSchemaObjects(DbObject.SEQUENCE)) {
            if (excludeSchema(obj.getSchema())) {
                continue;
            }
            Sequence sequence = (Sequence) obj;
            if (drop) {
                add(sequence.getDropSQL(), false);
            }
            add(sequence.getCreateSQL(), false);
        }
        // Generate CREATE TABLE and INSERT...VALUES
        int count = 0;
        for (Table table : tables) {
            if (excludeSchema(table.getSchema())) {
                continue;
            }
            if (excludeTable(table)) {
                continue;
            }
            if (table.isHidden()) {
                continue;
            }
            table.lock(session, false, false);
            String createTableSql = table.getCreateSQL();
            if (createTableSql == null) {
                // null for metadata tables
                continue;
            }
            final TableType tableType = table.getTableType();
            add(createTableSql, false);
            final ArrayList<Constraint> constraints = table.getConstraints();
            if (constraints != null) {
                for (Constraint constraint : constraints) {
                    if (Constraint.Type.PRIMARY_KEY == constraint.getConstraintType()) {
                        add(constraint.getCreateSQLWithoutIndexes(), false);
                    }
                }
            }
            if (TableType.TABLE == tableType) {
                if (table.canGetRowCount()) {
                    String rowcount = "-- " + table.getRowCountApproximation() + " +/- SELECT COUNT(*) FROM " + table.getSQL();
                    add(rowcount, false);
                }
                if (data) {
                    count = generateInsertValues(count, table);
                }
            }
            final ArrayList<Index> indexes = table.getIndexes();
            for (int j = 0; indexes != null && j < indexes.size(); j++) {
                Index index = indexes.get(j);
                if (!index.getIndexType().getBelongsToConstraint()) {
                    add(index.getCreateSQL(), false);
                }
            }
        }
        if (tempLobTableCreated) {
            add("DROP TABLE IF EXISTS SYSTEM_LOB_STREAM", true);
            add("CALL SYSTEM_COMBINE_BLOB(-1)", true);
            add("DROP ALIAS IF EXISTS SYSTEM_COMBINE_CLOB", true);
            add("DROP ALIAS IF EXISTS SYSTEM_COMBINE_BLOB", true);
            tempLobTableCreated = false;
        }
        // Generate CREATE CONSTRAINT ...
        final ArrayList<SchemaObject> constraints = db.getAllSchemaObjects(DbObject.CONSTRAINT);
        Collections.sort(constraints, new Comparator<SchemaObject>() {

            @Override
            public int compare(SchemaObject c1, SchemaObject c2) {
                return ((Constraint) c1).compareTo((Constraint) c2);
            }
        });
        for (SchemaObject obj : constraints) {
            if (excludeSchema(obj.getSchema())) {
                continue;
            }
            Constraint constraint = (Constraint) obj;
            if (excludeTable(constraint.getTable())) {
                continue;
            }
            if (constraint.getTable().isHidden()) {
                continue;
            }
            if (Constraint.Type.PRIMARY_KEY != constraint.getConstraintType()) {
                add(constraint.getCreateSQLWithoutIndexes(), false);
            }
        }
        // Generate CREATE TRIGGER ...
        for (SchemaObject obj : db.getAllSchemaObjects(DbObject.TRIGGER)) {
            if (excludeSchema(obj.getSchema())) {
                continue;
            }
            TriggerObject trigger = (TriggerObject) obj;
            if (excludeTable(trigger.getTable())) {
                continue;
            }
            add(trigger.getCreateSQL(), false);
        }
        // Generate GRANT ...
        for (Right right : db.getAllRights()) {
            DbObject object = right.getGrantedObject();
            if (object != null) {
                if (object instanceof Schema) {
                    if (excludeSchema((Schema) object)) {
                        continue;
                    }
                } else if (object instanceof Table) {
                    Table table = (Table) object;
                    if (excludeSchema(table.getSchema())) {
                        continue;
                    }
                    if (excludeTable(table)) {
                        continue;
                    }
                }
            }
            add(right.getCreateSQL(), false);
        }
        // Generate COMMENT ON ...
        for (Comment comment : db.getAllComments()) {
            add(comment.getCreateSQL(), false);
        }
        if (out != null) {
            out.close();
        }
    } catch (IOException e) {
        throw DbException.convertIOException(e, getFileName());
    } finally {
        closeIO();
    }
    result.done();
    LocalResult r = result;
    reset();
    return r;
}
Also used : SchemaObject(org.h2.schema.SchemaObject) User(org.h2.engine.User) Constraint(org.h2.constraint.Constraint) Constant(org.h2.schema.Constant) Schema(org.h2.schema.Schema) Right(org.h2.engine.Right) TriggerObject(org.h2.schema.TriggerObject) Index(org.h2.index.Index) ValueString(org.h2.value.ValueString) LocalResult(org.h2.result.LocalResult) Database(org.h2.engine.Database) Comment(org.h2.engine.Comment) Table(org.h2.table.Table) TableType(org.h2.table.TableType) DbObject(org.h2.engine.DbObject) Setting(org.h2.engine.Setting) UserDataType(org.h2.engine.UserDataType) Sequence(org.h2.schema.Sequence) IOException(java.io.IOException) Constraint(org.h2.constraint.Constraint) Role(org.h2.engine.Role) UserAggregate(org.h2.engine.UserAggregate)

Aggregations

Connection (java.sql.Connection)36 SQLException (java.sql.SQLException)21 PreparedStatement (java.sql.PreparedStatement)17 Statement (java.sql.Statement)17 ResultSet (java.sql.ResultSet)16 Server (org.h2.tools.Server)15 DbException (org.h2.message.DbException)14 Column (org.h2.table.Column)12 ValueString (org.h2.value.ValueString)12 Properties (java.util.Properties)10 Database (org.h2.engine.Database)10 Schema (org.h2.schema.Schema)8 IOException (java.io.IOException)7 User (org.h2.engine.User)7 JdbcDataSource (org.h2.jdbcx.JdbcDataSource)7 SimpleResultSet (org.h2.tools.SimpleResultSet)7 Value (org.h2.value.Value)7 PrintStream (java.io.PrintStream)6 Timestamp (java.sql.Timestamp)6 GridH2Table (org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)6