public void testIndexMapRemove() { final ODocument docOne = new ODocument(); docOne.save(); final ODocument docTwo = new ODocument(); docTwo.save(); final ODocument docThree = new ODocument(); docThree.save(); Map<String, ORID> map = new HashMap<String, ORID>(); map.put("key1", docOne.getIdentity()); map.put("key2", docTwo.getIdentity()); final ODocument document = new ODocument("LinkMapIndexTestClass"); document.field("linkMap", map); document.save(); document.delete(); final List<ODocument> resultByKey = database.command(new OCommandSQL("select key, rid from index:mapIndexTestKey")).execute(); Assert.assertNotNull(resultByKey); Assert.assertEquals(resultByKey.size(), 0); final List<ODocument> resultByValue = database.command(new OCommandSQL("select key, rid from index:mapIndexTestValue")).execute(); Assert.assertNotNull(resultByValue); Assert.assertEquals(resultByValue.size(), 0); }
@Test public void testConvertToDocument() throws Exception { IPictogram pictogram = new Pictogram(); pictogram.setTitle("title"); pictogram.setFileIdentifier("test.txt"); ODocument document = repository.convertToDocument(pictogram); assertEquals("title", document.field("title")); assertEquals("test.txt", document.field("fileIdentifier")); // class name should be correct assertEquals("Pictogram", document.getClassName()); // save document to get id document.save(); String id = document.getIdentity().toString(); // set id and test conversion pictogram.setId(id); ODocument newDocument = repository.convertToDocument(pictogram); assertEquals(document.getIdentity().toString(), newDocument.getIdentity().toString()); }
@Test(dependsOnMethods = "updateCollectionsRemoveWithWhereOperator") public void updateMapsWithPutOperatorAndWhere() { ODocument doc = database .command( new OCommandSQL( "insert into cluster:default (equaledges, name, properties) values ('no', 'updateMapsWithPutOperatorAndWhere', {} )")) .execute(); Integer records = database .command( new OCommandSQL( "update " + doc.getIdentity() + " put properties = 'one', 'two' where name = 'updateMapsWithPutOperatorAndWhere'")) .execute(); Assert.assertEquals(records.intValue(), 1); ODocument loadedDoc = database.load(doc.getIdentity(), "*:-1", true); Assert.assertTrue(loadedDoc.field("properties") instanceof Map); @SuppressWarnings("unchecked") Map<Object, Object> entries = loadedDoc.field("properties"); Assert.assertEquals(entries.size(), 1); Assert.assertNull(entries.get("round")); Assert.assertNull(entries.get("blaaa")); Assert.assertEquals(entries.get("one"), "two"); }
@Test public void testOrderByRid() { List<ODocument> qResult = db.command(new OCommandSQL("select from ridsorttest order by @rid ASC")).execute(); assertTrue(qResult.size() > 0); ODocument prev = qResult.get(0); for (int i = 1; i < qResult.size(); i++) { assertTrue(prev.getIdentity().compareTo(qResult.get(i).getIdentity()) <= 0); prev = qResult.get(i); } qResult = db.command(new OCommandSQL("select from ridsorttest order by @rid DESC")).execute(); assertTrue(qResult.size() > 0); prev = qResult.get(0); for (int i = 1; i < qResult.size(); i++) { assertTrue(prev.getIdentity().compareTo(qResult.get(i).getIdentity()) >= 0); prev = qResult.get(i); } qResult = db.command(new OCommandSQL("select from ridsorttest where name > 3 order by @rid DESC")) .execute(); assertTrue(qResult.size() > 0); prev = qResult.get(0); for (int i = 1; i < qResult.size(); i++) { assertTrue(prev.getIdentity().compareTo(qResult.get(i).getIdentity()) >= 0); prev = qResult.get(i); } }
@Override public void loadDataModel(ODatabaseDocumentTx db) { if (piutang != null) { if (paging != null) { int tmp = paging.getCurentHalaman() - 1 * paging.getJumlahPerHalaman(); if (tmp < 0) { tmp = 0; } model = dao.getAllByColumn( db, PiutangdDao.piutang, piutang.getIdentity(), tmp, paging.getJumlahPerHalaman()); // pelanggans=new ArrayList<ODocument>(); // for (ODocument oDocument : model) { // ODocument tmp2=oDocument.field(PenjualanDao.pelanggan); // tmp2.field(PelangganDao.name); // pelanggans.add(tmp2); // } } else { model = (List<ODocument>) getDao().getAllByColumn(db, PiutangdDao.piutang, piutang.getIdentity()); } } else { model = new ArrayList<ODocument>(); } }
@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(); }
@Test public void testFindByParent() throws Exception { ODocument parent1 = new ODocument("Node") .field("title", "ref1") .field("titleasc", "ref1") .field("description", "desc") .field("descriptionMarkup", "default") .field("created", 1L) .field("modified", 2L); parent1.save(); ODocument parent2 = new ODocument("Node") .field("title", "ref2") .field("titleasc", "ref2") .field("description", "desc") .field("descriptionMarkup", "default") .field("created", 1L) .field("modified", 2L); parent2.save(); String id1 = parent1.getIdentity().toString(); String id2 = parent2.getIdentity().toString(); IPeriod period1 = new Period(); period1.setFromEntry("1.1585"); period1.setToEntry("2.1585"); period1.setCreated(1L); period1.setModified(2L); period1.setParentId(id1); repository.save(period1); IPeriod period2 = new Period(); period2.setFromEntry("1929"); period2.setToEntry("1930"); period2.setCreated(1L); period2.setModified(2L); period2.setParentId(id1); repository.save(period2); IPeriod period3 = new Period(); period3.setFromEntry("1.1.1700"); period3.setToEntry("5.6.1702"); period3.setCreated(1L); period3.setModified(2L); period3.setParentId(id1); repository.save(period3); List<IPeriod> periods = repository.findByParent(id1); assertTrue(periods.size() == 3); periods = repository.findByParent(id2); assertTrue(periods.size() == 0); }
public void testIndexMapUpdateOneTx() throws Exception { final ODocument docOne = new ODocument(); docOne.save(); final ODocument docTwo = new ODocument(); docTwo.save(); database.begin(); try { final Map<String, ORID> mapTwo = new HashMap<String, ORID>(); mapTwo.put("key3", docOne.getIdentity()); mapTwo.put("key2", docTwo.getIdentity()); final ODocument document = new ODocument("LinkMapIndexTestClass"); document.field("linkMap", mapTwo); document.save(); database.commit(); } catch (Exception e) { database.rollback(); throw e; } final List<ODocument> resultByKey = database.command(new OCommandSQL("select key, rid from index:mapIndexTestKey")).execute(); Assert.assertNotNull(resultByKey); Assert.assertEquals(resultByKey.size(), 2); for (ODocument d : resultByKey) { Assert.assertTrue(d.containsField("key")); Assert.assertTrue(d.containsField("rid")); if (!d.field("key").equals("key2") && !d.field("key").equals("key3")) { Assert.fail("Unknown key found: " + d.field("key")); } } final List<ODocument> resultByValue = database.command(new OCommandSQL("select key, rid from index:mapIndexTestValue")).execute(); Assert.assertNotNull(resultByValue); Assert.assertEquals(resultByValue.size(), 2); for (ODocument d : resultByValue) { Assert.assertTrue(d.containsField("key")); Assert.assertTrue(d.containsField("rid")); if (!d.field("key").equals(docOne.getIdentity()) && !d.field("key").equals(docTwo.getIdentity())) { Assert.fail("Unknown key found: " + d.field("key")); } } }
@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(); }
@SuppressWarnings("unchecked") @Test public void loadRecordTest() { ODatabaseDocumentTx db = new ODatabaseDocumentTx(url); db.open("admin", "admin"); try { db.begin(); ODocument kim = new ODocument("Profile").field("name", "Kim").field("surname", "Bauer"); ODocument teri = new ODocument("Profile").field("name", "Teri").field("surname", "Bauer"); ODocument jack = new ODocument("Profile").field("name", "Jack").field("surname", "Bauer"); ODocument chloe = new ODocument("Profile").field("name", "Chloe").field("surname", "O'Brien"); ((HashSet<ODocument>) jack.field("following", new HashSet<ODocument>()).field("following")) .add(kim); ((HashSet<ODocument>) kim.field("following", new HashSet<ODocument>()).field("following")) .add(teri); ((HashSet<ODocument>) teri.field("following", new HashSet<ODocument>()).field("following")) .add(jack); ((HashSet<ODocument>) teri.field("following")).add(kim); ((HashSet<ODocument>) chloe.field("following", new HashSet<ODocument>()).field("following")) .add(jack); ((HashSet<ODocument>) chloe.field("following")).add(teri); ((HashSet<ODocument>) chloe.field("following")).add(kim); int profileClusterId = db.getClusterIdByName("Profile"); jack.save(); Assert.assertEquals(jack.getIdentity().getClusterId(), profileClusterId); kim.save(); Assert.assertEquals(kim.getIdentity().getClusterId(), profileClusterId); teri.save(); Assert.assertEquals(teri.getIdentity().getClusterId(), profileClusterId); chloe.save(); Assert.assertEquals(chloe.getIdentity().getClusterId(), profileClusterId); db.commit(); Assert.assertEquals(jack.getIdentity().getClusterId(), profileClusterId); Assert.assertEquals(kim.getIdentity().getClusterId(), profileClusterId); Assert.assertEquals(teri.getIdentity().getClusterId(), profileClusterId); Assert.assertEquals(chloe.getIdentity().getClusterId(), profileClusterId); db.close(); db.open("admin", "admin"); ODocument loadedChloe = db.load(chloe.getIdentity()); System.out.println(loadedChloe); } finally { db.close(); } }
@Override public Void call() throws Exception { baseDB.open("admin", "admin"); testDB.open("admin", "admin"); try { while (true) { long id = idGen.getAndIncrement(); long ts = System.currentTimeMillis(); ODatabaseRecordThreadLocal.INSTANCE.set(baseDB); ODocument doc = new ODocument(); doc.field("ts", ts); doc.save(); baseDB .command( new OCommandSQL( "insert into index:mi (key, rid) values (" + id + ", " + doc.getIdentity() + ")")) .execute(); ODatabaseRecordThreadLocal.INSTANCE.set(testDB); doc = new ODocument(); doc.field("ts", ts); doc.save(); testDB .command( new OCommandSQL( "insert into index:mi (key, rid) values (" + id + ", " + doc.getIdentity() + ")")) .execute(); } } finally { baseDB.activateOnCurrentThread(); baseDB.close(); testDB.activateOnCurrentThread(); testDB.close(); } }
@Test public void testConvertToEntity() throws Exception { ODocument parent = new ODocument("Node") .field("title", "ref1") .field("titleasc", "ref1") .field("description", "desc") .field("descriptionMarkup", "default") .field("created", 1L) .field("modified", 2L); parent.save(); ODocument document = new ODocument("Period") .field("fromEntryCalendar", "G") .field("toEntryCalendar", "G") .field("fromEntry", "1.1585") .field("toEntry", "2.1585") .field("from", 2299970L) .field("to", 2300028L) .field("type", "period") .field("comment", "comment") .field("fromFuzzyFlags", "x?") .field("toFuzzyFlags", "c?") .field("parent", parent) .field("created", 1L) .field("modified", 2L); // persist to database to create id document.save(); IPeriod period = repository.convertToEntity(document); assertEquals("1.1585", period.getFromEntry()); assertEquals("2.1585", period.getToEntry()); assertEquals("G", period.getFromEntryCalendar()); assertEquals("G", period.getToEntryCalendar()); assertEquals("period", period.getType()); assertEquals(new Long(2299970L), period.getFromJD()); assertEquals(new Long(2300028L), period.getToJD()); assertEquals("comment", period.getComment()); assertArrayEquals(new char[] {'?'}, period.getFuzzyFromFlags()); assertArrayEquals(new char[] {'c', '?'}, period.getFuzzyToFlags()); assertEquals(new Long(1L), period.getCreated()); assertEquals(new Long(2L), period.getModified()); assertEquals(parent.getIdentity().toString(), period.getParentId()); assertEquals("Node", period.getParentModel()); assertEquals(document.getIdentity().toString(), period.getId()); }
private static void fetchArray( final ORecordSchemaAware<?> iRootRecord, final Object iUserObject, final Map<String, Integer> iFetchPlan, Object fieldValue, String fieldName, final int iCurrentLevel, final int iLevelFromRoot, final int iFieldDepthLevel, final Map<ORID, Integer> parsedRecords, final String iFieldPathFromRoot, final OFetchListener iListener, final OFetchContext iContext) throws IOException { if (fieldValue instanceof ODocument[]) { final ODocument[] linked = (ODocument[]) fieldValue; iContext.onBeforeArray(iRootRecord, fieldName, iUserObject, linked); for (ODocument d : linked) { // GO RECURSIVELY final Integer fieldDepthLevel = parsedRecords.get(d.getIdentity()); if (!d.getIdentity().isValid() || (fieldDepthLevel != null && fieldDepthLevel.intValue() == iLevelFromRoot)) { removeParsedFromMap(parsedRecords, d); iContext.onBeforeDocument(iRootRecord, d, fieldName, iUserObject); final Object userObject = iListener.fetchLinked(iRootRecord, iUserObject, fieldName, d, iContext); processRecord( d, userObject, iFetchPlan, iCurrentLevel, iLevelFromRoot, iFieldDepthLevel, parsedRecords, iFieldPathFromRoot, iListener, iContext, ""); iContext.onAfterDocument(iRootRecord, d, fieldName, iUserObject); } else { iListener.parseLinkedCollectionValue(iRootRecord, d, iUserObject, fieldName, iContext); } } iContext.onAfterArray(iRootRecord, fieldName, iUserObject); } else { iListener.processStandardField(iRootRecord, fieldValue, fieldName, iContext, iUserObject, ""); } }
@Test public void test5CacheUpdatedMultipleDbs() { database1 = new ODatabaseDocumentTx(url).open("admin", "admin"); database2 = new ODatabaseDocumentTx(url).open("admin", "admin"); // Create docA in db1 database1.begin(TXTYPE.OPTIMISTIC); ODocument vDocA_db1 = database1.newInstance(); vDocA_db1.field(NAME, "docA"); database1.save(vDocA_db1); database1.commit(); // Keep the ID. ORID vDocA_Rid = vDocA_db1.getIdentity().copy(); // Update docA in db2 database2.begin(TXTYPE.OPTIMISTIC); ODocument vDocA_db2 = database2.load(vDocA_Rid); vDocA_db2.field(NAME, "docA_v2"); database2.save(vDocA_db2); database2.commit(); // Later... read docA with db1. database1.begin(TXTYPE.OPTIMISTIC); ODocument vDocA_db1_later = database1.load(vDocA_Rid, null, true); Assert.assertEquals(vDocA_db1_later.field(NAME), "docA_v2"); database1.commit(); database1.close(); database2.close(); }
@Override public OSerializableStream fromStream(final byte[] iStream) throws OSerializationException { final ODocument record = getRecord(); ((ORecordId) record.getIdentity()).fromString(new String(iStream)); record.setInternalStatus(STATUS.NOT_LOADED); return this; }
/** * helper to load nodes relation to document * * @param document relationLink document/link * @param direction "in" or "out" * @return INode instance or null */ private @Nullable INode getRelatedEntity(ODocument document, String direction) { Object nodeO = document.field(direction, ORecordId.class); if (nodeO == null) { logger.error( "Could not create related entity while converting relation with direction " + direction); return null; } if (nodeO instanceof ORecordId) nodeO = repositoryFactory.getDb().load((ORecordId) nodeO); if (nodeO == null) { logger.error("Invalid record in direction " + direction + ": " + document.toString()); return null; } // convert ODocument nodeDoc = (ODocument) nodeO; // slim node: just set title and id INode node = new Node(); node.setTitle(nodeDoc.field("title")); node.setId(nodeDoc.getIdentity().toString()); return node; /* old -not performant String id; if (relationO instanceof OIdentifiable) id = ((ORecordId)relationO).getIdentity().toString(); else { logger.error("Invalid class type: " + relationO.getClass().getName()); return null; } return nodeRepository.find(id);*/ }
public void testAutoConversionOfEmbeddededListWithLinkedClass() { OClass c = database.getMetadata().getSchema().getOrCreateClass("TestConvert"); if (!c.existsProperty("embeddedListWithLinkedClass")) c.createProperty( "embeddedListWithLinkedClass", OType.EMBEDDEDLIST, database.getMetadata().getSchema().getOrCreateClass("TestConvertLinkedClass")); ODocument doc = database .command( new OCommandSQL( "INSERT INTO TestConvert SET name = 'embeddedListWithLinkedClass', embeddedListWithLinkedClass = [{'line1':'123 Fake Street'}]")) .execute(); database .command( new OCommandSQL( "UPDATE " + doc.getIdentity() + " ADD embeddedListWithLinkedClass = [{'line1':'123 Fake Street'}]")) .execute(); doc.reload(); Assert.assertTrue(doc.field("embeddedListWithLinkedClass") instanceof List); Assert.assertEquals(((Collection) doc.field("embeddedListWithLinkedClass")).size(), 2); database .command( new OCommandSQL( "UPDATE " + doc.getIdentity() + " ADD embeddedListWithLinkedClass = {'line1':'123 Fake Street'}")) .execute(); doc.reload(); Assert.assertTrue(doc.field("embeddedListWithLinkedClass") instanceof List); Assert.assertEquals(((Collection) doc.field("embeddedListWithLinkedClass")).size(), 3); List addr = doc.field("embeddedListWithLinkedClass"); for (Object o : addr) { Assert.assertTrue(o instanceof ODocument); Assert.assertEquals(((ODocument) o).getClassName(), "TestConvertLinkedClass"); } }
private static void updateRidMap( final Map<String, Integer> iFetchPlan, final ODocument fieldValue, final int iCurrentLevel, final int iLevelFromRoot, final int iFieldDepthLevel, final Map<ORID, Integer> parsedRecords, final String iFieldPathFromRoot, final OFetchContext iContext) throws IOException { final Integer fetchedLevel = parsedRecords.get(fieldValue.getIdentity()); int currentLevel = iCurrentLevel + 1; int fieldDepthLevel = iFieldDepthLevel; if (iFetchPlan.containsKey(iFieldPathFromRoot)) { currentLevel = 1; fieldDepthLevel = iFetchPlan.get(iFieldPathFromRoot); } if (fetchedLevel == null) { if (!fieldValue.isEmbedded()) { parsedRecords.put(fieldValue.getIdentity(), iLevelFromRoot); } processRecordRidMap( fieldValue, iFetchPlan, currentLevel, iLevelFromRoot, fieldDepthLevel, parsedRecords, iFieldPathFromRoot, iContext); } else if ((!fieldValue.getIdentity().isValid() && fetchedLevel < iLevelFromRoot) || fetchedLevel > iLevelFromRoot) { if (!fieldValue.isEmbedded()) { parsedRecords.put(fieldValue.getIdentity(), iLevelFromRoot); } processRecordRidMap( (ODocument) fieldValue, iFetchPlan, currentLevel, iLevelFromRoot, fieldDepthLevel, parsedRecords, iFieldPathFromRoot, iContext); } }
@SuppressWarnings("unchecked") @Test public void checkVersionsInConnectedDocuments() { ODatabaseDocumentTx db = new ODatabaseDocumentTx(url); db.open("admin", "admin"); db.begin(); ODocument kim = new ODocument("Profile").field("name", "Kim").field("surname", "Bauer"); ODocument teri = new ODocument("Profile").field("name", "Teri").field("surname", "Bauer"); ODocument jack = new ODocument("Profile").field("name", "Jack").field("surname", "Bauer"); ((HashSet<ODocument>) jack.field("following", new HashSet<ODocument>()).field("following")) .add(kim); ((HashSet<ODocument>) kim.field("following", new HashSet<ODocument>()).field("following")) .add(teri); ((HashSet<ODocument>) teri.field("following", new HashSet<ODocument>()).field("following")) .add(jack); jack.save(); db.commit(); db.close(); db.open("admin", "admin"); ODocument loadedJack = db.load(jack.getIdentity()); ORecordVersion jackLastVersion = loadedJack.getRecordVersion().copy(); db.begin(); loadedJack.field("occupation", "agent"); loadedJack.save(); db.commit(); Assert.assertTrue(!jackLastVersion.equals(loadedJack.getRecordVersion())); loadedJack = db.load(jack.getIdentity()); Assert.assertTrue(!jackLastVersion.equals(loadedJack.getRecordVersion())); db.close(); db.open("admin", "admin"); loadedJack = db.load(jack.getIdentity()); Assert.assertTrue(!jackLastVersion.equals(loadedJack.getRecordVersion())); db.close(); }
public void testIndexMap() { final ODocument docOne = new ODocument(); docOne.save(); final ODocument docTwo = new ODocument(); docTwo.save(); Map<String, ORID> map = new HashMap<String, ORID>(); map.put("key1", docOne.getIdentity()); map.put("key2", docTwo.getIdentity()); final ODocument document = new ODocument("LinkMapIndexTestClass"); document.field("linkMap", map); document.save(); final List<ODocument> resultByKey = database.command(new OCommandSQL("select key, rid from index:mapIndexTestKey")).execute(); Assert.assertNotNull(resultByKey); Assert.assertEquals(resultByKey.size(), 2); for (ODocument d : resultByKey) { Assert.assertTrue(d.containsField("key")); Assert.assertTrue(d.containsField("rid")); if (!d.field("key").equals("key1") && !d.field("key").equals("key2")) { Assert.fail("Unknown key found: " + d.field("key")); } } final List<ODocument> resultByValue = database.command(new OCommandSQL("select key, rid from index:mapIndexTestValue")).execute(); Assert.assertNotNull(resultByValue); Assert.assertEquals(resultByValue.size(), 2); for (ODocument d : resultByValue) { Assert.assertTrue(d.containsField("key")); Assert.assertTrue(d.containsField("rid")); if (!d.field("key").equals(docOne.getIdentity()) && !d.field("key").equals(docTwo.getIdentity())) { Assert.fail("Unknown key found: " + d.field("key")); } } }
public void testIndexMapRemoveItemInTxRollback() throws Exception { final ODocument docOne = new ODocument(); docOne.save(); final ODocument docTwo = new ODocument(); docTwo.save(); final ODocument docThree = new ODocument(); docThree.save(); Map<String, ORID> map = new HashMap<String, ORID>(); map.put("key1", docOne.getIdentity()); map.put("key2", docTwo.getIdentity()); map.put("key3", docThree.getIdentity()); final ODocument document = new ODocument("LinkMapIndexTestClass"); document.field("linkMap", map); document.save(); database.begin(); final ODocument loadedDocument = database.load(document.getIdentity()); loadedDocument.<Map<String, ORID>>field("linkMap").remove("key2"); loadedDocument.save(); database.rollback(); final List<ODocument> resultByKey = database.command(new OCommandSQL("select key, rid from index:mapIndexTestKey")).execute(); Assert.assertNotNull(resultByKey); Assert.assertEquals(resultByKey.size(), 3); for (ODocument d : resultByKey) { Assert.assertTrue(d.containsField("key")); Assert.assertTrue(d.containsField("rid")); if (!d.field("key").equals("key1") && !d.field("key").equals("key2") && !d.field("key").equals("key3")) { Assert.fail("Unknown key found: " + d.field("key")); } } final List<ODocument> resultByValue = database.command(new OCommandSQL("select key, rid from index:mapIndexTestValue")).execute(); Assert.assertNotNull(resultByValue); Assert.assertEquals(resultByValue.size(), 3); for (ODocument d : resultByValue) { Assert.assertTrue(d.containsField("key")); Assert.assertTrue(d.containsField("rid")); if (!d.field("key").equals(docOne.getIdentity()) && !d.field("key").equals(docTwo.getIdentity()) && !d.field("key").equals(docThree.getIdentity())) { Assert.fail("Unknown key found: " + d.field("key")); } } }
/** * Deletes the specified object from the object set. * * <p>{@inheritDoc} * * @throws NotFoundException if the specified object could not be found. * @throws ForbiddenException if access to the object is forbidden. * @throws ConflictException if version is required but is {@code null}. * @throws PreconditionFailedException if version did not match the existing object in the set. */ @Override public ResourceResponse delete(DeleteRequest request) throws ResourceException { if (request.getResourcePathObject().size() < 2) { throw new NotFoundException( "The object identifier did not include sufficient information to determine the object type and identifier of the object to update: " + request.getResourcePath()); } if (request.getRevision() == null || "".equals(request.getRevision())) { throw new ConflictException( "Object passed into delete does not have revision it expects set."); } final String type = request.getResourcePathObject().parent().toString(); final String localId = request.getResourcePathObject().leaf(); int ver = DocumentUtil.parseVersion( request.getRevision()); // This throws ConflictException if parse fails ODatabaseDocumentTx db = getConnection(); try { ODocument existingDoc = predefinedQueries.getByID(localId, type, db); if (existingDoc == null) { throw new NotFoundException( "Object does not exist for delete on: " + request.getResourcePath()); } db.delete(existingDoc.getIdentity(), new OSimpleVersion(ver)); logger.debug("delete for id succeeded: {} revision: {}", localId, request.getRevision()); return DocumentUtil.toResource(existingDoc); } catch (ODatabaseException ex) { // Without transaction the concurrent modification exception gets nested instead if (isCauseConcurrentModificationException(ex, 10)) { throw new PreconditionFailedException( "Delete rejected as current Object revision is different than expected by caller, the object has changed since retrieval. " + ex.getMessage(), ex); } else { throw ex; } } catch (OConcurrentModificationException ex) { throw new PreconditionFailedException( "Delete rejected as current Object revision is different than expected by caller, the object has changed since retrieval." + ex.getMessage(), ex); } catch (RuntimeException e) { throw e; } finally { if (db != null) { db.close(); } } }
@Test(dependsOnMethods = "updateCollectionsRemoveWithWhereOperator") public void updateCollectionsWithSetOperator() { List<ODocument> docs = database.query(new OSQLSynchQuery<ODocument>("select from Account")); List<Long> positions = getValidPositions(addressClusterId); for (ODocument doc : docs) { final int records = database .command( new OCommandSQL( "update Account set addresses = [#" + addressClusterId + ":" + positions.get(0) + ", #" + addressClusterId + ":" + positions.get(1) + ",#" + addressClusterId + ":" + positions.get(2) + "] where @rid = " + doc.getIdentity())) .execute(); Assert.assertEquals(records, 1); ODocument loadedDoc = database.load(doc.getIdentity(), "*:-1", true); Assert.assertEquals(((List<?>) loadedDoc.field("addresses")).size(), 3); Assert.assertEquals( ((OIdentifiable) ((List<?>) loadedDoc.field("addresses")).get(0)) .getIdentity() .toString(), "#" + addressClusterId + ":" + positions.get(0)); loadedDoc.field("addresses", doc.field("addresses")); database.save(loadedDoc); } }
private void create() { for (int i = 0; i < ITERATIONS; ++i) { final int selectedClusterId = clusterIds[((int) (Math.abs(hashFunction.hashCode(i)) % clusterIds.length))]; ODocument sqlRecord = database .command(new OCommandSQL("insert into AutoShardingTest (id) values (" + i + ")")) .execute(); Assert.assertEquals(sqlRecord.getIdentity().getClusterId(), selectedClusterId); ODocument apiRecord = new ODocument("AutoShardingTest").field("id", i).save(); Assert.assertEquals(apiRecord.getIdentity().getClusterId(), selectedClusterId); } // TEST ALL CLUSTER HAVE RECORDS for (int clusterId : cls.getClusterIds()) { Assert.assertTrue(database.countClusterElements(clusterId) > 0); } }
@Test public void testUnwindOrder() { List<ODocument> qResult = db.command(new OCommandSQL("select from unwindtest order by coll unwind coll")).execute(); assertEquals(qResult.size(), 4); for (ODocument doc : qResult) { String name = doc.field("name"); String coll = doc.field("coll"); assertTrue(coll.startsWith(name)); assertFalse(doc.getIdentity().isPersistent()); } }
private List<Long> getValidPositions(int clusterId) { final List<Long> positions = new ArrayList<Long>(); final ORecordIteratorCluster<ODocument> iteratorCluster = database.browseCluster(database.getClusterNameById(clusterId)); for (int i = 0; i < 7; i++) { if (!iteratorCluster.hasNext()) break; ODocument doc = iteratorCluster.next(); positions.add(doc.getIdentity().getClusterPosition()); } return positions; }
@Test public void test3RollbackWithCopyCacheStrategy() throws IOException { database1 = new ODatabaseDocumentTx(url).open("admin", "admin"); database2 = new ODatabaseDocumentTx(url).open("admin", "admin"); database1.getLevel2Cache().setStrategy(STRATEGY.COPY_RECORD); // Create docA. ODocument vDocA_db1 = database1.newInstance(); vDocA_db1.field(NAME, "docA"); database1.save(vDocA_db1); // Keep the IDs. ORID vDocA_Rid = vDocA_db1.getIdentity().copy(); database2.begin(TXTYPE.OPTIMISTIC); try { // Get docA and update in db2 transaction context ODocument vDocA_db2 = database2.load(vDocA_Rid); vDocA_db2.field(NAME, "docA_v2"); database2.save(vDocA_db2); database1.begin(TXTYPE.OPTIMISTIC); try { vDocA_db1.field(NAME, "docA_v3"); database1.save(vDocA_db1); database1.commit(); } catch (OConcurrentModificationException e) { Assert.fail("Should not failed here..."); } Assert.assertEquals(vDocA_db1.field(NAME), "docA_v3"); // Will throw OConcurrentModificationException database2.commit(); Assert.fail("Should throw OConcurrentModificationException"); } catch (OConcurrentModificationException e) { database2.rollback(); } // Force reload all (to be sure it is not a cache problem) database1.close(); database2.close(); database2 = new ODatabaseDocumentTx(url).open("admin", "admin"); // docB should be in the last state : "docA_v3" ODocument vDocB_db2 = database2.load(vDocA_Rid); Assert.assertEquals(vDocB_db2.field(NAME), "docA_v3"); database1.close(); database2.close(); }
@Test public void testQuery() { create(); for (int i = 0; i < ITERATIONS; ++i) { final int selectedClusterId = clusterIds[((int) (Math.abs(hashFunction.hashCode(i)) % clusterIds.length))]; Iterable<ODocument> resultSet = database.command(new OCommandSQL("select from AutoShardingTest where id = ?")).execute(i); Assert.assertTrue(resultSet.iterator().hasNext()); final ODocument sqlRecord = resultSet.iterator().next(); Assert.assertEquals(sqlRecord.getIdentity().getClusterId(), selectedClusterId); } }
public void updateWithReturn() { ODocument doc = new ODocument("Data"); doc.field("name", "Pawel"); doc.field("city", "Wroclaw"); doc.field("really_big_field", "BIIIIIIIIIIIIIIIGGGGGGG!!!"); doc.save(); // check AFTER String sqlString = "UPDATE " + doc.getIdentity().toString() + " SET gender='male' RETURN AFTER"; List<ODocument> result1 = database.command(new OCommandSQL(sqlString)).execute(); Assert.assertEquals(result1.size(), 1); Assert.assertEquals(result1.get(0).getIdentity(), doc.getIdentity()); Assert.assertEquals((String) result1.get(0).field("gender"), "male"); final ODocument lastOne = result1.get(0).copy(); // check record attributes and BEFORE sqlString = "UPDATE " + doc.getIdentity().toString() + " SET Age=1 RETURN BEFORE @this"; result1 = database.command(new OCommandSQL(sqlString)).execute(); Assert.assertEquals(result1.size(), 1); Assert.assertEquals(lastOne.getVersion(), result1.get(0).getVersion()); Assert.assertFalse(result1.get(0).containsField("Age")); // check INCREMENT, AFTER + $current + field sqlString = "UPDATE " + doc.getIdentity().toString() + " INCREMENT Age = 100 RETURN AFTER $current.Age"; result1 = database.command(new OCommandSQL(sqlString)).execute(); Assert.assertEquals(result1.size(), 1); Assert.assertTrue(result1.get(0).containsField("value")); Assert.assertEquals(result1.get(0).field("value"), 101); // check exclude + WHERE + LIMIT sqlString = "UPDATE " + doc.getIdentity().toString() + " INCREMENT Age = 100 RETURN AFTER $current.Exclude('really_big_field') WHERE Age=101 LIMIT 1"; result1 = database.command(new OCommandSQL(sqlString)).execute(); Assert.assertEquals(result1.size(), 1); Assert.assertTrue(result1.get(0).containsField("Age")); Assert.assertEquals(result1.get(0).field("Age"), 201); Assert.assertFalse(result1.get(0).containsField("really_big_field")); }
@Test(dependsOnMethods = "updateCollectionsRemoveWithWhereOperator") public void updateMapsWithSetOperator() { ODocument doc = database .command( new OCommandSQL( "insert into cluster:default (equaledges, name, properties) values ('no', 'circleUpdate', {'round':'eeee', 'blaaa':'zigzag'} )")) .execute(); Integer records = database .command( new OCommandSQL( "update " + doc.getIdentity() + " set properties = {'roundOne':'ffff', 'bla':'zagzig','testTestTEST':'okOkOK'}")) .execute(); Assert.assertEquals(records.intValue(), 1); ODocument loadedDoc = database.load(doc.getIdentity(), "*:-1", true); Assert.assertTrue(loadedDoc.field("properties") instanceof Map); @SuppressWarnings("unchecked") Map<Object, Object> entries = loadedDoc.field("properties"); Assert.assertEquals(entries.size(), 3); Assert.assertNull(entries.get("round")); Assert.assertNull(entries.get("blaaa")); Assert.assertEquals(entries.get("roundOne"), "ffff"); Assert.assertEquals(entries.get("bla"), "zagzig"); Assert.assertEquals(entries.get("testTestTEST"), "okOkOK"); }