Search in sources :

Example 1 with Trigger

use of org.h2.api.Trigger in project h2database by h2database.

the class Parser method parseCreate.

private Prepared parseCreate() {
    boolean orReplace = false;
    if (readIf("OR")) {
        read("REPLACE");
        orReplace = true;
    }
    boolean force = readIf("FORCE");
    if (readIf("VIEW")) {
        return parseCreateView(force, orReplace);
    } else if (readIf("ALIAS")) {
        return parseCreateFunctionAlias(force);
    } else if (readIf("SEQUENCE")) {
        return parseCreateSequence();
    } else if (readIf("USER")) {
        return parseCreateUser();
    } else if (readIf("TRIGGER")) {
        return parseCreateTrigger(force);
    } else if (readIf("ROLE")) {
        return parseCreateRole();
    } else if (readIf("SCHEMA")) {
        return parseCreateSchema();
    } else if (readIf("CONSTANT")) {
        return parseCreateConstant();
    } else if (readIf("DOMAIN")) {
        return parseCreateUserDataType();
    } else if (readIf("TYPE")) {
        return parseCreateUserDataType();
    } else if (readIf("DATATYPE")) {
        return parseCreateUserDataType();
    } else if (readIf("AGGREGATE")) {
        return parseCreateAggregate(force);
    } else if (readIf("LINKED")) {
        return parseCreateLinkedTable(false, false, force);
    }
    // tables or linked tables
    boolean memory = false, cached = false;
    if (readIf("MEMORY")) {
        memory = true;
    } else if (readIf("CACHED")) {
        cached = true;
    }
    if (readIf("LOCAL")) {
        read("TEMPORARY");
        if (readIf("LINKED")) {
            return parseCreateLinkedTable(true, false, force);
        }
        read("TABLE");
        return parseCreateTable(true, false, cached);
    } else if (readIf("GLOBAL")) {
        read("TEMPORARY");
        if (readIf("LINKED")) {
            return parseCreateLinkedTable(true, true, force);
        }
        read("TABLE");
        return parseCreateTable(true, true, cached);
    } else if (readIf("TEMP") || readIf("TEMPORARY")) {
        if (readIf("LINKED")) {
            return parseCreateLinkedTable(true, true, force);
        }
        read("TABLE");
        return parseCreateTable(true, true, cached);
    } else if (readIf("TABLE")) {
        if (!cached && !memory) {
            cached = database.getDefaultTableType() == Table.TYPE_CACHED;
        }
        return parseCreateTable(false, false, cached);
    } else if (readIf("SYNONYM")) {
        return parseCreateSynonym(orReplace);
    } else {
        boolean hash = false, primaryKey = false;
        boolean unique = false, spatial = false;
        String indexName = null;
        Schema oldSchema = null;
        boolean ifNotExists = false;
        if (readIf("PRIMARY")) {
            read("KEY");
            if (readIf("HASH")) {
                hash = true;
            }
            primaryKey = true;
            if (!isToken("ON")) {
                ifNotExists = readIfNotExists();
                indexName = readIdentifierWithSchema(null);
                oldSchema = getSchema();
            }
        } else {
            if (readIf("UNIQUE")) {
                unique = true;
            }
            if (readIf("HASH")) {
                hash = true;
            }
            if (readIf("SPATIAL")) {
                spatial = true;
            }
            if (readIf("INDEX")) {
                if (!isToken("ON")) {
                    ifNotExists = readIfNotExists();
                    indexName = readIdentifierWithSchema(null);
                    oldSchema = getSchema();
                }
            } else {
                throw getSyntaxError();
            }
        }
        read("ON");
        String tableName = readIdentifierWithSchema();
        checkSchema(oldSchema);
        CreateIndex command = new CreateIndex(session, getSchema());
        command.setIfNotExists(ifNotExists);
        command.setPrimaryKey(primaryKey);
        command.setTableName(tableName);
        command.setUnique(unique);
        command.setIndexName(indexName);
        command.setComment(readCommentIf());
        read("(");
        command.setIndexColumns(parseIndexColumnList());
        if (readIf("USING")) {
            if (hash) {
                throw getSyntaxError();
            }
            if (spatial) {
                throw getSyntaxError();
            }
            if (readIf("BTREE")) {
            // default
            } else if (readIf("RTREE")) {
                spatial = true;
            } else if (readIf("HASH")) {
                hash = true;
            } else {
                throw getSyntaxError();
            }
        }
        command.setHash(hash);
        command.setSpatial(spatial);
        return command;
    }
}
Also used : CreateIndex(org.h2.command.ddl.CreateIndex) DropSchema(org.h2.command.ddl.DropSchema) CreateSchema(org.h2.command.ddl.CreateSchema) Schema(org.h2.schema.Schema) ValueString(org.h2.value.ValueString)

Example 2 with Trigger

use of org.h2.api.Trigger 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)

Example 3 with Trigger

use of org.h2.api.Trigger in project h2database by h2database.

the class FullTextLucene method search.

/**
 * Do the search.
 *
 * @param conn the database connection
 * @param text the query
 * @param limit the limit
 * @param offset the offset
 * @param data whether the raw data should be returned
 * @return the result set
 */
protected static ResultSet search(Connection conn, String text, int limit, int offset, boolean data) throws SQLException {
    SimpleResultSet result = createResultSet(data);
    if (conn.getMetaData().getURL().startsWith("jdbc:columnlist:")) {
        // this is just to query the result set columns
        return result;
    }
    if (text == null || text.trim().length() == 0) {
        return result;
    }
    try {
        IndexAccess access = getIndexAccess(conn);
        // take a reference as the searcher may change
        IndexSearcher searcher = access.getSearcher();
        try {
            // reuse the same analyzer; it's thread-safe;
            // also allows subclasses to control the analyzer used.
            Analyzer analyzer = access.writer.getAnalyzer();
            QueryParser parser = new QueryParser(Version.LUCENE_30, LUCENE_FIELD_DATA, analyzer);
            Query query = parser.parse(text);
            // Lucene 3 insists on a hard limit and will not provide
            // a total hits value. Take at least 100 which is
            // an optimal limit for Lucene as any more
            // will trigger writing results to disk.
            int maxResults = (limit == 0 ? 100 : limit) + offset;
            TopDocs docs = searcher.search(query, maxResults);
            if (limit == 0) {
                limit = docs.totalHits;
            }
            for (int i = 0, len = docs.scoreDocs.length; i < limit && i + offset < docs.totalHits && i + offset < len; i++) {
                ScoreDoc sd = docs.scoreDocs[i + offset];
                Document doc = searcher.doc(sd.doc);
                float score = sd.score;
                String q = doc.get(LUCENE_FIELD_QUERY);
                if (data) {
                    int idx = q.indexOf(" WHERE ");
                    JdbcConnection c = (JdbcConnection) conn;
                    Session session = (Session) c.getSession();
                    Parser p = new Parser(session);
                    String tab = q.substring(0, idx);
                    ExpressionColumn expr = (ExpressionColumn) p.parseExpression(tab);
                    String schemaName = expr.getOriginalTableAliasName();
                    String tableName = expr.getColumnName();
                    q = q.substring(idx + " WHERE ".length());
                    Object[][] columnData = parseKey(conn, q);
                    result.addRow(schemaName, tableName, columnData[0], columnData[1], score);
                } else {
                    result.addRow(q, score);
                }
            }
        } finally {
            access.returnSearcher(searcher);
        }
    } catch (Exception e) {
        throw convertException(e);
    }
    return result;
}
Also used : IndexSearcher(org.apache.lucene.search.IndexSearcher) SimpleResultSet(org.h2.tools.SimpleResultSet) Query(org.apache.lucene.search.Query) JdbcConnection(org.h2.jdbc.JdbcConnection) Analyzer(org.apache.lucene.analysis.Analyzer) StandardAnalyzer(org.apache.lucene.analysis.standard.StandardAnalyzer) Document(org.apache.lucene.document.Document) SQLException(java.sql.SQLException) IOException(java.io.IOException) ScoreDoc(org.apache.lucene.search.ScoreDoc) Parser(org.h2.command.Parser) QueryParser(org.apache.lucene.queryParser.QueryParser) ExpressionColumn(org.h2.expression.ExpressionColumn) TopDocs(org.apache.lucene.search.TopDocs) QueryParser(org.apache.lucene.queryParser.QueryParser) Session(org.h2.engine.Session)

Example 4 with Trigger

use of org.h2.api.Trigger in project h2database by h2database.

the class TriggerObject method loadFromSource.

private Trigger loadFromSource() {
    SourceCompiler compiler = database.getCompiler();
    synchronized (compiler) {
        String fullClassName = Constants.USER_PACKAGE + ".trigger." + getName();
        compiler.setSource(fullClassName, triggerSource);
        try {
            if (SourceCompiler.isJavaxScriptSource(triggerSource)) {
                return (Trigger) compiler.getCompiledScript(fullClassName).eval();
            } else {
                final Method m = compiler.getMethod(fullClassName);
                if (m.getParameterTypes().length > 0) {
                    throw new IllegalStateException("No parameters are allowed for a trigger");
                }
                return (Trigger) m.invoke(null);
            }
        } catch (DbException e) {
            throw e;
        } catch (Exception e) {
            throw DbException.get(ErrorCode.SYNTAX_ERROR_1, e, triggerSource);
        }
    }
}
Also used : Trigger(org.h2.api.Trigger) Method(java.lang.reflect.Method) DbException(org.h2.message.DbException) SQLException(java.sql.SQLException) SourceCompiler(org.h2.util.SourceCompiler) DbException(org.h2.message.DbException)

Example 5 with Trigger

use of org.h2.api.Trigger in project h2database by h2database.

the class TriggerObject method fire.

/**
 * Call the trigger class if required. This method does nothing if the
 * trigger is not defined for the given action. This method is called before
 * or after any rows have been processed, once for each statement.
 *
 * @param session the session
 * @param type the trigger type
 * @param beforeAction if this method is called before applying the changes
 */
public void fire(Session session, int type, boolean beforeAction) {
    if (rowBased || before != beforeAction || (typeMask & type) == 0) {
        return;
    }
    load();
    Connection c2 = session.createConnection(false);
    boolean old = false;
    if (type != Trigger.SELECT) {
        old = session.setCommitOrRollbackDisabled(true);
    }
    Value identity = session.getLastScopeIdentity();
    try {
        triggerCallback.fire(c2, null, null);
    } catch (Throwable e) {
        throw DbException.get(ErrorCode.ERROR_EXECUTING_TRIGGER_3, e, getName(), triggerClassName != null ? triggerClassName : "..source..", e.toString());
    } finally {
        if (session.getLastTriggerIdentity() != null) {
            session.setLastScopeIdentity(session.getLastTriggerIdentity());
            session.setLastTriggerIdentity(null);
        } else {
            session.setLastScopeIdentity(identity);
        }
        if (type != Trigger.SELECT) {
            session.setCommitOrRollbackDisabled(old);
        }
    }
}
Also used : Connection(java.sql.Connection) Value(org.h2.value.Value)

Aggregations

Statement (java.sql.Statement)20 Connection (java.sql.Connection)17 PreparedStatement (java.sql.PreparedStatement)16 JdbcConnection (org.h2.jdbc.JdbcConnection)14 ResultSet (java.sql.ResultSet)13 SimpleResultSet (org.h2.tools.SimpleResultSet)8 SQLException (java.sql.SQLException)7 TriggerObject (org.h2.schema.TriggerObject)6 IOException (java.io.IOException)5 ValueString (org.h2.value.ValueString)5 DbObject (org.h2.engine.DbObject)4 Session (org.h2.engine.Session)4 DbException (org.h2.message.DbException)4 Sequence (org.h2.schema.Sequence)4 Constraint (org.h2.constraint.Constraint)3 Schema (org.h2.schema.Schema)3 Table (org.h2.table.Table)3 Analyzer (org.apache.lucene.analysis.Analyzer)2 StandardAnalyzer (org.apache.lucene.analysis.standard.StandardAnalyzer)2 Document (org.apache.lucene.document.Document)2