public Object execute(
      ODistributedRequestId requestId,
      final OServer iServer,
      ODistributedServerManager iManager,
      final ODatabaseDocumentInternal database)
      throws Exception {
    ODistributedServerLog.debug(
        this,
        iManager.getLocalNodeName(),
        getNodeSource(),
        DIRECTION.IN,
        "execute command=%s db=%s",
        text.toString(),
        database.getName());

    final OCommandRequest cmd = database.command(new OCommandScript(text));

    final Object res;
    if (params != null)
      // EXECUTE WITH PARAMETERS
      res = cmd.execute(params);
    else res = cmd.execute();

    return res;
  }
Beispiel #2
0
  public void log(
      final Object iRequester,
      final Level iLevel,
      String iMessage,
      final Throwable iException,
      final Object... iAdditionalArgs) {
    if (iMessage != null) {
      try {
        final ODatabaseDocumentInternal db =
            ODatabaseRecordThreadLocal.INSTANCE != null
                ? ODatabaseRecordThreadLocal.INSTANCE.getIfDefined()
                : null;
        if (db != null
            && db.getStorage() != null
            && db.getStorage() instanceof OAbstractPaginatedStorage) {
          final String dbName = db.getStorage().getName();
          if (dbName != null) iMessage = "{db=" + dbName + "} " + iMessage;
        }
      } catch (Throwable e) {
      }

      final String requesterName;
      if (iRequester != null) {
        requesterName = iRequester.getClass().getName();
      } else {
        requesterName = DEFAULT_LOG;
      }

      Logger log = loggersCache.get(requesterName);
      if (log == null) {
        log = Logger.getLogger(requesterName);

        if (log != null) {
          Logger oldLogger = loggersCache.putIfAbsent(requesterName, log);

          if (oldLogger != null) log = oldLogger;
        }
      }

      if (log == null) {
        // USE SYSERR
        try {
          System.err.println(String.format(iMessage, iAdditionalArgs));
        } catch (Exception e) {
          OLogManager.instance().warn(this, "Error on formatting message", e);
        }
      } else if (log.isLoggable(iLevel)) {
        // USE THE LOG
        try {
          final String msg = String.format(iMessage, iAdditionalArgs);
          if (iException != null) log.log(iLevel, msg, iException);
          else log.log(iLevel, msg);
        } catch (Exception e) {
          System.err.print(
              String.format(
                  "Error on formatting message '%s'. Exception: %s", iMessage, e.toString()));
        }
      }
    }
  }
  protected boolean pushResult(final Object rec) {
    if (rec instanceof ORecord) {
      final ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.INSTANCE.getIfDefined();
      if (db != null) db.getLocalCache().updateRecord((ORecord) rec);
    }

    return request.getResultListener().result(rec);
  }
Beispiel #4
0
  private void deleteDefaultCluster(final OClass clazz) {
    final ODatabaseDocumentInternal database = getDatabase();
    final int clusterId = clazz.getDefaultClusterId();
    final OCluster cluster = database.getStorage().getClusterById(clusterId);

    if (cluster.getName().equalsIgnoreCase(clazz.getName()))
      database.getStorage().dropCluster(clusterId, true);

    // FREE THE RECORD CACHE
    getDatabase().getLocalCache().freeCluster(clusterId);
  }
Beispiel #5
0
 public void create() {
   rwSpinLock.acquireWriteLock();
   try {
     final ODatabaseDocumentInternal db = getDatabase();
     super.save(OMetadataDefault.CLUSTER_INTERNAL_NAME);
     db.getStorage().getConfiguration().schemaRecordId = document.getIdentity().toString();
     db.getStorage().getConfiguration().update();
     snapshot = new OImmutableSchema(this);
   } finally {
     rwSpinLock.releaseWriteLock();
   }
 }
Beispiel #6
0
  /*
   * (non-Javadoc)
   *
   * @see com.orientechnologies.orient.core.metadata.schema.OSchema#dropClass(java.lang.String)
   */
  public void dropClass(final String className) {
    final ODatabaseDocumentInternal db = getDatabase();
    final OStorage storage = db.getStorage();
    final StringBuilder cmd;

    acquireSchemaWriteLock();
    try {
      if (getDatabase().getTransaction().isActive())
        throw new IllegalStateException("Cannot drop a class inside a transaction");

      if (className == null) throw new IllegalArgumentException("Class name is null");

      getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_DELETE);

      final String key = className.toLowerCase();

      OClass cls = classes.get(key);

      if (cls == null)
        throw new OSchemaException("Class '" + className + "' was not found in current database");

      if (!cls.getSubclasses().isEmpty())
        throw new OSchemaException(
            "Class '"
                + className
                + "' cannot be dropped because it has sub classes. Remove the dependencies before trying to drop it again");

      cmd = new StringBuilder("drop class ");
      cmd.append(className);
      cmd.append(" unsafe");

      if (isDistributedCommand()) {
        final OAutoshardedStorage autoshardedStorage = (OAutoshardedStorage) storage;
        OCommandSQL commandSQL = new OCommandSQL(cmd.toString());
        commandSQL.addExcludedNode(autoshardedStorage.getNodeId());
        db.command(commandSQL).execute();

        dropClassInternal(className);
      } else if (storage instanceof OStorageProxy) {
        final OCommandSQL commandSQL = new OCommandSQL(cmd.toString());
        db.command(commandSQL).execute();
        reload();
      } else dropClassInternal(className);

      // FREE THE RECORD CACHE
      getDatabase().getLocalCache().freeCluster(cls.getDefaultClusterId());

    } finally {
      releaseSchemaWriteLock();
    }
  }
Beispiel #7
0
  /** Delegates to the OQueryExecutor the query execution. */
  @SuppressWarnings("unchecked")
  public List<T> run(final Object... iArgs) {
    final ODatabaseDocumentInternal database = ODatabaseRecordThreadLocal.INSTANCE.get();
    if (database == null) throw new OQueryParsingException("No database configured");

    ((OMetadataInternal) database.getMetadata()).makeThreadLocalSchemaSnapshot();
    try {
      setParameters(iArgs);
      return (List<T>) database.getStorage().command(this);

    } finally {
      ((OMetadataInternal) database.getMetadata()).clearThreadLocalSchemaSnapshot();
    }
  }
  protected Iterator<? extends OIdentifiable> searchInClasses(
      final OClass iCls, final boolean iPolymorphic, final boolean iAscendentOrder) {

    final ODatabaseDocumentInternal database = getDatabase();
    database.checkSecurity(
        ORule.ResourceGeneric.CLASS, ORole.PERMISSION_READ, iCls.getName().toLowerCase());

    final ORID[] range = getRange();
    if (iAscendentOrder)
      return new ORecordIteratorClass<ORecord>(
              database, database, iCls.getName(), iPolymorphic, isUseCache(), false)
          .setRange(range[0], range[1]);
    else
      return new ORecordIteratorClassDescendentOrder<ORecord>(
              database, database, iCls.getName(), iPolymorphic)
          .setRange(range[0], range[1]);
  }
Beispiel #9
0
 @Override
 public OUser getUser(ODatabaseDocumentInternal db) {
   if (this.rid != null) {
     ODocument result = db.load(new ORecordId(this.rid), "roles:1");
     if (result != null && result.getClassName().equals(OUser.CLASS_NAME)) {
       return new OUser(result);
     }
   }
   return null;
 }
  protected void searchInClusters() {
    final ODatabaseDocumentInternal database = getDatabase();

    final Set<Integer> clusterIds = new HashSet<Integer>();
    for (String clusterName : parsedTarget.getTargetClusters().keySet()) {
      if (clusterName == null || clusterName.length() == 0)
        throw new OCommandExecutionException("No cluster or schema class selected in query");

      database.checkSecurity(
          ORule.ResourceGeneric.CLUSTER, ORole.PERMISSION_READ, clusterName.toLowerCase());

      if (Character.isDigit(clusterName.charAt(0))) {
        // GET THE CLUSTER NUMBER
        for (int clusterId : OStringSerializerHelper.splitIntArray(clusterName)) {
          if (clusterId == -1)
            throw new OCommandExecutionException("Cluster '" + clusterName + "' not found");

          clusterIds.add(clusterId);
        }
      } else {
        // GET THE CLUSTER NUMBER BY THE CLASS NAME
        final int clusterId = database.getClusterIdByName(clusterName.toLowerCase());
        if (clusterId == -1)
          throw new OCommandExecutionException("Cluster '" + clusterName + "' not found");

        clusterIds.add(clusterId);
      }
    }

    // CREATE CLUSTER AS ARRAY OF INT
    final int[] clIds = new int[clusterIds.size()];
    int i = 0;
    for (int c : clusterIds) clIds[i++] = c;

    final ORID[] range = getRange();

    target =
        new ORecordIteratorClusters<ORecord>(database, database, clIds)
            .setRange(range[0], range[1]);
  }
  /**
   * returns an already parsed SQL executor, taking it from the cache if it exists or creating a new
   * one (parsing and then putting it into the cache) if it doesn't
   *
   * @param statement the SQL statement
   * @param db the current DB instance. If null, cache is ignored and a new executor is created
   *     through statement parsing
   * @return a statement executor from the cache
   */
  public static OStatement get(String statement, ODatabaseDocumentInternal db) {
    if (db == null) {
      return parse(statement);
    }

    OStatementCache resource =
        db.getStorage()
            .getResource(
                OStatementCache.class.getSimpleName(),
                new Callable<OStatementCache>() {
                  @Override
                  public OStatementCache call() throws Exception {
                    return new OStatementCache(
                        OGlobalConfiguration.STATEMENT_CACHE_SIZE.getValueAsInteger());
                  }
                });
    return resource.get(statement);
  }
Beispiel #12
0
  private int[] createClusters(String className) {
    className = className.toLowerCase();

    final ODatabaseDocumentInternal database = getDatabase();
    final OStorage storage = database.getStorage();

    int[] clusterIds; // CREATE A NEW CLUSTER(S)
    final int minimumClusters = storage.getConfiguration().getMinimumClusters();

    clusterIds = new int[minimumClusters];
    if (minimumClusters <= 1) {
      clusterIds[0] = database.getClusterIdByName(className);
      if (clusterIds[0] == -1) clusterIds[0] = database.addCluster(className);
    } else
      for (int i = 0; i < minimumClusters; ++i) {
        clusterIds[i] = database.getClusterIdByName(className + "_" + i);
        if (clusterIds[i] == -1) clusterIds[i] = database.addCluster(className + "_" + i);
      }
    return clusterIds;
  }
Beispiel #13
0
  private OClass doCreateClass(
      final String className, final int[] clusterIds, int retry, OClass... superClasses)
      throws ClusterIdsAreEmptyException {
    OClass result;

    final ODatabaseDocumentInternal db = getDatabase();
    final OStorage storage = db.getStorage();
    StringBuilder cmd = null;

    getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_CREATE);
    acquireSchemaWriteLock();
    try {

      final String key = className.toLowerCase();
      if (classes.containsKey(key) && retry == 0)
        throw new OSchemaException("Class " + className + " already exists in current database");

      if (!isDistributedCommand()) checkClustersAreAbsent(clusterIds);

      cmd = new StringBuilder("create class ");
      // if (getDatabase().getStorage().getConfiguration().isStrictSql())
      // cmd.append('`');
      cmd.append(className);
      // if (getDatabase().getStorage().getConfiguration().isStrictSql())
      // cmd.append('`');

      List<OClass> superClassesList = new ArrayList<OClass>();
      if (superClasses != null && superClasses.length > 0) {
        boolean first = true;
        for (OClass superClass : superClasses) {
          // Filtering for null
          if (superClass != null) {
            if (first) cmd.append(" extends ");
            else cmd.append(", ");
            cmd.append(superClass.getName());
            first = false;
            superClassesList.add(superClass);
          }
        }
      }

      if (clusterIds != null) {
        if (clusterIds.length == 1 && clusterIds[0] == -1) cmd.append(" abstract");
        else {
          cmd.append(" cluster ");
          for (int i = 0; i < clusterIds.length; ++i) {
            if (i > 0) cmd.append(',');
            else cmd.append(' ');

            cmd.append(clusterIds[i]);
          }
        }
      }

      if (isDistributedCommand()) {
        createClassInternal(className, clusterIds, superClassesList);

        final OAutoshardedStorage autoshardedStorage = (OAutoshardedStorage) storage;
        OCommandSQL commandSQL = new OCommandSQL(cmd.toString());
        commandSQL.addExcludedNode(autoshardedStorage.getNodeId());

        final Object res = db.command(commandSQL).execute();

      } else if (storage instanceof OStorageProxy) {
        db.command(new OCommandSQL(cmd.toString())).execute();
        reload();
      } else createClassInternal(className, clusterIds, superClassesList);

      result = classes.get(className.toLowerCase());

      // WAKE UP DB LIFECYCLE LISTENER
      for (Iterator<ODatabaseLifecycleListener> it = Orient.instance().getDbLifecycleListeners();
          it.hasNext(); ) it.next().onCreateClass(getDatabase(), result);

    } finally {
      releaseSchemaWriteLock();
    }

    return result;
  }
Beispiel #14
0
  private OClass createClassInternal(
      final String className, final int[] clusterIdsToAdd, final List<OClass> superClasses)
      throws ClusterIdsAreEmptyException {
    acquireSchemaWriteLock();
    try {
      if (className == null || className.length() == 0)
        throw new OSchemaException("Found class name null or empty");

      if (Character.isDigit(className.charAt(0)))
        throw new OSchemaException("Found invalid class name. Cannot start with numbers");

      final Character wrongCharacter = checkClassNameIfValid(className);
      if (wrongCharacter != null)
        throw new OSchemaException(
            "Found invalid class name. Character '"
                + wrongCharacter
                + "' cannot be used in class name.");

      final ODatabaseDocumentInternal database = getDatabase();
      final OStorage storage = database.getStorage();
      checkEmbedded(storage);

      checkClustersAreAbsent(clusterIdsToAdd);

      final int[] clusterIds;
      if (clusterIdsToAdd == null || clusterIdsToAdd.length == 0) {
        throw new ClusterIdsAreEmptyException();

      } else clusterIds = clusterIdsToAdd;

      database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_CREATE);

      final String key = className.toLowerCase();

      if (classes.containsKey(key))
        throw new OSchemaException("Class " + className + " already exists in current database");

      OClassImpl cls = new OClassImpl(this, className, clusterIds);

      classes.put(key, cls);

      if (superClasses != null && superClasses.size() > 0) {
        cls.setSuperClassesInternal(superClasses);
        for (OClass superClass : superClasses) {
          // UPDATE INDEXES
          final int[] clustersToIndex = superClass.getPolymorphicClusterIds();
          final String[] clusterNames = new String[clustersToIndex.length];
          for (int i = 0; i < clustersToIndex.length; i++)
            clusterNames[i] = database.getClusterNameById(clustersToIndex[i]);

          for (OIndex<?> index : superClass.getIndexes())
            for (String clusterName : clusterNames)
              if (clusterName != null)
                database
                    .getMetadata()
                    .getIndexManager()
                    .addClusterToIndex(clusterName, index.getName());
        }
      }

      addClusterClassMap(cls);

      return cls;
    } finally {
      releaseSchemaWriteLock();
    }
  }