/** Execute the DROP CLASS. */
  public Object execute(final Map<Object, Object> iArgs) {
    if (className == null) {
      throw new OCommandExecutionException(
          "Cannot execute the command because it has not been parsed yet");
    }

    final ODatabaseDocument database = getDatabase();
    if (ifExists && !database.getMetadata().getSchema().existsClass(className)) {
      return true;
    }
    final OClass cls = database.getMetadata().getSchema().getClass(className);
    if (cls == null) {
      return null;
    }

    final long records = cls.count(true);

    if (records > 0 && !unsafe) {
      // NOT EMPTY, CHECK IF CLASS IS OF VERTEX OR EDGES
      if (cls.isSubClassOf("V")) {
        // FOUND VERTEX CLASS
        throw new OCommandExecutionException(
            "'DROP CLASS' command cannot drop class '"
                + className
                + "' because it contains Vertices. Use 'DELETE VERTEX' command first to avoid broken edges in a database, or apply the 'UNSAFE' keyword to force it");
      } else if (cls.isSubClassOf("E")) {
        // FOUND EDGE CLASS
        throw new OCommandExecutionException(
            "'DROP CLASS' command cannot drop class '"
                + className
                + "' because it contains Edges. Use 'DELETE EDGE' command first to avoid broken vertices in a database, or apply the 'UNSAFE' keyword to force it");
      }
    }

    database.getMetadata().getSchema().dropClass(className);

    if (records > 0 && unsafe) {
      // NOT EMPTY, CHECK IF CLASS IS OF VERTEX OR EDGES
      if (cls.isSubClassOf("V")) {
        // FOUND VERTICES
        if (unsafe)
          OLogManager.instance()
              .warn(
                  this,
                  "Dropped class '%s' containing %d vertices using UNSAFE mode. Database could contain broken edges",
                  className,
                  records);
      } else if (cls.isSubClassOf("E")) {
        // FOUND EDGES
        OLogManager.instance()
            .warn(
                this,
                "Dropped class '%s' containing %d edges using UNSAFE mode. Database could contain broken vertices",
                className,
                records);
      }
    }

    return true;
  }
  @Test
  public void queryProjectionOk() {
    database.open("admin", "admin");

    List<ODocument> result =
        database
            .command(
                new OSQLSynchQuery<ODocument>(
                    " select nick, followings, followers from Profile where nick is defined and followings is defined and followers is defined"))
            .execute();

    Assert.assertTrue(result.size() != 0);

    for (ODocument d : result) {
      String[] colNames = d.fieldNames();
      Assert.assertEquals(colNames.length, 3);
      Assert.assertEquals(colNames[0], "nick");
      Assert.assertEquals(colNames[1], "followings");
      Assert.assertEquals(colNames[2], "followers");

      Assert.assertNull(d.getClassName());
      Assert.assertEquals(d.getRecordType(), ODocument.RECORD_TYPE);
    }

    database.close();
  }
Exemplo n.º 3
0
  private void saveInternal() {
    final ODatabaseDocument db = getDatabase();

    if (db.getTransaction().isActive()) {
      reload(null, true);
      throw new OSchemaException(
          "Cannot change the schema while a transaction is active. Schema changes are not transactional");
    }

    setDirty();

    OScenarioThreadLocal.executeAsDistributed(
        new Callable<Object>() {
          @Override
          public Object call() {
            try {
              toStream();
              document.save(OMetadataDefault.CLUSTER_INTERNAL_NAME);
              if (fullCheckpointOnChange) getDatabase().getStorage().synch();
            } catch (OConcurrentModificationException e) {
              reload(null, true);
              throw e;
            }
            return null;
          }
        });

    snapshot = new OImmutableSchema(this);
  }
Exemplo n.º 4
0
  private void dropClassIndexes(final OClass cls) {
    final ODatabaseDocument database = getDatabase();
    final OIndexManager indexManager = database.getMetadata().getIndexManager();

    for (final OIndex<?> index : indexManager.getClassIndexes(cls.getName()))
      indexManager.dropIndex(index.getName());
  }
  @Override
  public boolean execute(final OHttpRequest iRequest, OHttpResponse iResponse) throws Exception {
    String[] urlParts =
        checkSyntax(
            iRequest.url,
            3,
            "Syntax error: cluster/<database>/<cluster-name>[/<limit>]<br>Limit is optional and is setted to 20 by default. Set expressely to 0 to have no limits.");

    iRequest.data.commandInfo = "Browse cluster";
    iRequest.data.commandDetail = urlParts[2];

    ODatabaseDocument db = null;

    try {
      db = getProfiledDatabaseInstance(iRequest);

      if (db.getClusterIdByName(urlParts[2]) > -1) {
        final int limit = urlParts.length > 3 ? Integer.parseInt(urlParts[3]) : 20;

        final List<OIdentifiable> response = new ArrayList<OIdentifiable>();
        for (ORecord rec : db.browseCluster(urlParts[2])) {
          if (limit > 0 && response.size() >= limit) break;

          response.add(rec);
        }

        iResponse.writeRecords(response);
      } else iResponse.send(OHttpUtils.STATUS_NOTFOUND_CODE, null, null, null, null);

    } finally {
      if (db != null) db.close();
    }
    return false;
  }
  @Override
  public Object execute(Map<Object, Object> iArgs) {
    final ODatabaseDocument database = getDatabase();
    if (database.hide(recordIdToHide)) return 1;

    return 0;
  }
Exemplo n.º 7
0
  @Test
  public void queryDate() {
    List<ODocument> result =
        database
            .command(new OSQLSynchQuery<ODocument>("select count(*) as tot from Account"))
            .execute();
    Assert.assertEquals(result.size(), 1);
    int tot = ((Number) result.get(0).field("tot")).intValue();

    int updated =
        ((Number)
                database.command(new OCommandSQL("update Account set created = date()")).execute())
            .intValue();
    Assert.assertEquals(updated, tot);

    String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
    SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);

    result =
        database
            .command(
                new OSQLSynchQuery<ODocument>(
                    "select from Account where created <= date('"
                        + dateFormat.format(new Date())
                        + "', '"
                        + pattern
                        + "')"))
            .execute();

    Assert.assertEquals(result.size(), tot);
    for (ODocument d : result) {
      Assert.assertNotNull(d.field("created"));
    }
  }
Exemplo n.º 8
0
  public void updateMultipleFields() {
    database.open("admin", "admin");

    List<OClusterPosition> positions = getValidPositions(3);

    OIdentifiable result =
        database
            .command(
                new OCommandSQL(
                    "  INSERT INTO Account SET id= 3232,name= 'my name',map= {\"key\":\"value\"},dir= '',user= #3:"
                        + positions.get(0)))
            .execute();
    Assert.assertNotNull(result);

    ODocument record = result.getRecord();

    Assert.assertEquals(record.field("id"), 3232);
    Assert.assertEquals(record.field("name"), "my name");
    Map<String, String> map = record.field("map");
    Assert.assertTrue(map.get("key").equals("value"));
    Assert.assertEquals(record.field("dir"), "");
    Assert.assertEquals(record.field("user", OType.LINK), new ORecordId(3, positions.get(0)));

    database.close();
  }
Exemplo n.º 9
0
 @Override
 protected void setValue(OClass entity, String critery, V value) {
   ODatabaseDocument db = OrientDbWebSession.get().getDatabase();
   db.commit();
   try {
     CustomAttributes custom;
     if (OClassPrototyper.CLUSTER_SELECTION.equals(critery)) {
       if (value != null) entity.setClusterSelection(value.toString());
     } else if ((CustomAttributes.ON_CREATE_FIELDS.getName().equals(critery))
         && (custom = CustomAttributes.fromString(critery)) != null) {
       custom.setValue(entity, value != null ? Joiner.on(",").join((List<String>) value) : null);
     } else if ((custom = CustomAttributes.fromString(critery)) != null) {
       custom.setValue(entity, value);
     } else if (OClassPrototyper.SUPER_CLASSES.equals(critery)) {
       if (value != null) entity.setSuperClasses((List<OClass>) value);
     } else {
       PropertyResolver.setValue(
           critery,
           entity,
           value,
           new PropertyResolverConverter(
               Application.get().getConverterLocator(), Session.get().getLocale()));
     }
   } finally {
     db.begin();
   }
 }
Exemplo n.º 10
0
 public void close() throws SQLException {
   status = ODatabase.STATUS.CLOSED;
   if (database != null) {
     database.activateOnCurrentThread();
     database.close();
     database = null;
   }
 }
Exemplo n.º 11
0
  @Test
  @SuppressWarnings("unchecked")
  public void insertList() {
    database.open("admin", "admin");

    ODocument doc =
        (ODocument)
            database
                .command(
                    new OCommandSQL(
                        "insert into cluster:default (equaledges, name, list) values ('yes', 'square', ['bottom', 'top','left','right'] )"))
                .execute();

    Assert.assertTrue(doc != null);

    doc = (ODocument) new ODocument(doc.getIdentity()).load();

    Assert.assertEquals(doc.field("equaledges"), "yes");
    Assert.assertEquals(doc.field("name"), "square");
    Assert.assertTrue(doc.field("list") instanceof List);

    List<Object> entries = ((List<Object>) doc.field("list"));
    Assert.assertEquals(entries.size(), 4);

    Assert.assertEquals(entries.get(0), "bottom");
    Assert.assertEquals(entries.get(1), "top");
    Assert.assertEquals(entries.get(2), "left");
    Assert.assertEquals(entries.get(3), "right");

    database.delete(doc);

    doc =
        (ODocument)
            database
                .command(
                    new OCommandSQL(
                        "insert into cluster:default SET equaledges = 'yes', name = 'square', list = ['bottom', 'top','left','right'] "))
                .execute();

    Assert.assertTrue(doc != null);

    doc = (ODocument) new ODocument(doc.getIdentity()).load();

    Assert.assertEquals(doc.field("equaledges"), "yes");
    Assert.assertEquals(doc.field("name"), "square");
    Assert.assertTrue(doc.field("list") instanceof List);

    entries = ((List<Object>) doc.field("list"));
    Assert.assertEquals(entries.size(), 4);

    Assert.assertEquals(entries.get(0), "bottom");
    Assert.assertEquals(entries.get(1), "top");
    Assert.assertEquals(entries.get(2), "left");
    Assert.assertEquals(entries.get(3), "right");

    database.close();
  }
  @Override
  public void init() {
    OProfiler.getInstance().startRecording();

    database = new ODatabaseDocumentTx(System.getProperty("url")).open("admin", "admin");
    record = database.newInstance();

    database.declareIntent(new OIntentMassiveInsert());
    database.begin(TXTYPE.NOTX);
  }
  @Override
  public void deinit() {
    final long endRecords = database.countClass("Account");
    System.out.println(
        "Total accounts: " + endRecords + ". Expected: " + (beginRecords + data.getCycles()));

    System.out.println(Orient.instance().getProfiler().dump());

    if (database != null) database.close();
    super.deinit();
  }
Exemplo n.º 14
0
  @Test
  public void createProperty() {
    database.open("admin", "admin");

    database.command(new OCommandSQL("create property account.timesheet string")).execute();

    Assert.assertEquals(
        database.getMetadata().getSchema().getClass("account").getProperty("timesheet").getType(),
        OType.STRING);

    database.close();
  }
Exemplo n.º 15
0
  @Test
  @SuppressWarnings("unchecked")
  public void insertMap() {
    database.open("admin", "admin");

    ODocument doc =
        (ODocument)
            database
                .command(
                    new OCommandSQL(
                        "insert into cluster:default (equaledges, name, properties) values ('no', 'circle', {'round':'eeee', 'blaaa':'zigzag'} )"))
                .execute();

    Assert.assertTrue(doc != null);

    doc = (ODocument) new ODocument(doc.getIdentity()).load();

    Assert.assertEquals(doc.field("equaledges"), "no");
    Assert.assertEquals(doc.field("name"), "circle");
    Assert.assertTrue(doc.field("properties") instanceof Map);

    Map<Object, Object> entries = ((Map<Object, Object>) doc.field("properties"));
    Assert.assertEquals(entries.size(), 2);

    Assert.assertEquals(entries.get("round"), "eeee");
    Assert.assertEquals(entries.get("blaaa"), "zigzag");

    database.delete(doc);

    doc =
        (ODocument)
            database
                .command(
                    new OCommandSQL(
                        "insert into cluster:default SET equaledges = 'no', name = 'circle', properties = {'round':'eeee', 'blaaa':'zigzag'} "))
                .execute();

    Assert.assertTrue(doc != null);

    doc = (ODocument) new ODocument(doc.getIdentity()).load();

    Assert.assertEquals(doc.field("equaledges"), "no");
    Assert.assertEquals(doc.field("name"), "circle");
    Assert.assertTrue(doc.field("properties") instanceof Map);

    entries = ((Map<Object, Object>) doc.field("properties"));
    Assert.assertEquals(entries.size(), 2);

    Assert.assertEquals(entries.get("round"), "eeee");
    Assert.assertEquals(entries.get("blaaa"), "zigzag");
    database.close();
  }
Exemplo n.º 16
0
  @Override
  public void load() {
    final ODatabaseDocument db = ODatabaseRecordThreadLocal.INSTANCE.get();

    if (db.getMetadata().getSchema().existsClass(OScheduledEvent.CLASS_NAME)) {
      final Iterable<ODocument> result = db.browseClass(OScheduledEvent.CLASS_NAME);
      for (ODocument d : result) {
        final OScheduledEvent event = new OScheduledEvent(d);

        if (events.putIfAbsent(event.getName(), event) == null) this.scheduleEvent(event);
      }
    }
  }
Exemplo n.º 17
0
  private List<OClusterPosition> getValidPositions(int clusterId) {
    final List<OClusterPosition> positions = new ArrayList<OClusterPosition>();

    final ORecordIteratorCluster<?> iteratorCluster =
        database.browseCluster(database.getClusterNameById(clusterId));

    for (int i = 0; i < 100; i++) {
      if (!iteratorCluster.hasNext()) break;
      ORecord<?> doc = iteratorCluster.next();
      positions.add(doc.getIdentity().getClusterPosition());
    }
    return positions;
  }
Exemplo n.º 18
0
 @Provides
 public ODatabaseDocument getDatabaseRecord() {
   ODatabaseDocument db =
       DefaultODatabaseThreadLocalFactory.castToODatabaseDocument(
           ODatabaseRecordThreadLocal.INSTANCE.get().getDatabaseOwner());
   if (db.isClosed()) {
     ODatabaseRecordThreadLocal.INSTANCE.remove();
     db =
         DefaultODatabaseThreadLocalFactory.castToODatabaseDocument(
             ODatabaseRecordThreadLocal.INSTANCE.get().getDatabaseOwner());
   }
   return db;
 }
  @Override
  public void init() {
    Orient.instance().getProfiler().startRecording();

    database = new ODatabaseDocumentTx(System.getProperty("url")).open("admin", "admin");
    record = database.newInstance();

    database.declareIntent(new OIntentMassiveInsert());
    database.begin(TXTYPE.NOTX);

    beginRecords = database.countClass("Account");
    System.out.println("Total accounts: " + beginRecords);
  }
Exemplo n.º 20
0
  @SuppressWarnings("unchecked")
  @Test
  public void queryUnionAllAsAggregationNotRemoveDuplicates() {
    List<ODocument> result =
        database.command(new OSQLSynchQuery<ODocument>("select from City")).execute();
    int count = result.size();

    result =
        database
            .command(new OSQLSynchQuery<ODocument>("select unionAll(name) as name from City"))
            .execute();
    Collection<Object> citiesFound = result.get(0).field("name");
    Assert.assertEquals(citiesFound.size(), count);
  }
  @Test(expectedExceptions = OCommandSQLParsingException.class)
  public void queryProjectionFlattenError() {
    database.open("admin", "admin");

    try {
      database
          .command(
              new OSQLSynchQuery<ODocument>(
                  "SELECT FLATTEN( out ), in FROM OGraphVertex WHERE out TRAVERSE(1,1) (@class = 'OGraphEdge')"))
          .execute();

    } finally {
      database.close();
    }
  }
Exemplo n.º 22
0
  @Test(dependsOnMethods = "createLinkedClassProperty")
  public void createLinkedTypeProperty() {
    database.open("admin", "admin");

    database.command(new OCommandSQL("create property account.tags embeddedlist string")).execute();

    Assert.assertEquals(
        database.getMetadata().getSchema().getClass("account").getProperty("tags").getType(),
        OType.EMBEDDEDLIST);
    Assert.assertEquals(
        database.getMetadata().getSchema().getClass("account").getProperty("tags").getLinkedType(),
        OType.STRING);

    database.close();
  }
Exemplo n.º 23
0
  @Test
  public void insertWithNoSpaces() {
    database.open("admin", "admin");

    ODocument doc =
        (ODocument)
            database
                .command(
                    new OCommandSQL(
                        "insert into cluster:default(id, title)values(10, 'NoSQL movement')"))
                .execute();

    Assert.assertTrue(doc != null);

    database.close();
  }
Exemplo n.º 24
0
  @Test
  public void queryComposedAggregates() {
    List<ODocument> result =
        database
            .command(
                new OSQLSynchQuery<ODocument>(
                    "select MIN(id) as min, max(id) as max, AVG(id) as average, count(id) as total from Account"))
            .execute();

    Assert.assertTrue(result.size() == 1);
    for (ODocument d : result) {
      Assert.assertNotNull(d.field("min"));
      Assert.assertNotNull(d.field("max"));
      Assert.assertNotNull(d.field("average"));
      Assert.assertNotNull(d.field("total"));

      Assert.assertTrue(
          ((Number) d.field("max")).longValue() > ((Number) d.field("average")).longValue());
      Assert.assertTrue(
          ((Number) d.field("average")).longValue() >= ((Number) d.field("min")).longValue());
      Assert.assertTrue(
          ((Number) d.field("total")).longValue() >= ((Number) d.field("max")).longValue(),
          "Total " + d.field("total") + " max " + d.field("max"));
    }
  }
Exemplo n.º 25
0
 private void checkUpdatedDoc(
     ODatabaseDocument database, String expectedName, String expectedCity, String expectedGender) {
   List<ODocument> result = database.query(new OSQLSynchQuery<Object>("select * from person"));
   ODocument oDoc = result.get(0);
   Assert.assertEquals(expectedName, oDoc.field("name"));
   Assert.assertEquals(expectedCity, oDoc.field("city"));
   Assert.assertEquals(expectedGender, oDoc.field("gender"));
 }
Exemplo n.º 26
0
Arquivo: DB.java Projeto: o-nix/Kafra
  public static ODatabaseDocument getDb() {
    ODatabaseDocument db = DatabaseObjects.INSTANCE.get();
    boolean useServer = Application.getConfig().getBooleanProperty("db.server", false);

    if (db == null) {
      db = new ODatabaseDocumentTx(useServer ? "remote:localhost/main" : "local:data");

      if (!useServer && !db.exists()) db.create();

      if (db.isClosed()) db.open("admin", "admin");
    }

    ODatabaseRecordThreadLocal.INSTANCE.get().setDatabaseOwner(db);
    DatabaseObjects.INSTANCE.set(db);

    return db;
  }
Exemplo n.º 27
0
  @Test
  public void insertCluster() {
    database.open("admin", "admin");

    ODocument doc =
        (ODocument)
            database
                .command(
                    new OCommandSQL(
                        "insert into Account cluster default (id, title) values (10, 'NoSQL movement')"))
                .execute();

    Assert.assertTrue(doc != null);
    Assert.assertEquals(doc.getIdentity().getClusterId(), database.getDefaultClusterId());
    Assert.assertEquals(doc.getClassName(), "Account");

    database.close();
  }
Exemplo n.º 28
0
  @Test
  public void insertAvoidingSubQuery() {
    database.open("admin", "admin");

    final OSchema schema = database.getMetadata().getSchema();
    if (schema.getClass("test") == null) schema.createClass("test");

    ODocument doc =
        (ODocument)
            database
                .command(new OCommandSQL("INSERT INTO test(text) VALUES ('(Hello World)')"))
                .execute();

    Assert.assertTrue(doc != null);
    Assert.assertEquals(doc.field("text"), "(Hello World)");

    database.close();
  }
  protected <RET> RET executeCommand(OCommandRequest query) throws SQLException {

    try {
      return database.command(query).execute();
    } catch (OQueryParsingException e) {
      throw new SQLSyntaxErrorException("Error while parsing command", e);
    } catch (OException e) {
      throw new SQLException("Error while executing command", e);
    }
  }
Exemplo n.º 30
0
 /** @return result of execution */
 public final V execute() {
   ODatabaseDocument db = null;
   ODatabaseDocument oldDb = ODatabaseRecordThreadLocal.INSTANCE.getIfDefined();
   if (oldDb != null)
     ODatabaseRecordThreadLocal.INSTANCE.remove(); // Required to avoid stack of transactions
   try {
     db =
         getSettings()
             .getDatabasePoolFactory()
             .get(getDBUrl(), getUsername(), getPassword())
             .acquire();
     db.activateOnCurrentThread();
     return execute(db);
   } finally {
     if (db != null) db.close();
     if (oldDb != null) ODatabaseRecordThreadLocal.INSTANCE.set((ODatabaseDocumentInternal) oldDb);
     else ODatabaseRecordThreadLocal.INSTANCE.remove();
   }
 }