@Test
  public void testOldSyntax() throws Exception {
    database.command(new OCommandSQL("CREATE INDEX SQLDropIndexTestClass.prop1 UNIQUE")).execute();

    database.getMetadata().getIndexManager().reload();

    OIndex<?> index =
        database
            .getMetadata()
            .getSchema()
            .getClass("SQLDropIndexTestClass")
            .getClassIndex("SQLDropIndexTestClass.prop1");
    Assert.assertNotNull(index);

    database.command(new OCommandSQL("DROP INDEX SQLDropIndexTestClass.prop1")).execute();
    database.getMetadata().getIndexManager().reload();

    index =
        database
            .getMetadata()
            .getSchema()
            .getClass("SQLDropIndexTestClass")
            .getClassIndex("SQLDropIndexTestClass.prop1");
    Assert.assertNull(index);
  }
  @Test(dependsOnMethods = "testDropIndexWithoutClass")
  public void testDropCompositeIndex() throws Exception {
    database
        .command(
            new OCommandSQL(
                "CREATE INDEX SQLDropIndexCompositeIndex ON SQLDropIndexTestClass (prop1, prop2) UNIQUE"))
        .execute();
    database.getMetadata().getIndexManager().reload();

    OIndex<?> index =
        database
            .getMetadata()
            .getSchema()
            .getClass("SQLDropIndexTestClass")
            .getClassIndex("SQLDropIndexCompositeIndex");
    Assert.assertNotNull(index);

    database.command(new OCommandSQL("DROP INDEX SQLDropIndexCompositeIndex")).execute();
    database.getMetadata().getIndexManager().reload();

    index =
        database
            .getMetadata()
            .getSchema()
            .getClass("SQLDropIndexTestClass")
            .getClassIndex("SQLDropIndexCompositeIndex");
    Assert.assertNull(index);
  }
  private void initializeExceptionRecordTable(String databaseUrl) {
    ODatabaseDocumentTx database = new ODatabaseDocumentTx(databaseUrl).create();
    OClass exceptionRecordClass = database.getMetadata().getSchema().createClass("ExceptionRecord");
    OClass exceptionVersionClass =
        database.getMetadata().getSchema().createClass("ExceptionRecordVersion");
    try {

      exceptionRecordClass.createProperty("id", OType.STRING);
      exceptionRecordClass.createProperty("status", OType.STRING);
      exceptionRecordClass.createProperty("approved", OType.BOOLEAN);
      exceptionRecordClass.createProperty("recordType", OType.STRING);
      exceptionRecordClass.createProperty("groupNonException", OType.BOOLEAN);
      exceptionRecordClass.createProperty("comment", OType.STRING);
      exceptionRecordClass.createProperty("jobId", OType.STRING);
      exceptionRecordClass.createProperty("dataflowName", OType.STRING);
      exceptionRecordClass.createProperty("username", OType.STRING);
      exceptionRecordClass.createProperty("timestamp", OType.LONG);
      exceptionRecordClass.createProperty("stageLabel", OType.STRING);
      exceptionRecordClass.createProperty("groupColumn", OType.STRING);
      exceptionRecordClass.createProperty("lastModifiedBy", OType.STRING);
      exceptionRecordClass.createProperty("lastModified", OType.LONG);
      exceptionRecordClass.createProperty("data", OType.STRING);

      exceptionVersionClass.createProperty("key-exceptionId", OType.STRING);
      exceptionVersionClass.createProperty("key-version", OType.STRING);
      exceptionVersionClass.createProperty("jobId", OType.STRING);
      exceptionVersionClass.createProperty("dataflowName", OType.STRING);

      exceptionRecordClass.createIndex("ExceptionRecord_pk", INDEX_TYPE.UNIQUE, "id");
      exceptionRecordClass.createIndex(
          "ExceptionRecord_idx",
          INDEX_TYPE.NOTUNIQUE,
          "status",
          "approved",
          "recordType",
          "groupNonException",
          "comment",
          "jobId",
          "dataflowName",
          "username",
          "timestamp",
          "stageLabel",
          "groupColumn",
          "lastModifiedBy",
          "lastModified");

      exceptionVersionClass.createIndex(
          "ExceptionVersion_Index",
          INDEX_TYPE.NOTUNIQUE,
          "key-exceptionId",
          "key-version",
          "jobId",
          "dataflowname");
    } finally {
      database.close();
    }
  }
  @SuppressWarnings("unchecked")
  @Test
  public void createLinkInTx() {
    ODatabaseDocumentTx db = new ODatabaseDocumentTx(url);
    db.open("admin", "admin");

    OClass profile =
        db.getMetadata()
            .getSchema()
            .createClass("MyProfile", db.addCluster("myprofile", OStorage.CLUSTER_TYPE.PHYSICAL));
    OClass edge =
        db.getMetadata()
            .getSchema()
            .createClass("MyEdge", db.addCluster("myedge", OStorage.CLUSTER_TYPE.PHYSICAL));
    profile
        .createProperty("name", OType.STRING)
        .setMin("3")
        .setMax("30")
        .createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
    profile.createProperty("surname", OType.STRING).setMin("3").setMax("30");
    profile.createProperty("in", OType.LINKSET, edge);
    profile.createProperty("out", OType.LINKSET, edge);
    edge.createProperty("in", OType.LINK, profile);
    edge.createProperty("out", OType.LINK, profile);

    db.begin();

    ODocument kim = new ODocument("MyProfile").field("name", "Kim").field("surname", "Bauer");
    ODocument teri = new ODocument("MyProfile").field("name", "Teri").field("surname", "Bauer");
    ODocument jack = new ODocument("MyProfile").field("name", "Jack").field("surname", "Bauer");

    ODocument myedge = new ODocument("MyEdge").field("in", kim).field("out", jack);
    myedge.save();
    ((HashSet<ODocument>) kim.field("out", new HashSet<ORID>()).field("out")).add(myedge);
    ((HashSet<ODocument>) jack.field("in", new HashSet<ORID>()).field("in")).add(myedge);

    jack.save();
    kim.save();
    teri.save();

    db.commit();

    db.close();

    db.open("admin", "admin");
    List<ODocument> result =
        db.command(new OSQLSynchQuery<ODocument>("select from MyProfile ")).execute();

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

    db.close();
  }
Example #5
0
  @SuppressWarnings("unchecked")
  @Test
  public void test1() {

    db =
        new ODatabaseDocumentTx(
            "local:C:/work/dev/orientechnologies/orientdb/temp/danny/library/library");

    try {
      db.create();

      master = db.getMetadata().getSchema().createClass("Master");
      master.createProperty("type", OType.STRING);
      master.createProperty("master", OType.LONG);

      dependents = db.getMetadata().getSchema().createClass("Dependents");
      dependents.createProperty("type", OType.STRING);
      dependents.createProperty("dependents", OType.EMBEDDEDLIST, master);

      db.close();

      db.open("admin", "admin");
      dependents = db.getMetadata().getSchema().getClass("Dependents");
      master = db.getMetadata().getSchema().getClass("Master");

      // CREATE NEW DOC
      new ODocument(db, "Dependents")
          .field(
              "dependents",
              new ODocument[] {
                new ODocument(db, "Master")
                    .field("mastertype", "Title")
                    .field("master", 4151788013272153098L)
              })
          .save();
      db.close();

      db.open("admin", "admin");

      // LOAD IT AND CHECK THE LONG VALUE
      for (ODocument doc : db.browseClass("Dependents")) {
        System.out.println(doc);
        for (ODocument emb : (Iterable<ODocument>) doc.field("dependents"))
          Assert.assertEquals(emb.field("master"), 4151788013272153098L);
      }
      db.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  @Override
  public boolean execute(final OHttpRequest iRequest) throws Exception {
    String[] urlParts =
        checkSyntax(
            iRequest.url,
            3,
            "Syntax error: class/<database>/<class-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 class";
    iRequest.data.commandDetail = urlParts[2];

    ODatabaseDocumentTx db = null;

    try {
      db = getProfiledDatabaseInstance(iRequest);

      if (db.getMetadata().getSchema().getClass(urlParts[2]) == null)
        throw new IllegalArgumentException("Invalid class '" + urlParts[2] + "'");

      final int limit = urlParts.length > 3 ? Integer.parseInt(urlParts[3]) : 20;

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

        response.add(rec);
      }

      if (response != null && response.size() > 0) {
        sendRecordsContent(iRequest, response);
      } else {
        final StringWriter buffer = new StringWriter();
        final OJSONWriter json = new OJSONWriter(buffer, JSON_FORMAT);
        json.beginObject();
        exportClassSchema(db, json, db.getMetadata().getSchema().getClass(urlParts[2]));
        json.endObject();
        sendTextContent(
            iRequest,
            OHttpUtils.STATUS_OK_CODE,
            "OK",
            null,
            OHttpUtils.CONTENT_JSON,
            buffer.toString());
      }
    } finally {
      if (db != null) OSharedDocumentDatabase.release(db);
    }
    return false;
  }
  @Override
  public boolean execute(final OHttpRequest iRequest, OHttpResponse iResponse) throws Exception {
    final String[] urlParts =
        checkSyntax(iRequest.url, 3, "Syntax error: index/<database>/<index-name>/<key>/[<value>]");

    iRequest.data.commandInfo = "Index remove";

    ODatabaseDocumentTx db = null;

    try {
      db = getProfiledDatabaseInstance(iRequest);

      final OIndex<?> index = db.getMetadata().getIndexManager().getIndex(urlParts[2]);
      if (index == null)
        throw new IllegalArgumentException("Index name '" + urlParts[2] + "' not found");

      final boolean found;
      if (urlParts.length > 4) found = index.remove(urlParts[3], new ORecordId(urlParts[3]));
      else found = index.remove(urlParts[3]);

      if (found)
        iResponse.send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_TEXT_PLAIN, null, null);
      else
        iResponse.send(
            OHttpUtils.STATUS_NOTFOUND_CODE,
            OHttpUtils.STATUS_NOTFOUND_DESCRIPTION,
            OHttpUtils.CONTENT_TEXT_PLAIN,
            null,
            null);
    } finally {
      if (db != null) db.close();
    }
    return false;
  }
  @Test
  public void testExceptionManagement() {
    // issue #5244
    OLiveCommandExecutorSQLFactory.init();

    ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:ONonBlockingQueryTest");
    db.activateOnCurrentThread();
    db.create();

    db.getMetadata().getSchema().createClass("test");
    MyResultListener listener = new MyResultListener();
    try {
      db.command(new OCommandSQL("insert into test set name = 'foo', surname = 'bar'")).execute();

      db.query(new OSQLNonBlockingQuery<Object>("select from test bla blu", listener));
      try {
        Thread.sleep(3000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      Assert.assertEquals(listener.finished, true);

      listener = new MyResultListener();
      db.query(new OSQLNonBlockingQuery<Object>("select from test", listener));

    } finally {
      db.close();
    }
    try {
      Thread.sleep(3000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    Assert.assertEquals(listener.numResults, 1);
  }
Example #9
0
  @Test
  public void testLiveInsert() {
    OLiveCommandExecutorSQLFactory.init();

    ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:OLiveQueryTest");
    db.activateOnCurrentThread();
    db.create();
    db.registerHook(new OLiveQueryHook(db));
    try {
      db.getMetadata().getSchema().createClass("test");
      db.getMetadata().getSchema().createClass("test2");
      MyLiveQueryListener listener = new MyLiveQueryListener();

      db.query(new OLiveQuery<ODocument>("live select from test", listener));

      db.command(new OCommandSQL("insert into test set name = 'foo', surname = 'bar'")).execute();
      db.command(new OCommandSQL("insert into test set name = 'foo', surname = 'baz'")).execute();
      db.command(new OCommandSQL("insert into test2 set name = 'foo'"));

      try {
        Thread.sleep(3000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      Assert.assertEquals(listener.ops.size(), 2);
      for (ORecordOperation doc : listener.ops) {
        Assert.assertEquals(doc.type, ORecordOperation.CREATED);
        Assert.assertEquals(((ODocument) doc.record).field("name"), "foo");
      }
    } finally {

      db.drop();
    }
  }
Example #10
0
  @Test(dependsOnMethods = "testOldSyntax")
  public void testDropIndexWithoutClass() throws Exception {
    database
        .command(new OCommandSQL("CREATE INDEX SQLDropIndexWithoutClass UNIQUE double"))
        .execute();
    database.getMetadata().getIndexManager().reload();

    OIndex<?> index = database.getMetadata().getIndexManager().getIndex("SQLDropIndexWithoutClass");
    Assert.assertNotNull(index);

    database.command(new OCommandSQL("DROP INDEX SQLDropIndexWithoutClass")).execute();
    database.getMetadata().getIndexManager().reload();

    index = database.getMetadata().getIndexManager().getIndex("SQLDropIndexWithoutClass");

    Assert.assertNull(index);
  }
  @Override
  public void initClazz(ODatabaseDocumentTx db) {

    OSchemaProxy schema = db.getMetadata().getSchema();
    OClass shape = superClass(db);
    OClass polygon = schema.createAbstractClass(getName(), shape);
    polygon.createProperty("geometries", OType.EMBEDDEDLIST, shape);
  }
 @Test
 public void testSelectFromClusterNumber() {
   OClass clazz = db.getMetadata().getSchema().getClass("DistinctLimit");
   int firstCluster = clazz.getClusterIds()[0];
   OSQLSynchQuery sql = new OSQLSynchQuery("select from cluster:" + firstCluster + " limit 1");
   List<ODocument> results = db.query(sql);
   assertEquals(results.size(), 1);
 }
 @AfterClass
 public void afterClass() throws Exception {
   if (db.isClosed()) {
     db.open("admin", "admin");
   }
   db.command(new OCommandSQL("drop class foo")).execute();
   db.getMetadata().getSchema().reload();
   db.close();
 }
  private void compareIndexes() {
    ODatabaseRecordThreadLocal.INSTANCE.set(baseDocumentTx);
    OIndexCursor cursor = baseDocumentTx.getMetadata().getIndexManager().getIndex("mi").cursor();

    long lastTs = 0;
    long minLostTs = Long.MAX_VALUE;

    long restoredRecords = 0;

    Map.Entry<Object, OIdentifiable> entry = cursor.nextEntry();
    while (entry != null) {
      ODatabaseRecordThreadLocal.INSTANCE.set(baseDocumentTx);
      Integer key = (Integer) entry.getKey();

      OIdentifiable identifiable = entry.getValue();
      ODocument doc = identifiable.getRecord();

      long ts = doc.<Long>field("ts");
      if (ts > lastTs) lastTs = ts;

      entry = cursor.nextEntry();

      ODatabaseRecordThreadLocal.INSTANCE.set(testDocumentTx);
      OIndex testIndex = testDocumentTx.getMetadata().getIndexManager().getIndex("mi");

      Set<OIdentifiable> result = (Set<OIdentifiable>) testIndex.get(key);
      if (result == null || result.isEmpty()) {
        if (minLostTs > ts) minLostTs = ts;
      } else restoredRecords++;
    }

    ODatabaseRecordThreadLocal.INSTANCE.set(baseDocumentTx);
    System.out.println(
        "Restored entries : "
            + restoredRecords
            + " out of : "
            + baseDocumentTx.getMetadata().getIndexManager().getIndex("mi").getSize());

    long maxInterval = minLostTs == Long.MAX_VALUE ? 0 : lastTs - minLostTs;
    System.out.println("Lost records max interval (ms) : " + maxInterval);

    assertThat(maxInterval).isLessThan(2000);
  }
  @Before
  public void setup() throws DBException {
    orientDBClient = new OrientDBClient();

    Properties p = new Properties();
    // TODO: Extract the property names into final variables in OrientDBClient
    p.setProperty("orientdb.url", TEST_DB_URL);

    orientDBClient.setProperties(p);
    orientDBClient.init();
    orientDBConnection = new ODatabaseDocumentTx(TEST_DB_URL).open("admin", "admin");
    orientDBDictionary = orientDBConnection.getMetadata().getIndexManager().getDictionary();
  }
Example #16
0
  @BeforeClass
  public void beforeClass() {
    database = new ODatabaseDocumentTx(url);

    if (database.isClosed()) database.open("admin", "admin");

    final OSchema schema = database.getMetadata().getSchema();
    final OClass oClass = schema.createClass("SQLDropIndexTestClass");
    oClass.createProperty("prop1", EXPECTED_PROP1_TYPE);
    oClass.createProperty("prop2", EXPECTED_PROP2_TYPE);

    schema.save();
  }
  private void initExpandSkipLimit(ODatabaseDocumentTx db) {
    db.getMetadata().getSchema().createClass("ExpandSkipLimit");

    for (int i = 0; i < 5; i++) {
      ODocument doc = new ODocument("ExpandSkipLimit");
      doc.field("nnum", i);
      doc.save();
      ODocument parent = new ODocument("ExpandSkipLimit");
      parent.field("parent", true);
      parent.field("num", i);
      parent.field("linked", doc);
      parent.save();
    }
  }
Example #18
0
 @Test(dependsOnMethods = "testDropCompositeIndex")
 public void testDropIndexWorkedCorrectly() {
   OIndex<?> index =
       database
           .getMetadata()
           .getSchema()
           .getClass("SQLDropIndexTestClass")
           .getClassIndex("SQLDropIndexTestClass.prop1");
   Assert.assertNull(index);
   index =
       database
           .getMetadata()
           .getSchema()
           .getClass("SQLDropIndexTestClass")
           .getClassIndex("SQLDropIndexWithoutClass");
   Assert.assertNull(index);
   index =
       database
           .getMetadata()
           .getSchema()
           .getClass("SQLDropIndexTestClass")
           .getClassIndex("SQLDropIndexCompositeIndex");
   Assert.assertNull(index);
 }
Example #19
0
 public static void create() {
   OClass account =
       database
           .getMetadata()
           .getSchema()
           .createClass(
               "Account",
               database.getStorage().addCluster("account", OStorage.CLUSTER_TYPE.PHYSICAL));
   account.createProperty("id", OType.LONG);
   account.createProperty("val1", OType.DOUBLE);
   account.createProperty("val2", OType.DOUBLE);
   account.createProperty("val3", OType.FLOAT);
   account.createProperty("val4", OType.SHORT);
   account.createProperty("val5", OType.STRING);
   account.createProperty("name", OType.STRING);
 }
  private void initMassiveOrderSkipLimit(ODatabaseDocumentTx db) {
    db.getMetadata().getSchema().createClass("MassiveOrderSkipLimit");
    db.declareIntent(new OIntentMassiveInsert());
    String fieldValue =
        "laskdf lkajsd flaksjdf laksjd flakjsd flkasjd flkajsd flkajsd flkajsd flkajsd flkajsd flkjas;lkj a;ldskjf laksdj asdklasdjf lskdaj fladsd";
    for (int i = 0; i < ORDER_SKIP_LIMIT_ITEMS; i++) {
      ODocument doc = new ODocument("MassiveOrderSkipLimit");
      doc.field("nnum", i);
      doc.field("aaa", fieldValue);
      doc.field("bbb", fieldValue);
      doc.field("bbba", fieldValue);
      doc.field("daf", fieldValue);
      doc.field("dfgd", fieldValue);
      doc.field("dgd", fieldValue);

      doc.save();
    }
    db.declareIntent(null);
  }
Example #21
0
  public static void insert() {
    database.declareIntent(new OIntentMassiveInsert());
    database.begin(TXTYPE.NOTX);
    long ndoc = 1000000;
    ODocument doc = new ODocument();

    System.out.println("Inserting " + ndoc + " docs...");

    long block = System.nanoTime();
    for (long i = 1; i <= ndoc; i++) {
      doc.field("id", i);
      doc.field("val1", 4.0d);
      doc.field("val2", 5.0d);
      doc.field("val3", 6.0f);
      doc.field("val4", 255);
      doc.field("val5", "this is the description for a long comic books -" + i);
      doc.field("name", "this is secmask put on top - " + i);
      doc.setClassName("Account");
      doc.save();
      doc.reset();
      if (i % 100000 == 0) {
        double time = (double) (System.nanoTime() - block) / 1000000;
        System.out.println(i * 100 / ndoc + "%.\t" + time + "\t" + 100000.0d / time + " docs/ms");
        block = System.nanoTime();
      }
    }
    database.commit();

    System.out.println("Insertion done, now indexing ids...");

    block = System.nanoTime();

    // CREATE THE INDEX AT THE END
    database
        .getMetadata()
        .getSchema()
        .getClass("Account")
        .getProperty("id")
        .createIndex(OClass.INDEX_TYPE.UNIQUE);

    System.out.println("Indexing done in: " + (System.nanoTime() - block) / 1000000 + "ms");
  }
Example #22
0
  @BeforeMethod
  public void beforeMethod() {
    database.open("admin", "admin");
    OIndex<?> index = getIndex();

    if (index == null) {
      OBinarySerializerFactory.INSTANCE.registerSerializer(new OHash256Serializer(), null);

      database
          .getMetadata()
          .getIndexManager()
          .createIndex(
              "custom-hash",
              "UNIQUE",
              new ORuntimeKeyIndexDefinition(OHash256Serializer.ID),
              null,
              null,
              null);
    }
  }
 private void createSchema(ODatabaseDocumentTx dbDocumentTx) {
   ODatabaseRecordThreadLocal.INSTANCE.set(dbDocumentTx);
   dbDocumentTx.command(new OCommandSQL("create index mi notunique integer")).execute();
   dbDocumentTx.getMetadata().getIndexManager().reload();
 }
  public void TransactionRollbackConstistencyTest() {
    System.out.println(
        "**************************TransactionRollbackConsistencyTest***************************************");
    ODatabaseDocumentTx db = new ODatabaseDocumentTx(url);
    db.open("admin", "admin");
    OClass vertexClass = db.getMetadata().getSchema().createClass("TRVertex");
    OClass edgeClass = db.getMetadata().getSchema().createClass("TREdge");
    vertexClass.createProperty("in", OType.LINKSET, edgeClass);
    vertexClass.createProperty("out", OType.LINKSET, edgeClass);
    edgeClass.createProperty("in", OType.LINK, vertexClass);
    edgeClass.createProperty("out", OType.LINK, vertexClass);

    OClass personClass = db.getMetadata().getSchema().createClass("TRPerson", vertexClass);
    personClass.createProperty("name", OType.STRING).createIndex(OClass.INDEX_TYPE.UNIQUE);
    personClass.createProperty("surname", OType.STRING).createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
    personClass.createProperty("version", OType.INTEGER);

    db.getMetadata().getSchema().save();
    db.close();

    final int cnt = 4;

    db.open("admin", "admin");
    db.begin();
    Vector inserted = new Vector();

    for (int i = 0; i < cnt; i++) {
      ODocument person = new ODocument("TRPerson");
      person.field("name", Character.toString((char) ('A' + i)));
      person.field("surname", Character.toString((char) ('A' + (i % 3))));
      person.field("myversion", 0);
      person.field("in", new HashSet<ODocument>());
      person.field("out", new HashSet<ODocument>());

      if (i >= 1) {
        ODocument edge = new ODocument("TREdge");
        edge.field("in", person.getIdentity());
        edge.field("out", inserted.elementAt(i - 1));
        ((HashSet<ODocument>) person.field("out")).add(edge);
        ((HashSet<ODocument>) ((ODocument) inserted.elementAt(i - 1)).field("in")).add(edge);
        edge.save();
      }
      inserted.add(person);
      person.save();
    }
    db.commit();

    final List<ODocument> result1 = db.command(new OCommandSQL("select from TRPerson")).execute();
    Assert.assertNotNull(result1);
    Assert.assertEquals(result1.size(), cnt);
    System.out.println("Before transaction commit");
    for (ODocument d : result1) System.out.println(d);

    try {
      db.begin();
      Vector inserted2 = new Vector();

      for (int i = 0; i < cnt; i++) {
        ODocument person = new ODocument("TRPerson");
        person.field("name", Character.toString((char) ('a' + i)));
        person.field("surname", Character.toString((char) ('a' + (i % 3))));
        person.field("myversion", 0);
        person.field("in", new HashSet<ODocument>());
        person.field("out", new HashSet<ODocument>());

        if (i >= 1) {
          ODocument edge = new ODocument("TREdge");
          edge.field("in", person.getIdentity());
          edge.field("out", inserted2.elementAt(i - 1));
          ((HashSet<ODocument>) person.field("out")).add(edge);
          ((HashSet<ODocument>) ((ODocument) inserted2.elementAt(i - 1)).field("in")).add(edge);
          edge.save();
        }
        inserted2.add(person);
        person.save();
      }

      for (int i = 0; i < cnt; i++) {
        if (i != cnt - 1) {
          ((ODocument) inserted.elementAt(i)).field("myversion", 2);
          ((ODocument) inserted.elementAt(i)).save();
        }
      }

      ((ODocument) inserted.elementAt(cnt - 1)).delete();
      ((ODocument) inserted.elementAt(cnt - 2)).getRecordVersion().reset();
      ((ODocument) inserted.elementAt(cnt - 2)).save();
      db.commit();
      Assert.assertTrue(false);
    } catch (OConcurrentModificationException e) {
      Assert.assertTrue(true);
      db.rollback();
    }

    final List<ODocument> result2 = db.command(new OCommandSQL("select from TRPerson")).execute();
    Assert.assertNotNull(result2);
    System.out.println("After transaction commit failure/rollback");
    for (ODocument d : result2) System.out.println(d);
    Assert.assertEquals(result2.size(), cnt);

    db.close();
    System.out.println(
        "**************************TransactionRollbackConstistencyTest***************************************");
  }
  @Test
  public void testTransactionPopulateDelete() {
    ODatabaseDocumentTx db = new ODatabaseDocumentTx(url);
    db.open("admin", "admin");

    if (!db.getMetadata().getSchema().existsClass("MyFruit")) {
      OClass fruitClass = db.getMetadata().getSchema().createClass("MyFruit");
      fruitClass.createProperty("name", OType.STRING);
      fruitClass.createProperty("color", OType.STRING);
      fruitClass.createProperty("flavor", OType.STRING);

      db.getMetadata()
          .getSchema()
          .getClass("MyFruit")
          .getProperty("name")
          .createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
      db.getMetadata()
          .getSchema()
          .getClass("MyFruit")
          .getProperty("color")
          .createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
      db.getMetadata()
          .getSchema()
          .getClass("MyFruit")
          .getProperty("flavor")
          .createIndex(OClass.INDEX_TYPE.NOTUNIQUE);
    }
    db.close();

    db = new ODatabaseDocumentTx(url);
    db.open("admin", "admin");
    int chunkSize = 500;
    for (int initialValue = 0; initialValue < 10; initialValue++) {
      System.out.println("initialValue = " + initialValue);
      Assert.assertEquals(db.countClusterElements("MyFruit"), 0);

      // do insert
      Vector<ODocument> v = new Vector<ODocument>();
      db.begin();
      for (int i = initialValue * chunkSize; i < (initialValue * chunkSize) + chunkSize; i++) {
        ODocument d =
            new ODocument("MyFruit")
                .field("name", "" + i)
                .field("color", "FOO")
                .field("flavor", "BAR" + i);
        d.save();
        v.addElement(d);
      }
      System.out.println("populate commit");
      db.commit();

      // do delete
      db.begin();
      System.out.println("vector size = " + v.size());
      for (int i = 0; i < v.size(); i++) {
        db.delete(v.elementAt(i));
      }
      System.out.println("delete commit");
      db.commit();

      Assert.assertEquals(db.countClusterElements("MyFruit"), 0);
    }

    db.close();
  }
Example #26
0
 @AfterClass
 public void afterClass() {
   database.open("admin", "admin");
   database.getMetadata().getIndexManager().dropIndex("custom-hash");
 }
    @Override
    public void run() {
      ODatabaseDocumentTx db = null;
      try {
        db = graph.getDatabase();

        // does class Config exist in database?
        if (db.getMetadata().getSchema().existsClass("Config")) {
          // get last update
          // create query
          String sql = "select value from Config where key = 'lastUpdateCheck'";
          // execute query
          OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<>(sql);
          List<ODocument> list = db.command(query).execute();

          // update needed?
          boolean updateNeeded = false;
          if (list.size() == 0) updateNeeded = true;
          else { // update needed?
            ODocument doc = list.get(0);
            try { // try to parse int
              int lastCheck = Integer.parseInt(doc.field("value", String.class));
              int now = (int) (System.currentTimeMillis() / 1000);
              // check within the last 24 hours?
              int timePassed = now - lastCheck;
              if (timePassed > 24 * 60 * 60) updateNeeded = true;
              else
                logger.info("No update check needed. Last check " + timePassed + " seconds ago.");
            } catch (Throwable e) {
              logger.warn(
                  "UpdateThread could not determine correct lastUpdateCheck although Config class exists in database",
                  e);
              updateNeeded = true;
            }
          }

          if (updateNeeded) {
            logger.info("Update check needed: Checking now.");

            // run update and return value
            String version = null;
            try {
              version = getHTML();
            } catch (Exception e) {
              logger.error(
                  "Could not load new version status from http://segrada.org/fileadmin/downloads/version.txt. Skipping update check.");

              // clear version update - just to make sure we have no strange artifacts
              db.command(new OCommandSQL("DELETE FROM Config WHERE key = 'versionUpdate'"))
                  .execute();
            }

            if (version != null) {
              String versionUpdate;
              if (toNumericVersion(currentVersion) < toNumericVersion(version)) {
                if (logger.isInfoEnabled())
                  logger.info(
                      "UPDATE NEEDED: My version is "
                          + currentVersion
                          + ", server said newest is "
                          + version);
                versionUpdate = version;
              } else {
                logger.info("No update needed (version is " + currentVersion + ").");
                versionUpdate = "";
              }

              // upsert last check
              String update =
                  "UPDATE Config SET key = 'lastUpdateCheck', value = '"
                      + Long.toString((System.currentTimeMillis() / 1000))
                      + "' UPSERT WHERE key = 'lastUpdateCheck'";
              db.command(new OCommandSQL(update)).execute();

              // upsert version update
              if (versionUpdate == null || versionUpdate.isEmpty()) {
                db.command(new OCommandSQL("DELETE FROM Config WHERE key = 'versionUpdate'"))
                    .execute();
              } else {
                update =
                    "UPDATE Config SET key = 'versionUpdate', value = '"
                        + OrientStringEscape.escapeOrientSql(versionUpdate)
                        + "' UPSERT WHERE key = 'versionUpdate'";
                db.command(new OCommandSQL(update)).execute();
              }
            }
          }
        } else logger.info("No configuration yet, no update check.");
      } finally {
        // close db, if not null
        if (db != null) db.close();
      }
    }
  @BeforeClass
  public void beforeClass() throws Exception {
    db = new ODatabaseDocumentTx(DB_STORAGE + ":" + DB_NAME);
    db.create();
    getProfilerInstance().startRecording();

    db.command(new OCommandSQL("CREATE class foo")).execute();
    db.command(new OCommandSQL("CREATE property foo.name STRING")).execute();
    db.command(new OCommandSQL("CREATE property foo.bar INTEGER")).execute();
    db.command(new OCommandSQL("CREATE property foo.address EMBEDDED")).execute();
    db.command(new OCommandSQL("CREATE property foo.comp STRING")).execute();
    db.command(new OCommandSQL("CREATE property foo.osite INTEGER")).execute();

    db.command(new OCommandSQL("CREATE index foo_name on foo (name) NOTUNIQUE")).execute();
    db.command(new OCommandSQL("CREATE index foo_bar on foo (bar) NOTUNIQUE")).execute();
    db.command(new OCommandSQL("CREATE index foo_comp_osite on foo (comp, osite) NOTUNIQUE"))
        .execute();

    db.command(
            new OCommandSQL(
                "insert into foo (name, bar, address) values ('a', 1, {'street':'1st street', 'city':'NY', '@type':'d'})"))
        .execute();
    db.command(new OCommandSQL("insert into foo (name, bar) values ('b', 2)")).execute();
    db.command(new OCommandSQL("insert into foo (name, bar) values ('c', 3)")).execute();

    db.command(new OCommandSQL("insert into foo (comp, osite) values ('a', 1)")).execute();
    db.command(new OCommandSQL("insert into foo (comp, osite) values ('b', 2)")).execute();

    db.command(new OCommandSQL("CREATE class bar")).execute();

    db.command(new OCommandSQL("insert into bar (name, foo) values ('a', 1)")).execute();
    db.command(new OCommandSQL("insert into bar (name, foo) values ('b', 2)")).execute();
    db.command(new OCommandSQL("insert into bar (name, foo) values ('c', 3)")).execute();
    db.command(new OCommandSQL("insert into bar (name, foo) values ('d', 4)")).execute();
    db.command(new OCommandSQL("insert into bar (name, foo) values ('e', 5)")).execute();
    db.command(new OCommandSQL("insert into bar (name, foo) values ('f', 1)")).execute();
    db.command(new OCommandSQL("insert into bar (name, foo) values ('g', 2)")).execute();
    db.command(new OCommandSQL("insert into bar (name, foo) values ('h', 3)")).execute();
    db.command(new OCommandSQL("insert into bar (name, foo) values ('i', 4)")).execute();
    db.command(new OCommandSQL("insert into bar (name, foo) values ('j', 5)")).execute();
    db.command(new OCommandSQL("insert into bar (name, foo) values ('k', 1)")).execute();
    db.command(new OCommandSQL("insert into bar (name, foo) values ('l', 2)")).execute();
    db.command(new OCommandSQL("insert into bar (name, foo) values ('m', 3)")).execute();
    db.command(new OCommandSQL("insert into bar (name, foo) values ('n', 4)")).execute();
    db.command(new OCommandSQL("insert into bar (name, foo) values ('o', 5)")).execute();

    db.command(new OCommandSQL("CREATE class ridsorttest")).execute();
    db.command(new OCommandSQL("CREATE property ridsorttest.name INTEGER")).execute();
    db.command(new OCommandSQL("CREATE index ridsorttest_name on ridsorttest (name) NOTUNIQUE"))
        .execute();

    db.command(new OCommandSQL("insert into ridsorttest (name) values (1)")).execute();
    db.command(new OCommandSQL("insert into ridsorttest (name) values (5)")).execute();
    db.command(new OCommandSQL("insert into ridsorttest (name) values (3)")).execute();
    db.command(new OCommandSQL("insert into ridsorttest (name) values (4)")).execute();
    db.command(new OCommandSQL("insert into ridsorttest (name) values (1)")).execute();
    db.command(new OCommandSQL("insert into ridsorttest (name) values (8)")).execute();
    db.command(new OCommandSQL("insert into ridsorttest (name) values (6)")).execute();

    db.command(new OCommandSQL("CREATE class unwindtest")).execute();
    db.command(
            new OCommandSQL("insert into unwindtest (name, coll) values ('foo', ['foo1', 'foo2'])"))
        .execute();
    db.command(
            new OCommandSQL("insert into unwindtest (name, coll) values ('bar', ['bar1', 'bar2'])"))
        .execute();

    db.command(new OCommandSQL("CREATE class edge")).execute();

    db.command(new OCommandSQL("CREATE class TestFromInSquare")).execute();
    db.command(
            new OCommandSQL(
                "insert into TestFromInSquare set tags = {' from ':'foo',' to ':'bar'}"))
        .execute();

    db.command(new OCommandSQL("CREATE class TestMultipleClusters")).execute();
    db.command(
            new OCommandSQL("alter class TestMultipleClusters addcluster testmultipleclusters1 "))
        .execute();
    db.command(
            new OCommandSQL("alter class TestMultipleClusters addcluster testmultipleclusters2 "))
        .execute();
    db.command(new OCommandSQL("insert into cluster:testmultipleclusters set name = 'aaa'"))
        .execute();
    db.command(new OCommandSQL("insert into cluster:testmultipleclusters1 set name = 'foo'"))
        .execute();
    db.command(new OCommandSQL("insert into cluster:testmultipleclusters2 set name = 'bar'"))
        .execute();

    db.command(new OCommandSQL("CREATE class TestUrl")).execute();
    db.command(
            new OCommandSQL("insert into TestUrl content { \"url\": \"http://www.google.com\" }"))
        .execute();

    db.command(new OCommandSQL("CREATE class TestParams")).execute();
    db.command(
            new OCommandSQL(
                "insert into TestParams  set name = 'foo', surname ='foo', active = true"))
        .execute();
    db.command(
            new OCommandSQL(
                "insert into TestParams  set name = 'foo', surname ='bar', active = false"))
        .execute();

    db.command(new OCommandSQL("CREATE class TestParamsEmbedded")).execute();
    db.command(
            new OCommandSQL(
                "insert into TestParamsEmbedded set emb = {  \n"
                    + "            \"count\":0,\n"
                    + "            \"testupdate\":\"1441258203385\"\n"
                    + "         }"))
        .execute();
    db.command(
            new OCommandSQL(
                "insert into TestParamsEmbedded set emb = {  \n"
                    + "            \"count\":1,\n"
                    + "            \"testupdate\":\"1441258203385\"\n"
                    + "         }"))
        .execute();

    db.command(new OCommandSQL("CREATE class TestBacktick")).execute();
    db.command(new OCommandSQL("insert into TestBacktick  set foo = 1, bar = 2, `foo-bar` = 10"))
        .execute();

    // /*** from issue #2743
    OSchema schema = db.getMetadata().getSchema();
    if (!schema.existsClass("alphabet")) {
      schema.createClass("alphabet");
    }

    ORecordIteratorClass<ODocument> iter = db.browseClass("alphabet");
    while (iter.hasNext()) {
      iter.next().delete();
    }

    // add 26 entries: { "letter": "A", "number": 0 }, ... { "letter": "Z", "number": 25 }

    String rowModel = "{\"letter\": \"%s\", \"number\": %d}";
    for (int i = 0; i < 26; ++i) {
      String l = String.valueOf((char) ('A' + i));
      String json = String.format(rowModel, l, i);
      ODocument doc = db.newInstance("alphabet");
      doc.fromJSON(json);
      doc.save();
    }

    db.command(new OCommandSQL("create class OCommandExecutorSQLSelectTest_aggregations"))
        .execute();
    db.command(
            new OCommandSQL(
                "insert into OCommandExecutorSQLSelectTest_aggregations set data = [{\"size\": 0}, {\"size\": 0}, {\"size\": 30}, {\"size\": 50}, {\"size\": 50}]"))
        .execute();

    initExpandSkipLimit(db);

    initMassiveOrderSkipLimit(db);
    initDatesSet(db);

    initMatchesWithRegex(db);
    initDistinctLimit(db);
  }
Example #29
0
 protected OIndex<?> getIndex() {
   return database.getMetadata().getIndexManager().getIndex("custom-hash");
 }