Search in sources :

Example 16 with Function

use of org.h2.expression.Function in project ignite by apache.

the class GridSqlFunction method getSQL.

/**
 * {@inheritDoc}
 */
@Override
public String getSQL() {
    StatementBuilder buff = new StatementBuilder();
    if (schema != null)
        buff.append(Parser.quoteIdentifier(schema)).append('.');
    // We don't need to quote identifier as long as H2 never does so with function names when generating plan SQL.
    // On the other hand, quoting identifiers that also serve as keywords (like CURRENT_DATE() and CURRENT_DATE)
    // turns CURRENT_DATE() into "CURRENT_DATE"(), which is not good.
    buff.append(name);
    if (type == CASE) {
        buff.append(' ').append(child().getSQL());
        for (int i = 1, len = size() - 1; i < len; i += 2) {
            buff.append(" WHEN ").append(child(i).getSQL());
            buff.append(" THEN ").append(child(i + 1).getSQL());
        }
        if ((size() & 1) == 0)
            buff.append(" ELSE ").append(child(size() - 1).getSQL());
        return buff.append(" END").toString();
    }
    buff.append('(');
    switch(type) {
        case CAST:
        case CONVERT:
            assert size() == 1;
            String castType = resultType().sql();
            assert !F.isEmpty(castType) : castType;
            buff.append(child().getSQL());
            buff.append(type == CAST ? " AS " : ",");
            buff.append(castType);
            break;
        case EXTRACT:
            ValueString v = (ValueString) ((GridSqlConst) child(0)).value();
            buff.append(v.getString()).append(" FROM ").append(child(1).getSQL());
            break;
        case TABLE:
            for (int i = 0; i < size(); i++) {
                buff.appendExceptFirst(", ");
                GridSqlElement e = child(i);
                // id int = ?, name varchar = ('aaa', 'bbb')
                buff.append(Parser.quoteIdentifier(((GridSqlAlias) e).alias())).append(' ').append(e.resultType().sql()).append('=').append(e.child().getSQL());
            }
            break;
        default:
            for (int i = 0; i < size(); i++) {
                buff.appendExceptFirst(", ");
                buff.append(child(i).getSQL());
            }
    }
    return buff.append(')').toString();
}
Also used : StatementBuilder(org.h2.util.StatementBuilder) ValueString(org.h2.value.ValueString) ValueString(org.h2.value.ValueString)

Example 17 with Function

use of org.h2.expression.Function in project Gargoyle by callakrsos.

the class FileSearcher method listSources.

public static List<ProjectInfo> listSources(String classDirName) throws Exception {
    File file = new File(classDirName);
    // 기본적인 파일의 존재유무 및 디렉토리인지 체크.
    if (!file.exists())
        throw new FileNotFoundException(file + " Not found!");
    //
    if (!file.isDirectory())
        throw new IllegalArgumentException("only directory.");
    /*
		 * 디렉토리안에 클래스패스 정보가 존재하는지 확인하고 존재한다면 classpath에 기술된 정보 기준으로 클래스 파일을
		 * 로드한다. 프로그램내에서 workspace를 선택한 경우일수있고, 프로젝트를 선택한 두가지의 경우가 있기때문에 두가지의
		 * 케이스를 고려한 로직이 들어간다.
		 */
    /*
		 * 일단 워크스페이스를 선택한경우라고 가정하고 워크스페이스내에 폴더들을 순차적으로 돌아보면서 classpath의 존재유무를 찾고
		 * 존재하는케이스는 따로 모아놓는다. 파일레벨은 워크스페이스(0레벨)-프로젝트(1레벨)로 가정하여 1레벨까지만 이동한다.
		 */
    List<File> listFiles = findClassPaths(file);
    /*
		 * classpath파일을 찾은경우 그 파일path를 기준으로 클래스들을 로딩한다.
		 */
    List<ProjectInfo> allClasses = new ArrayList<>();
    if (listFiles != null && !listFiles.isEmpty())
        LOGGER.debug(" im will working...");
    long startTime = System.currentTimeMillis();
    int searchedDirCount = 0;
    StringBuffer srchedDirNames = new StringBuffer();
    for (File f : listFiles) {
        try {
            ClassPath parsingClassPath = parsingClassPath(f.getAbsolutePath());
            // 프로젝트파일.
            File projectFile = f.getParentFile();
            // output 속성값의 존재유무만 확인하여 컴파일되는 경로를 찾는다.
            List<ProjectInfo> collect = parsingClassPath.toStream().filter(entry -> {
                boolean notEmpty = ValueUtil.isNotEmpty(entry.getPath());
                LOGGER.debug(String.format("srch entry path : %s is Traget %b ", entry.getPath(), notEmpty));
                return notEmpty;
            }).filter(entry -> {
                return StringUtils.equals("src", entry.getKind());
            }).map(pram -> pram.getPath()).distinct().parallel().flatMap(new Function<String, Stream<ProjectInfo>>() {

                @Override
                public Stream<ProjectInfo> apply(String entry) {
                    LOGGER.debug(String.format("entry : %s", entry));
                    File compiledFilePath = new File(projectFile, entry);
                    int length = compiledFilePath.getAbsolutePath().length() + 1;
                    List<String> findJavaSources = findSource(projectFile.getAbsolutePath(), compiledFilePath, length);
                    LOGGER.debug(compiledFilePath.toString());
                    LOGGER.debug(findJavaSources.toString());
                    LOGGER.debug(String.valueOf(findJavaSources.size()));
                    ProjectInfo classInfo = new ProjectInfo();
                    classInfo.setProjectName(projectFile.getName());
                    classInfo.setProjectDir(compiledFilePath.getAbsolutePath());
                    classInfo.setJavaSources(findJavaSources);
                    return Stream.of(classInfo);
                }
            }).collect(Collectors.toList());
            allClasses.addAll(collect);
            searchedDirCount++;
            srchedDirNames.append(f.getAbsolutePath()).append(SystemUtils.LINE_SEPARATOR);
        } catch (SAXParseException e) {
            LOGGER.error(String.format("정상적인 XML 형태가 아님. 파일명 :  %s", f.getAbsolutePath()));
            LOGGER.error(String.format("%d 행 :: %d 열", e.getLineNumber(), e.getColumnNumber()));
        }
    }
    long endTime = System.currentTimeMillis();
    long costMillisend = endTime - startTime;
    LOGGER.debug(String.format("Total Cost time : %s (ms) searched Directory Count : %d ", costMillisend, searchedDirCount));
    LOGGER.debug(String.format("Searched Dirs info \n%s", srchedDirNames.toString()));
    return allClasses;
}
Also used : URL(java.net.URL) ZipUtil(com.kyj.fx.voeditor.visual.util.ZipUtil) LoggerFactory(org.slf4j.LoggerFactory) Function(java.util.function.Function) Supplier(java.util.function.Supplier) MimetypesFileTypeMap(javax.activation.MimetypesFileTypeMap) ArrayList(java.util.ArrayList) URLClassLoader(java.net.URLClassLoader) Document(org.w3c.dom.Document) Node(org.w3c.dom.Node) NamedNodeMap(org.w3c.dom.NamedNodeMap) Method(java.lang.reflect.Method) SystemUtils(org.apache.commons.lang.SystemUtils) ClassPathEntry(com.kyj.fx.voeditor.visual.main.model.vo.ClassPathEntry) InputSource(org.xml.sax.InputSource) Logger(org.slf4j.Logger) NodeList(org.w3c.dom.NodeList) MalformedURLException(java.net.MalformedURLException) Predicate(java.util.function.Predicate) ClassPath(com.kyj.fx.voeditor.visual.main.model.vo.ClassPath) ValueUtil(com.kyj.fx.voeditor.visual.util.ValueUtil) FileInputStream(java.io.FileInputStream) Reader(java.io.Reader) ConfigResourceLoader(com.kyj.fx.voeditor.visual.momory.ConfigResourceLoader) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) StringUtils(org.h2.util.StringUtils) List(java.util.List) SAXParseException(org.xml.sax.SAXParseException) Stream(java.util.stream.Stream) DocumentBuilder(javax.xml.parsers.DocumentBuilder) FileTypeMap(javax.activation.FileTypeMap) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) ClassPath(com.kyj.fx.voeditor.visual.main.model.vo.ClassPath) FileNotFoundException(java.io.FileNotFoundException) ArrayList(java.util.ArrayList) Function(java.util.function.Function) SAXParseException(org.xml.sax.SAXParseException) File(java.io.File)

Example 18 with Function

use of org.h2.expression.Function in project elastic-core-maven by OrdinaryDude.

the class FullTextTrigger method init.

/**
 * Initialize the fulltext support for a new database
 *
 * This method should be called from NxtDbVersion when performing the database version update
 * that enables NRS fulltext search support
 */
public static void init() {
    String ourClassName = FullTextTrigger.class.getName();
    try (Connection conn = Db.db.getConnection();
        Statement stmt = conn.createStatement();
        Statement qstmt = conn.createStatement()) {
        // 
        // Check if we have already been initialized.
        // 
        boolean alreadyInitialized = true;
        boolean triggersExist = false;
        try (ResultSet rs = qstmt.executeQuery("SELECT JAVA_CLASS FROM INFORMATION_SCHEMA.TRIGGERS " + "WHERE SUBSTRING(TRIGGER_NAME, 0, 4) = 'FTL_'")) {
            while (rs.next()) {
                triggersExist = true;
                if (!rs.getString(1).startsWith(ourClassName)) {
                    alreadyInitialized = false;
                }
            }
        }
        if (triggersExist && alreadyInitialized) {
            Logger.logInfoMessage("NRS fulltext support is already initialized");
            return;
        }
        // 
        // We need to delete an existing Lucene index since the V3 file format is not compatible with V5
        // 
        getIndexPath(conn);
        removeIndexFiles(conn);
        // 
        // Drop the H2 Lucene V3 function aliases
        // 
        stmt.execute("DROP ALIAS IF EXISTS FTL_INIT");
        stmt.execute("DROP ALIAS IF EXISTS FTL_CREATE_INDEX");
        stmt.execute("DROP ALIAS IF EXISTS FTL_DROP_INDEX");
        stmt.execute("DROP ALIAS IF EXISTS FTL_DROP_ALL");
        stmt.execute("DROP ALIAS IF EXISTS FTL_REINDEX");
        stmt.execute("DROP ALIAS IF EXISTS FTL_SEARCH");
        stmt.execute("DROP ALIAS IF EXISTS FTL_SEARCH_DATA");
        Logger.logInfoMessage("H2 fulltext function aliases dropped");
        // 
        // Create our schema and table
        // 
        stmt.execute("CREATE SCHEMA IF NOT EXISTS FTL");
        stmt.execute("CREATE TABLE IF NOT EXISTS FTL.INDEXES " + "(SCHEMA VARCHAR, TABLE VARCHAR, COLUMNS VARCHAR, PRIMARY KEY(SCHEMA, TABLE))");
        Logger.logInfoMessage("NRS fulltext schema created");
        // 
        try (ResultSet rs = qstmt.executeQuery("SELECT * FROM FTL.INDEXES")) {
            while (rs.next()) {
                String schema = rs.getString("SCHEMA");
                String table = rs.getString("TABLE");
                stmt.execute("DROP TRIGGER IF EXISTS FTL_" + table);
                stmt.execute(String.format("CREATE TRIGGER FTL_%s AFTER INSERT,UPDATE,DELETE ON %s.%s " + "FOR EACH ROW CALL \"%s\"", table, schema, table, ourClassName));
            }
        }
        // 
        // Rebuild the Lucene index since the Lucene V3 index is not compatible with Lucene V5
        // 
        reindex(conn);
        // 
        // Create our function aliases
        // 
        stmt.execute("CREATE ALIAS FTL_CREATE_INDEX FOR \"" + ourClassName + ".createIndex\"");
        stmt.execute("CREATE ALIAS FTL_DROP_INDEX FOR \"" + ourClassName + ".dropIndex\"");
        stmt.execute("CREATE ALIAS FTL_SEARCH NOBUFFER FOR \"" + ourClassName + ".search\"");
        Logger.logInfoMessage("NRS fulltext aliases created");
    } catch (SQLException exc) {
        Logger.logErrorMessage("Unable to initialize NRS fulltext search support", exc);
        throw new RuntimeException(exc.toString(), exc);
    }
}
Also used : SQLException(java.sql.SQLException) Statement(java.sql.Statement) Connection(java.sql.Connection) SimpleResultSet(org.h2.tools.SimpleResultSet) ResultSet(java.sql.ResultSet)

Example 19 with Function

use of org.h2.expression.Function in project elastic-core-maven by OrdinaryDude.

the class FullTextTrigger method init.

/**
 * Initialize the trigger (Trigger interface)
 *
 * @param   conn                Database connection
 * @param   schema              Database schema name
 * @param   trigger             Database trigger name
 * @param   table               Database table name
 * @param   before              TRUE if trigger is called before database operation
 * @param   type                Trigger type
 * @throws  SQLException        A SQL error occurred
 */
@Override
public void init(Connection conn, String schema, String trigger, String table, boolean before, int type) throws SQLException {
    // 
    if (!isActive || table.contains("_COPY_")) {
        return;
    }
    // 
    // Access the Lucene index
    // 
    // We need to get the access just once, either in a trigger or in a function alias
    // 
    getIndexAccess(conn);
    // 
    // Get table and index information
    // 
    tableName = schema + "." + table;
    try (Statement stmt = conn.createStatement()) {
        // 
        try (ResultSet rs = stmt.executeQuery("SHOW COLUMNS FROM " + table + " FROM " + schema)) {
            int index = 0;
            while (rs.next()) {
                String columnName = rs.getString("FIELD");
                String columnType = rs.getString("TYPE");
                columnType = columnType.substring(0, columnType.indexOf('('));
                columnNames.add(columnName);
                columnTypes.add(columnType);
                if (columnName.equals("DB_ID")) {
                    dbColumn = index;
                }
                index++;
            }
        }
        if (dbColumn < 0) {
            Logger.logErrorMessage("DB_ID column not found for table " + tableName);
            return;
        }
        // 
        try (ResultSet rs = stmt.executeQuery(String.format("SELECT COLUMNS FROM FTL.INDEXES WHERE SCHEMA = '%s' AND TABLE = '%s'", schema, table))) {
            if (rs.next()) {
                String[] columns = rs.getString(1).split(",");
                for (String column : columns) {
                    int pos = columnNames.indexOf(column);
                    if (pos >= 0) {
                        if (columnTypes.get(pos).equals("VARCHAR")) {
                            indexColumns.add(pos);
                        } else {
                            Logger.logErrorMessage("Indexed column " + column + " in table " + tableName + " is not a string");
                        }
                    } else {
                        Logger.logErrorMessage("Indexed column " + column + " not found in table " + tableName);
                    }
                }
            }
        }
        if (indexColumns.isEmpty()) {
            Logger.logErrorMessage("No indexed columns found for table " + tableName);
            return;
        }
        // 
        // Trigger is enabled
        // 
        isEnabled = true;
        indexTriggers.put(tableName, this);
    } catch (SQLException exc) {
        Logger.logErrorMessage("Unable to get table information", exc);
    }
}
Also used : SQLException(java.sql.SQLException) Statement(java.sql.Statement) SimpleResultSet(org.h2.tools.SimpleResultSet) ResultSet(java.sql.ResultSet)

Example 20 with Function

use of org.h2.expression.Function in project jackrabbit-oak by apache.

the class PersistentCache method broadcast.

void broadcast(CacheType type, Function<WriteBuffer, Void> writer) {
    Broadcaster b = broadcaster;
    if (b == null) {
        return;
    }
    WriteBuffer buff = writeBuffer.get();
    if (buff == null) {
        buff = new WriteBuffer();
        writeBuffer.set(buff);
    }
    buff.clear();
    // space for the length
    buff.putInt(0);
    buff.put(broadcastId);
    buff.put((byte) type.ordinal());
    writer.apply(buff);
    ByteBuffer byteBuff = buff.getBuffer();
    int length = byteBuff.position();
    byteBuff.limit(length);
    // write length
    byteBuff.putInt(0, length);
    byteBuff.position(0);
    b.send(byteBuff);
}
Also used : WriteBuffer(org.h2.mvstore.WriteBuffer) Broadcaster(org.apache.jackrabbit.oak.plugins.document.persistentCache.broadcast.Broadcaster) UDPBroadcaster(org.apache.jackrabbit.oak.plugins.document.persistentCache.broadcast.UDPBroadcaster) InMemoryBroadcaster(org.apache.jackrabbit.oak.plugins.document.persistentCache.broadcast.InMemoryBroadcaster) TCPBroadcaster(org.apache.jackrabbit.oak.plugins.document.persistentCache.broadcast.TCPBroadcaster) ByteBuffer(java.nio.ByteBuffer)

Aggregations

SimpleResultSet (org.h2.tools.SimpleResultSet)10 ResultSet (java.sql.ResultSet)9 Function (org.h2.expression.Function)8 JavaFunction (org.h2.expression.JavaFunction)8 TableFunction (org.h2.expression.TableFunction)8 Expression (org.h2.expression.Expression)7 ValueExpression (org.h2.expression.ValueExpression)7 Column (org.h2.table.Column)7 Statement (java.sql.Statement)6 AlterTableAddConstraint (org.h2.command.ddl.AlterTableAddConstraint)6 AlterTableAlterColumn (org.h2.command.ddl.AlterTableAlterColumn)6 ExpressionColumn (org.h2.expression.ExpressionColumn)6 IndexColumn (org.h2.table.IndexColumn)6 SQLException (java.sql.SQLException)5 AlterTableRenameColumn (org.h2.command.ddl.AlterTableRenameColumn)5 PreparedStatement (java.sql.PreparedStatement)4 ValueString (org.h2.value.ValueString)4 Connection (java.sql.Connection)3 ArrayList (java.util.ArrayList)3 AlterTableDropConstraint (org.h2.command.ddl.AlterTableDropConstraint)3