Search in sources :

Example 1 with OCluster

use of com.orientechnologies.orient.core.storage.OCluster in project orientdb by orientechnologies.

the class OCommandExecutorSQLInsert method parse.

@SuppressWarnings("unchecked")
public OCommandExecutorSQLInsert parse(final OCommandRequest iRequest) {
    final OCommandRequestText textRequest = (OCommandRequestText) iRequest;
    String queryText = textRequest.getText();
    String originalQuery = queryText;
    try {
        // System.out.println("NEW PARSER FROM: " + queryText);
        queryText = preParse(queryText, iRequest);
        // System.out.println("NEW PARSER   TO: " + queryText);
        textRequest.setText(queryText);
        final ODatabaseDocument database = getDatabase();
        init((OCommandRequestText) iRequest);
        className = null;
        newRecords = null;
        content = null;
        if (parserTextUpperCase.endsWith(KEYWORD_UNSAFE)) {
            unsafe = true;
            parserText = parserText.substring(0, parserText.length() - KEYWORD_UNSAFE.length() - 1);
            parserTextUpperCase = parserTextUpperCase.substring(0, parserTextUpperCase.length() - KEYWORD_UNSAFE.length() - 1);
        }
        parserRequiredKeyword("INSERT");
        parserRequiredKeyword("INTO");
        String subjectName = parserRequiredWord(true, "Invalid subject name. Expected cluster, class or index");
        if (subjectName.startsWith(OCommandExecutorSQLAbstract.CLUSTER_PREFIX)) {
            // CLUSTER
            clusterName = subjectName.substring(OCommandExecutorSQLAbstract.CLUSTER_PREFIX.length());
            try {
                int clusterId = Integer.parseInt(clusterName);
                clusterName = database.getClusterNameById(clusterId);
            } catch (Exception e) {
            //not an integer
            }
        } else if (subjectName.startsWith(OCommandExecutorSQLAbstract.INDEX_PREFIX))
            // INDEX
            indexName = subjectName.substring(OCommandExecutorSQLAbstract.INDEX_PREFIX.length());
        else {
            // CLASS
            if (subjectName.startsWith(OCommandExecutorSQLAbstract.CLASS_PREFIX))
                subjectName = subjectName.substring(OCommandExecutorSQLAbstract.CLASS_PREFIX.length());
            final OClass cls = ((OMetadataInternal) database.getMetadata()).getImmutableSchemaSnapshot().getClass(subjectName);
            if (cls == null)
                throwParsingException("Class " + subjectName + " not found in database");
            if (!unsafe && cls.isSubClassOf("E"))
                // FOUND EDGE
                throw new OCommandExecutionException("'INSERT' command cannot create Edges. Use 'CREATE EDGE' command instead, or apply the 'UNSAFE' keyword to force it");
            className = cls.getName();
            clazz = database.getMetadata().getSchema().getClass(className);
            if (clazz == null)
                throw new OQueryParsingException("Class '" + className + "' was not found");
        }
        if (clusterName != null && className == null) {
            ODatabaseDocumentInternal db = getDatabase();
            OCluster cluster = db.getStorage().getClusterByName(clusterName);
            if (cluster != null) {
                clazz = db.getMetadata().getSchema().getClassByClusterId(cluster.getId());
                if (clazz != null) {
                    className = clazz.getName();
                }
            }
        }
        parserSkipWhiteSpaces();
        if (parserIsEnded())
            throwSyntaxErrorException("Set of fields is missed. Example: (name, surname) or SET name = 'Bill'");
        final String temp = parseOptionalWord(true);
        if (parserGetLastWord().equalsIgnoreCase("cluster")) {
            clusterName = parserRequiredWord(false);
            parserSkipWhiteSpaces();
            if (parserIsEnded())
                throwSyntaxErrorException("Set of fields is missed. Example: (name, surname) or SET name = 'Bill'");
        } else
            parserGoBack();
        newRecords = new ArrayList<Map<String, Object>>();
        Boolean sourceClauseProcessed = false;
        if (parserGetCurrentChar() == '(') {
            parseValues();
            parserNextWord(true, " \r\n");
            sourceClauseProcessed = true;
        } else {
            parserNextWord(true, " ,\r\n");
            if (parserGetLastWord().equals(KEYWORD_CONTENT)) {
                newRecords = null;
                parseContent();
                sourceClauseProcessed = true;
            } else if (parserGetLastWord().equals(KEYWORD_SET)) {
                final List<OPair<String, Object>> fields = new ArrayList<OPair<String, Object>>();
                parseSetFields(clazz, fields);
                newRecords.add(OPair.convertToMap(fields));
                sourceClauseProcessed = true;
            }
        }
        if (sourceClauseProcessed)
            parserNextWord(true, " \r\n");
        // it has to be processed before KEYWORD_FROM in order to not be taken as part of SELECT
        if (parserGetLastWord().equals(KEYWORD_RETURN)) {
            parseReturn(!sourceClauseProcessed);
            parserNextWord(true, " \r\n");
        }
        if (!sourceClauseProcessed) {
            if (parserGetLastWord().equals(KEYWORD_FROM)) {
                newRecords = null;
                subQuery = new OSQLAsynchQuery<OIdentifiable>(parserText.substring(parserGetCurrentPosition()), this);
            }
        }
    } finally {
        textRequest.setText(originalQuery);
    }
    return this;
}
Also used : OCommandRequestText(com.orientechnologies.orient.core.command.OCommandRequestText) OMetadataInternal(com.orientechnologies.orient.core.metadata.OMetadataInternal) OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) OQueryParsingException(com.orientechnologies.orient.core.exception.OQueryParsingException) ODatabaseDocumentInternal(com.orientechnologies.orient.core.db.ODatabaseDocumentInternal) ODatabaseDocument(com.orientechnologies.orient.core.db.document.ODatabaseDocument) OPair(com.orientechnologies.common.util.OPair) OClass(com.orientechnologies.orient.core.metadata.schema.OClass) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) OQueryParsingException(com.orientechnologies.orient.core.exception.OQueryParsingException) OCluster(com.orientechnologies.orient.core.storage.OCluster)

Example 2 with OCluster

use of com.orientechnologies.orient.core.storage.OCluster in project orientdb by orientechnologies.

the class OCommandExecutorSQLSetAware method extractClassFromTarget.

protected OClass extractClassFromTarget(String iTarget) {
    // CLASS
    if (!iTarget.toUpperCase().startsWith(OCommandExecutorSQLAbstract.CLUSTER_PREFIX) && !iTarget.startsWith(OCommandExecutorSQLAbstract.INDEX_PREFIX)) {
        if (iTarget.toUpperCase().startsWith(OCommandExecutorSQLAbstract.CLASS_PREFIX))
            // REMOVE CLASS PREFIX
            iTarget = iTarget.substring(OCommandExecutorSQLAbstract.CLASS_PREFIX.length());
        if (iTarget.charAt(0) == ORID.PREFIX)
            return getDatabase().getMetadata().getSchema().getClassByClusterId(new ORecordId(iTarget).getClusterId());
        return getDatabase().getMetadata().getSchema().getClass(iTarget);
    }
    //CLUSTER
    if (iTarget.toUpperCase().startsWith(OCommandExecutorSQLAbstract.CLUSTER_PREFIX)) {
        String clusterName = iTarget.substring(OCommandExecutorSQLAbstract.CLUSTER_PREFIX.length()).trim();
        ODatabaseDocumentInternal db = getDatabase();
        if (clusterName.startsWith("[") && clusterName.endsWith("]")) {
            String[] clusterNames = clusterName.substring(1, clusterName.length() - 1).split(",");
            OClass candidateClass = null;
            for (String cName : clusterNames) {
                OCluster aCluster = db.getStorage().getClusterByName(cName.trim());
                if (aCluster == null) {
                    return null;
                }
                OClass aClass = db.getMetadata().getSchema().getClassByClusterId(aCluster.getId());
                if (aClass == null) {
                    return null;
                }
                if (candidateClass == null || candidateClass.equals(aClass) || candidateClass.isSubClassOf(aClass)) {
                    candidateClass = aClass;
                } else if (!candidateClass.isSuperClassOf(aClass)) {
                    return null;
                }
            }
            return candidateClass;
        } else {
            OCluster cluster = db.getStorage().getClusterByName(clusterName);
            if (cluster != null) {
                return db.getMetadata().getSchema().getClassByClusterId(cluster.getId());
            }
        }
    }
    return null;
}
Also used : OClass(com.orientechnologies.orient.core.metadata.schema.OClass) OCluster(com.orientechnologies.orient.core.storage.OCluster) ORecordId(com.orientechnologies.orient.core.id.ORecordId) ODatabaseDocumentInternal(com.orientechnologies.orient.core.db.ODatabaseDocumentInternal)

Example 3 with OCluster

use of com.orientechnologies.orient.core.storage.OCluster in project orientdb by orientechnologies.

the class OConsoleDatabaseApp method listClusters.

@ConsoleCommand(description = "Display all the configured clusters", aliases = { "clusters" }, onlineHelp = "Console-Command-List-Clusters")
public void listClusters(@ConsoleParameter(name = "[options]", optional = true, description = "Additional options, example: -v=verbose") final String options) {
    final Map<String, String> commandOptions = parseCommandOptions(options);
    if (currentDatabaseName != null) {
        message("\n\nCLUSTERS (collections)");
        final List<ODocument> resultSet = new ArrayList<ODocument>();
        int clusterId;
        long totalElements = 0;
        long totalSpaceUsed = 0;
        long totalTombstones = 0;
        long count;
        final List<String> clusters = new ArrayList<String>(currentDatabase.getClusterNames());
        Collections.sort(clusters);
        ODocument dClusters = null;
        final ODocument dCfg = getDistributedConfiguration();
        if (dCfg != null) {
            final ODocument dDatabaseCfg = dCfg.field("database");
            if (dDatabaseCfg != null) {
                dClusters = dDatabaseCfg.field("clusters");
            }
        }
        final boolean isRemote = currentDatabase.getStorage().isRemote();
        for (String clusterName : clusters) {
            try {
                final ODocument row = new ODocument();
                resultSet.add(row);
                clusterId = currentDatabase.getClusterIdByName(clusterName);
                final OCluster cluster = currentDatabase.getStorage().getClusterById(clusterId);
                final String conflictStrategy = cluster.getRecordConflictStrategy() != null ? cluster.getRecordConflictStrategy().getName() : "";
                count = currentDatabase.countClusterElements(clusterName);
                totalElements += count;
                final long spaceUsed = !isRemote ? cluster.getRecordsSize() : 0;
                totalSpaceUsed += spaceUsed;
                final long tombstones = !isRemote ? cluster.getTombstonesCount() : 0;
                totalTombstones += tombstones;
                final OClass cls = currentDatabase.getMetadata().getSchema().getClassByClusterId(clusterId);
                final String className = cls != null ? cls.getName() : null;
                row.field("NAME", clusterName);
                row.field("ID", clusterId);
                row.field("CLASS", className);
                row.field("CONFLICT-STRATEGY", conflictStrategy);
                row.field("COUNT", count);
                if (!isRemote) {
                    row.field("SPACE-USED", OFileUtils.getSizeAsString(spaceUsed));
                    if (commandOptions.containsKey("-v")) {
                        row.field("TOMBSTONES", tombstones);
                    }
                }
                if (dClusters != null) {
                    ODocument dClusterCfg = dClusters.field(clusterName);
                    if (dClusterCfg == null)
                        dClusterCfg = dClusters.field("*");
                    if (dClusterCfg != null) {
                        final List<String> servers = new ArrayList<String>((Collection<? extends String>) dClusterCfg.field("servers"));
                        final boolean newNode = servers.remove("<NEW_NODE>");
                        if (!servers.isEmpty()) {
                            row.field("OWNER_SERVER", servers.get(0));
                            if (servers.size() > 1) {
                                servers.remove(0);
                                row.field("OTHER_SERVERS", servers);
                            }
                        }
                        row.field("AUTO_DEPLOY_NEW_NODE", newNode);
                    }
                }
            } catch (Exception e) {
                if (e instanceof OIOException)
                    break;
            }
        }
        final OTableFormatter formatter = new OTableFormatter(this);
        formatter.setColumnAlignment("ID", OTableFormatter.ALIGNMENT.RIGHT);
        formatter.setColumnAlignment("COUNT", OTableFormatter.ALIGNMENT.RIGHT);
        formatter.setColumnAlignment("OWNER_SERVER", OTableFormatter.ALIGNMENT.CENTER);
        formatter.setColumnAlignment("OTHER_SERVERS", OTableFormatter.ALIGNMENT.CENTER);
        formatter.setColumnAlignment("AUTO_DEPLOY_NEW_NODE", OTableFormatter.ALIGNMENT.CENTER);
        if (!isRemote) {
            formatter.setColumnAlignment("SPACE-USED", OTableFormatter.ALIGNMENT.RIGHT);
            if (commandOptions.containsKey("-v")) {
                formatter.setColumnAlignment("TOMBSTONES", OTableFormatter.ALIGNMENT.RIGHT);
            }
        }
        final ODocument footer = new ODocument();
        footer.field("NAME", "TOTAL");
        footer.field("COUNT", totalElements);
        if (!isRemote) {
            footer.field("SPACE-USED", OFileUtils.getSizeAsString(totalSpaceUsed));
            if (commandOptions.containsKey("-v")) {
                footer.field("TOMBSTONES", totalTombstones);
            }
        }
        formatter.setFooter(footer);
        formatter.writeRecords(resultSet, -1);
        message("\n");
    } else
        message("\nNo database selected yet.");
}
Also used : OSystemException(com.orientechnologies.common.exception.OSystemException) OConfigurationException(com.orientechnologies.orient.core.exception.OConfigurationException) ORetryQueryException(com.orientechnologies.orient.core.exception.ORetryQueryException) OIOException(com.orientechnologies.common.io.OIOException) ODatabaseException(com.orientechnologies.orient.core.exception.ODatabaseException) OIOException(com.orientechnologies.common.io.OIOException) OClass(com.orientechnologies.orient.core.metadata.schema.OClass) OCluster(com.orientechnologies.orient.core.storage.OCluster) ODocument(com.orientechnologies.orient.core.record.impl.ODocument) ConsoleCommand(com.orientechnologies.common.console.annotation.ConsoleCommand)

Example 4 with OCluster

use of com.orientechnologies.orient.core.storage.OCluster in project orientdb by orientechnologies.

the class OCommandExecutorSQLAlterCluster method getClusters.

protected List<OCluster> getClusters() {
    final ODatabaseDocumentInternal database = getDatabase();
    final List<OCluster> result = new ArrayList<OCluster>();
    if (clusterName.endsWith("*")) {
        final String toMatch = clusterName.substring(0, clusterName.length() - 1).toLowerCase();
        for (String cl : database.getStorage().getClusterNames()) {
            if (cl.startsWith(toMatch))
                result.add(database.getStorage().getClusterByName(cl));
        }
    } else {
        if (clusterId > -1) {
            result.add(database.getStorage().getClusterById(clusterId));
        } else {
            result.add(database.getStorage().getClusterById(database.getStorage().getClusterIdByName(clusterName)));
        }
    }
    return result;
}
Also used : ArrayList(java.util.ArrayList) OCluster(com.orientechnologies.orient.core.storage.OCluster) ODatabaseDocumentInternal(com.orientechnologies.orient.core.db.ODatabaseDocumentInternal)

Example 5 with OCluster

use of com.orientechnologies.orient.core.storage.OCluster in project orientdb by orientechnologies.

the class OCommandExecutorSQLTruncateCluster method execute.

/**
   * Execute the command.
   */
public Object execute(final Map<Object, Object> iArgs) {
    if (clusterName == null)
        throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");
    final ODatabaseDocumentInternal database = getDatabase();
    final int clusterId = database.getClusterIdByName(clusterName);
    if (clusterId < 0) {
        throw new ODatabaseException("Cluster with name " + clusterName + " does not exist");
    }
    final OSchema schema = database.getMetadata().getSchema();
    final OClass clazz = schema.getClassByClusterId(clusterId);
    if (clazz == null) {
        final OStorage storage = database.getStorage();
        final OCluster cluster = storage.getClusterById(clusterId);
        if (cluster == null) {
            throw new ODatabaseException("Cluster with name " + clusterName + " does not exist");
        }
        try {
            storage.checkForClusterPermissions(cluster.getName());
            cluster.truncate();
        } catch (IOException ioe) {
            throw OException.wrapException(new ODatabaseException("Error during truncation of cluster with name " + clusterName), ioe);
        }
    } else {
        clazz.truncateCluster(clusterName);
    }
    return true;
}
Also used : OSchema(com.orientechnologies.orient.core.metadata.schema.OSchema) OClass(com.orientechnologies.orient.core.metadata.schema.OClass) OStorage(com.orientechnologies.orient.core.storage.OStorage) OCommandExecutionException(com.orientechnologies.orient.core.exception.OCommandExecutionException) ODatabaseException(com.orientechnologies.orient.core.exception.ODatabaseException) OCluster(com.orientechnologies.orient.core.storage.OCluster) IOException(java.io.IOException) ODatabaseDocumentInternal(com.orientechnologies.orient.core.db.ODatabaseDocumentInternal)

Aggregations

OCluster (com.orientechnologies.orient.core.storage.OCluster)12 OClass (com.orientechnologies.orient.core.metadata.schema.OClass)9 ODatabaseDocumentInternal (com.orientechnologies.orient.core.db.ODatabaseDocumentInternal)5 OCommandExecutionException (com.orientechnologies.orient.core.exception.OCommandExecutionException)4 ODatabaseDocumentTx (com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx)3 ODatabaseException (com.orientechnologies.orient.core.exception.ODatabaseException)3 ODocument (com.orientechnologies.orient.core.record.impl.ODocument)3 IOException (java.io.IOException)3 OStorageEntryConfiguration (com.orientechnologies.orient.core.config.OStorageEntryConfiguration)2 OSecurityAccessException (com.orientechnologies.orient.core.exception.OSecurityAccessException)2 OMetadataInternal (com.orientechnologies.orient.core.metadata.OMetadataInternal)2 OJSONWriter (com.orientechnologies.orient.core.serialization.serializer.OJSONWriter)2 ORawBuffer (com.orientechnologies.orient.core.storage.ORawBuffer)2 OStorage (com.orientechnologies.orient.core.storage.OStorage)2 StringWriter (java.io.StringWriter)2 ArrayList (java.util.ArrayList)2 ConsoleCommand (com.orientechnologies.common.console.annotation.ConsoleCommand)1 OException (com.orientechnologies.common.exception.OException)1 OSystemException (com.orientechnologies.common.exception.OSystemException)1 OIOException (com.orientechnologies.common.io.OIOException)1