Search in sources :

Example 6 with OCommandContext

use of com.orientechnologies.orient.core.command.OCommandContext in project orientdb by orientechnologies.

the class OETLProcessor method parseConfigAndParameters.

public static OETLProcessor parseConfigAndParameters(String[] args) {
    final OCommandContext context = createDefaultContext();
    ODocument configuration = new ODocument().fromJSON("{}");
    for (final String arg : args) {
        if (arg.charAt(0) != '-') {
            try {
                final String config = OIOUtils.readFileAsString(new File(arg));
                configuration.merge(new ODocument().fromJSON(config, "noMap"), true, true);
                // configuration = ;
                ODocument cfgGlobal = configuration.field("config");
                if (cfgGlobal != null) {
                    for (String f : cfgGlobal.fieldNames()) {
                        context.setVariable(f, cfgGlobal.field(f));
                    }
                }
            } catch (IOException e) {
                throw OException.wrapException(new OConfigurationException("Error on loading config file: " + arg), e);
            }
        }
    }
    // override with args passed by command line
    for (final String arg : args) {
        if (arg.charAt(0) == '-') {
            final String[] parts = arg.substring(1).split("=");
            context.setVariable(parts[0], parts[1]);
        }
    }
    return new OETLProcessor().parse(configuration, context);
}
Also used : OConfigurationException(com.orientechnologies.orient.core.exception.OConfigurationException) OCommandContext(com.orientechnologies.orient.core.command.OCommandContext) IOException(java.io.IOException) File(java.io.File) ODocument(com.orientechnologies.orient.core.record.impl.ODocument)

Example 7 with OCommandContext

use of com.orientechnologies.orient.core.command.OCommandContext in project orientdb by orientechnologies.

the class SQLFunctionsTest method queryCustomFunction.

@Test
public void queryCustomFunction() {
    OSQLEngine.getInstance().registerFunction("bigger", new OSQLFunctionAbstract("bigger", 2, 2) {

        @Override
        public String getSyntax() {
            return "bigger(<first>, <second>)";
        }

        @Override
        public Object execute(Object iThis, OIdentifiable iCurrentRecord, Object iCurrentResult, final Object[] iParams, OCommandContext iContext) {
            if (iParams[0] == null || iParams[1] == null)
                // CHECK BOTH EXPECTED PARAMETERS
                return null;
            if (!(iParams[0] instanceof Number) || !(iParams[1] instanceof Number))
                // EXCLUDE IT FROM THE RESULT SET
                return null;
            // USE DOUBLE TO AVOID LOSS OF PRECISION
            final double v1 = ((Number) iParams[0]).doubleValue();
            final double v2 = ((Number) iParams[1]).doubleValue();
            return Math.max(v1, v2);
        }
    });
    List<ODocument> result = database.command(new OSQLSynchQuery<ODocument>("select from Account where bigger(id,1000) = 1000")).execute();
    Assert.assertTrue(result.size() != 0);
    for (ODocument d : result) {
        Assert.assertTrue((Integer) d.field("id") <= 1000);
    }
    OSQLEngine.getInstance().unregisterFunction("bigger");
}
Also used : OSQLFunctionAbstract(com.orientechnologies.orient.core.sql.functions.OSQLFunctionAbstract) OCommandContext(com.orientechnologies.orient.core.command.OCommandContext) OSQLSynchQuery(com.orientechnologies.orient.core.sql.query.OSQLSynchQuery) OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) ODocument(com.orientechnologies.orient.core.record.impl.ODocument) Test(org.testng.annotations.Test)

Example 8 with OCommandContext

use of com.orientechnologies.orient.core.command.OCommandContext in project orientdb by orientechnologies.

the class TraverseTest method traverseAPIIterating.

@Test
public void traverseAPIIterating() {
    int cycles = 0;
    for (OIdentifiable id : new OTraverse().target(database.browseClass("Movie").iterator()).predicate(new OCommandPredicate() {

        @Override
        public Object evaluate(OIdentifiable iRecord, ODocument iCurrentResult, OCommandContext iContext) {
            return ((Integer) iContext.getVariable("depth")) <= 2;
        }
    })) {
        cycles++;
    }
    Assert.assertTrue(cycles > 0);
}
Also used : OCommandContext(com.orientechnologies.orient.core.command.OCommandContext) OTraverse(com.orientechnologies.orient.core.command.traverse.OTraverse) OCommandPredicate(com.orientechnologies.orient.core.command.OCommandPredicate) OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) ODocument(com.orientechnologies.orient.core.record.impl.ODocument) Test(org.testng.annotations.Test)

Example 9 with OCommandContext

use of com.orientechnologies.orient.core.command.OCommandContext in project orientdb by orientechnologies.

the class OSQLTarget method extractTargets.

@SuppressWarnings("unchecked")
private boolean extractTargets() {
    parserSkipWhiteSpaces();
    if (parserIsEnded())
        throw new OQueryParsingException("No query target found", parserText, 0);
    final char c = parserGetCurrentChar();
    if (c == '$') {
        targetVariable = parserRequiredWord(false, "No valid target");
        targetVariable = targetVariable.substring(1);
    } else if (c == OStringSerializerHelper.LINK || Character.isDigit(c)) {
        // UNIQUE RID
        targetRecords = new ArrayList<OIdentifiable>();
        ((List<OIdentifiable>) targetRecords).add(new ORecordId(parserRequiredWord(true, "No valid RID")));
    } else if (c == OStringSerializerHelper.EMBEDDED_BEGIN) {
        // SUB QUERY
        final StringBuilder subText = new StringBuilder(256);
        parserSetCurrentPosition(OStringSerializerHelper.getEmbedded(parserText, parserGetCurrentPosition(), -1, subText) + 1);
        final OCommandSQL subCommand = new OCommandSQLResultset(subText.toString());
        final OCommandExecutorSQLResultsetDelegate executor = (OCommandExecutorSQLResultsetDelegate) OCommandManager.instance().getExecutor(subCommand);
        executor.setProgressListener(subCommand.getProgressListener());
        executor.parse(subCommand);
        OCommandContext childContext = executor.getContext();
        if (childContext != null) {
            childContext.setParent(context);
        }
        if (!(executor instanceof Iterable<?>))
            throw new OCommandSQLParsingException("Sub-query cannot be iterated because doesn't implement the Iterable interface: " + subCommand);
        targetQuery = subText.toString();
        targetRecords = executor;
    } else if (c == OStringSerializerHelper.LIST_BEGIN) {
        // COLLECTION OF RIDS
        final List<String> rids = new ArrayList<String>();
        parserSetCurrentPosition(OStringSerializerHelper.getCollection(parserText, parserGetCurrentPosition(), rids));
        targetRecords = new ArrayList<OIdentifiable>();
        for (String rid : rids) ((List<OIdentifiable>) targetRecords).add(new ORecordId(rid));
        parserMoveCurrentPosition(1);
    } else {
        while (!parserIsEnded() && (targetClasses == null && targetClusters == null && targetIndex == null && targetIndexValues == null && targetRecords == null)) {
            String originalSubjectName = parserRequiredWord(false, "Target not found");
            String subjectName = originalSubjectName.toUpperCase();
            final String alias;
            if (subjectName.equals("AS"))
                alias = parserRequiredWord(true, "Alias not found");
            else
                alias = subjectName;
            final String subjectToMatch = subjectName;
            if (subjectToMatch.startsWith(OCommandExecutorSQLAbstract.CLUSTER_PREFIX)) {
                // REGISTER AS CLUSTER
                if (targetClusters == null)
                    targetClusters = new HashMap<String, String>();
                final String clusterNames = subjectName.substring(OCommandExecutorSQLAbstract.CLUSTER_PREFIX.length());
                if (clusterNames.startsWith("[") && clusterNames.endsWith("]")) {
                    final Collection<String> clusters = new HashSet<String>(3);
                    OStringSerializerHelper.getCollection(clusterNames, 0, clusters);
                    for (String cl : clusters) {
                        targetClusters.put(cl, cl);
                    }
                } else
                    targetClusters.put(clusterNames, alias);
            } else if (subjectToMatch.startsWith(OCommandExecutorSQLAbstract.INDEX_PREFIX)) {
                // REGISTER AS INDEX
                targetIndex = subjectName.substring(OCommandExecutorSQLAbstract.INDEX_PREFIX.length());
            } else if (subjectToMatch.startsWith(OCommandExecutorSQLAbstract.METADATA_PREFIX)) {
                // METADATA
                final String metadataTarget = subjectName.substring(OCommandExecutorSQLAbstract.METADATA_PREFIX.length());
                targetRecords = new ArrayList<OIdentifiable>();
                if (metadataTarget.equals(OCommandExecutorSQLAbstract.METADATA_SCHEMA)) {
                    ((ArrayList<OIdentifiable>) targetRecords).add(new ORecordId(ODatabaseRecordThreadLocal.INSTANCE.get().getStorage().getConfiguration().schemaRecordId));
                } else if (metadataTarget.equals(OCommandExecutorSQLAbstract.METADATA_INDEXMGR)) {
                    ((ArrayList<OIdentifiable>) targetRecords).add(new ORecordId(ODatabaseRecordThreadLocal.INSTANCE.get().getStorage().getConfiguration().indexMgrRecordId));
                } else
                    throw new OQueryParsingException("Metadata element not supported: " + metadataTarget);
            } else if (subjectToMatch.startsWith(OCommandExecutorSQLAbstract.DICTIONARY_PREFIX)) {
                // DICTIONARY
                final String key = originalSubjectName.substring(OCommandExecutorSQLAbstract.DICTIONARY_PREFIX.length());
                targetRecords = new ArrayList<OIdentifiable>();
                final OIdentifiable value = ODatabaseRecordThreadLocal.INSTANCE.get().getDictionary().get(key);
                if (value != null)
                    ((List<OIdentifiable>) targetRecords).add(value);
            } else if (subjectToMatch.startsWith(OCommandExecutorSQLAbstract.INDEX_VALUES_PREFIX)) {
                targetIndexValues = subjectName.substring(OCommandExecutorSQLAbstract.INDEX_VALUES_PREFIX.length());
                targetIndexValuesAsc = true;
            } else if (subjectToMatch.startsWith(OCommandExecutorSQLAbstract.INDEX_VALUES_ASC_PREFIX)) {
                targetIndexValues = subjectName.substring(OCommandExecutorSQLAbstract.INDEX_VALUES_ASC_PREFIX.length());
                targetIndexValuesAsc = true;
            } else if (subjectToMatch.startsWith(OCommandExecutorSQLAbstract.INDEX_VALUES_DESC_PREFIX)) {
                targetIndexValues = subjectName.substring(OCommandExecutorSQLAbstract.INDEX_VALUES_DESC_PREFIX.length());
                targetIndexValuesAsc = false;
            } else {
                if (subjectToMatch.startsWith(OCommandExecutorSQLAbstract.CLASS_PREFIX))
                    // REGISTER AS CLASS
                    subjectName = subjectName.substring(OCommandExecutorSQLAbstract.CLASS_PREFIX.length());
                // REGISTER AS CLASS
                if (targetClasses == null)
                    targetClasses = new HashMap<String, String>();
                final OClass cls = ODatabaseRecordThreadLocal.INSTANCE.get().getMetadata().getSchema().getClass(subjectName);
                if (cls == null)
                    throw new OCommandExecutionException("Class '" + subjectName + "' was not found in database '" + ODatabaseRecordThreadLocal.INSTANCE.get().getName() + "'");
                targetClasses.put(cls.getName(), alias);
            }
        }
    }
    return !parserIsEnded();
}
Also used : OCommandContext(com.orientechnologies.orient.core.command.OCommandContext) OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) ORecordId(com.orientechnologies.orient.core.id.ORecordId) OClass(com.orientechnologies.orient.core.metadata.schema.OClass) OQueryParsingException(com.orientechnologies.orient.core.exception.OQueryParsingException) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException)

Aggregations

OCommandContext (com.orientechnologies.orient.core.command.OCommandContext)9 ODocument (com.orientechnologies.orient.core.record.impl.ODocument)4 OIdentifiable (com.orientechnologies.orient.core.db.record.OIdentifiable)3 Test (org.testng.annotations.Test)3 OBasicCommandContext (com.orientechnologies.orient.core.command.OBasicCommandContext)2 OCommandExecutionException (com.orientechnologies.orient.core.exception.OCommandExecutionException)2 OQueryParsingException (com.orientechnologies.orient.core.exception.OQueryParsingException)2 IOException (java.io.IOException)2 OException (com.orientechnologies.common.exception.OException)1 OLuceneCompositeKey (com.orientechnologies.lucene.collections.OLuceneCompositeKey)1 OCommandPredicate (com.orientechnologies.orient.core.command.OCommandPredicate)1 OTraverse (com.orientechnologies.orient.core.command.traverse.OTraverse)1 ODatabaseDocumentInternal (com.orientechnologies.orient.core.db.ODatabaseDocumentInternal)1 OConfigurationException (com.orientechnologies.orient.core.exception.OConfigurationException)1 ORecordId (com.orientechnologies.orient.core.id.ORecordId)1 OIndexEngineException (com.orientechnologies.orient.core.index.OIndexEngineException)1 OClass (com.orientechnologies.orient.core.metadata.schema.OClass)1 ORecord (com.orientechnologies.orient.core.record.ORecord)1 OSQLPredicate (com.orientechnologies.orient.core.sql.filter.OSQLPredicate)1 OSQLFunctionAbstract (com.orientechnologies.orient.core.sql.functions.OSQLFunctionAbstract)1