Search in sources :

Example 1 with AttributeReference

use of com.torodb.core.language.AttributeReference in project torodb by torodb.

the class IndexedAttributes method toString.

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    for (AttributeReference attribute : attributes) {
        sb.append(attribute).append(' ');
        sb.append("(");
        sb.append(orderingInfo.get(attribute).name());
        sb.append(")");
        sb.append(", ");
    }
    sb.delete(sb.length() - 2, sb.length());
    return sb.toString();
}
Also used : AttributeReference(com.torodb.core.language.AttributeReference)

Example 2 with AttributeReference

use of com.torodb.core.language.AttributeReference in project torodb by torodb.

the class ToroIndexConverter method from.

@Override
public NamedToroIndex from(String databaseObject) {
    JsonReader reader = Json.createReader(new StringReader(databaseObject));
    JsonObject object = reader.readObject();
    IndexedAttributes.Builder builder = new IndexedAttributes.Builder();
    JsonArray attsArray = object.getJsonArray(ATTS_KEY);
    Set<Integer> descendingAttPos;
    if (object.containsKey(DESCENDING)) {
        JsonArray descArray = object.getJsonArray(DESCENDING);
        descendingAttPos = Sets.newHashSetWithExpectedSize(descArray.size());
        for (int i = 0; i < descArray.size(); i++) {
            descendingAttPos.add(descArray.getInt(i));
        }
    } else {
        descendingAttPos = Collections.emptySet();
    }
    for (int i = 0; i < attsArray.size(); i++) {
        String att = attsArray.getString(i);
        AttributeReference attRef = parseAttRef(att);
        if (descendingAttPos.contains(i)) {
            builder.addAttribute(attRef, IndexType.desc);
        } else {
            builder.addAttribute(attRef, IndexType.asc);
        }
    }
    return new DefaultNamedToroIndex(object.getString(NAME_KEY), builder.build(), databaseName, collectionName, object.getBoolean(UNIQUE_KEY, false));
}
Also used : DefaultNamedToroIndex(com.torodb.core.model.DefaultNamedToroIndex) IndexedAttributes(com.torodb.core.model.IndexedAttributes) AttributeReference(com.torodb.core.language.AttributeReference) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonObjectBuilder(javax.json.JsonObjectBuilder) JsonObject(javax.json.JsonObject) JsonArray(javax.json.JsonArray) StringReader(java.io.StringReader) JsonReader(javax.json.JsonReader)

Example 3 with AttributeReference

use of com.torodb.core.language.AttributeReference in project torodb by torodb.

the class InsertImplementation method apply.

@Override
public Status<InsertResult> apply(Request req, Command<? super InsertArgument, ? super InsertResult> command, InsertArgument arg, WriteMongodTransaction context) {
    mongodMetrics.getInserts().mark(arg.getDocuments().size());
    Stream<KvDocument> docsToInsert = arg.getDocuments().stream().map(FromBsonValueTranslator.getInstance()).map((v) -> (KvDocument) v);
    try {
        if (!context.getTorodTransaction().existsCollection(req.getDatabase(), arg.getCollection())) {
            context.getTorodTransaction().createIndex(req.getDatabase(), arg.getCollection(), Constants.ID_INDEX, ImmutableList.<IndexFieldInfo>of(new IndexFieldInfo(new AttributeReference(Arrays.asList(new Key[] { new ObjectKey(Constants.ID) })), FieldIndexOrdering.ASC.isAscending())), true);
        }
        context.getTorodTransaction().insert(req.getDatabase(), arg.getCollection(), docsToInsert);
    } catch (UserException ex) {
        //TODO: Improve error reporting
        return Status.from(ErrorCode.COMMAND_FAILED, ex.getLocalizedMessage());
    }
    return Status.ok(new InsertResult(arg.getDocuments().size()));
}
Also used : KvDocument(com.torodb.kvdocument.values.KvDocument) InsertResult(com.torodb.mongodb.commands.signatures.general.InsertCommand.InsertResult) AttributeReference(com.torodb.core.language.AttributeReference) ObjectKey(com.torodb.core.language.AttributeReference.ObjectKey) IndexFieldInfo(com.torodb.torod.IndexFieldInfo) UserException(com.torodb.core.exceptions.user.UserException)

Example 4 with AttributeReference

use of com.torodb.core.language.AttributeReference in project torodb by torodb.

the class UpdateImplementation method apply.

@Override
public Status<UpdateResult> apply(Request req, Command<? super UpdateArgument, ? super UpdateResult> command, UpdateArgument arg, WriteMongodTransaction context) {
    UpdateStatus updateStatus = new UpdateStatus();
    try {
        if (!context.getTorodTransaction().existsCollection(req.getDatabase(), arg.getCollection())) {
            context.getTorodTransaction().createIndex(req.getDatabase(), arg.getCollection(), Constants.ID_INDEX, ImmutableList.<IndexFieldInfo>of(new IndexFieldInfo(new AttributeReference(Arrays.asList(new Key[] { new ObjectKey(Constants.ID) })), FieldIndexOrdering.ASC.isAscending())), true);
        }
        for (UpdateStatement updateStatement : arg.getStatements()) {
            BsonDocument query = updateStatement.getQuery();
            UpdateAction updateAction = UpdateActionTranslator.translate(updateStatement.getUpdate());
            Cursor<ToroDocument> candidatesCursor;
            switch(query.size()) {
                case 0:
                    {
                        candidatesCursor = context.getTorodTransaction().findAll(req.getDatabase(), arg.getCollection()).asDocCursor();
                        break;
                    }
                case 1:
                    {
                        try {
                            candidatesCursor = findByAttribute(context.getTorodTransaction(), req.getDatabase(), arg.getCollection(), query);
                        } catch (CommandFailed ex) {
                            return Status.from(ex);
                        }
                        break;
                    }
                default:
                    {
                        return Status.from(ErrorCode.COMMAND_FAILED, "The given query is not supported right now");
                    }
            }
            if (candidatesCursor.hasNext()) {
                try {
                    Stream<List<ToroDocument>> candidatesbatchStream;
                    if (updateStatement.isMulti()) {
                        candidatesbatchStream = StreamSupport.stream(Spliterators.spliteratorUnknownSize(candidatesCursor.batch(100), Spliterator.ORDERED), false);
                    } else {
                        candidatesbatchStream = Stream.of(ImmutableList.of(candidatesCursor.next()));
                    }
                    Stream<KvDocument> updatedCandidates = candidatesbatchStream.map(candidates -> {
                        updateStatus.increaseCandidates(candidates.size());
                        context.getTorodTransaction().delete(req.getDatabase(), arg.getCollection(), candidates);
                        return candidates;
                    }).flatMap(l -> l.stream()).map(candidate -> {
                        try {
                            updateStatus.increaseUpdated();
                            return update(updateAction, candidate);
                        } catch (UserException userException) {
                            throw new UserWrappedException(userException);
                        }
                    });
                    context.getTorodTransaction().insert(req.getDatabase(), arg.getCollection(), updatedCandidates);
                } catch (UserWrappedException userWrappedException) {
                    throw userWrappedException.getCause();
                }
            } else if (updateStatement.isUpsert()) {
                KvDocument toInsertCandidate;
                if (updateAction instanceof SetDocumentUpdateAction) {
                    toInsertCandidate = ((SetDocumentUpdateAction) updateAction).getNewValue();
                } else {
                    toInsertCandidate = update(updateAction, new ToroDocument(-1, (KvDocument) MongoWpConverter.translate(query)));
                }
                if (!toInsertCandidate.containsKey(Constants.ID)) {
                    KvDocument.Builder builder = new KvDocument.Builder();
                    for (DocEntry<?> entry : toInsertCandidate) {
                        builder.putValue(entry.getKey(), entry.getValue());
                    }
                    builder.putValue(Constants.ID, MongoWpConverter.translate(objectIdFactory.consumeObjectId()));
                    toInsertCandidate = builder.build();
                }
                updateStatus.increaseCandidates(1);
                updateStatus.increaseCreated(toInsertCandidate.get(Constants.ID));
                Stream<KvDocument> toInsertCandidates = Stream.of(toInsertCandidate);
                context.getTorodTransaction().insert(req.getDatabase(), arg.getCollection(), toInsertCandidates);
            }
        }
    } catch (UserException ex) {
        //TODO: Improve error reporting
        return Status.from(ErrorCode.COMMAND_FAILED, ex.getLocalizedMessage());
    }
    mongodMetrics.getUpdateModified().mark(updateStatus.updated);
    mongodMetrics.getUpdateMatched().mark(updateStatus.candidates);
    mongodMetrics.getUpdateUpserted().mark(updateStatus.upsertResults.size());
    return Status.ok(new UpdateResult(updateStatus.updated, updateStatus.candidates, ImmutableList.copyOf(updateStatus.upsertResults)));
}
Also used : Request(com.eightkdata.mongowp.server.api.Request) UpdateActionTranslator(com.torodb.mongodb.language.UpdateActionTranslator) Arrays(java.util.Arrays) UpdatedToroDocumentBuilder(com.torodb.mongodb.language.update.UpdatedToroDocumentBuilder) FieldIndexOrdering(com.torodb.core.transaction.metainf.FieldIndexOrdering) Spliterators(java.util.Spliterators) BsonDocument(com.eightkdata.mongowp.bson.BsonDocument) WriteTorodbCommandImpl(com.torodb.mongodb.commands.impl.WriteTorodbCommandImpl) UpdateAction(com.torodb.mongodb.language.update.UpdateAction) UpdateStatement(com.torodb.mongodb.commands.signatures.general.UpdateCommand.UpdateStatement) Singleton(javax.inject.Singleton) ToroDocument(com.torodb.core.document.ToroDocument) UpdateResult(com.torodb.mongodb.commands.signatures.general.UpdateCommand.UpdateResult) ArrayList(java.util.ArrayList) ObjectKey(com.torodb.core.language.AttributeReference.ObjectKey) IndexFieldInfo(com.torodb.torod.IndexFieldInfo) Inject(javax.inject.Inject) KvValue(com.torodb.kvdocument.values.KvValue) ImmutableList(com.google.common.collect.ImmutableList) MongoWpConverter(com.torodb.kvdocument.conversion.mongowp.MongoWpConverter) StreamSupport(java.util.stream.StreamSupport) Builder(com.torodb.core.language.AttributeReference.Builder) ErrorCode(com.eightkdata.mongowp.ErrorCode) CommandFailed(com.eightkdata.mongowp.exceptions.CommandFailed) UpdateException(com.torodb.core.exceptions.user.UpdateException) SharedWriteTorodTransaction(com.torodb.torod.SharedWriteTorodTransaction) AttributeReference(com.torodb.core.language.AttributeReference) Constants(com.torodb.mongodb.language.Constants) Cursor(com.torodb.core.cursors.Cursor) KvDocument(com.torodb.kvdocument.values.KvDocument) UpsertResult(com.torodb.mongodb.commands.signatures.general.UpdateCommand.UpsertResult) Command(com.eightkdata.mongowp.server.api.Command) UserException(com.torodb.core.exceptions.user.UserException) SetDocumentUpdateAction(com.torodb.mongodb.language.update.SetDocumentUpdateAction) ObjectIdFactory(com.torodb.mongodb.language.ObjectIdFactory) DocEntry(com.torodb.kvdocument.values.KvDocument.DocEntry) MongodMetrics(com.torodb.mongodb.core.MongodMetrics) WriteMongodTransaction(com.torodb.mongodb.core.WriteMongodTransaction) List(java.util.List) Stream(java.util.stream.Stream) Status(com.eightkdata.mongowp.Status) UserWrappedException(com.torodb.core.exceptions.UserWrappedException) UpdateArgument(com.torodb.mongodb.commands.signatures.general.UpdateCommand.UpdateArgument) Spliterator(java.util.Spliterator) Key(com.torodb.core.language.AttributeReference.Key) KvDocument(com.torodb.kvdocument.values.KvDocument) UpdateStatement(com.torodb.mongodb.commands.signatures.general.UpdateCommand.UpdateStatement) UpdateAction(com.torodb.mongodb.language.update.UpdateAction) SetDocumentUpdateAction(com.torodb.mongodb.language.update.SetDocumentUpdateAction) AttributeReference(com.torodb.core.language.AttributeReference) UpdatedToroDocumentBuilder(com.torodb.mongodb.language.update.UpdatedToroDocumentBuilder) Builder(com.torodb.core.language.AttributeReference.Builder) ObjectKey(com.torodb.core.language.AttributeReference.ObjectKey) DocEntry(com.torodb.kvdocument.values.KvDocument.DocEntry) BsonDocument(com.eightkdata.mongowp.bson.BsonDocument) UserWrappedException(com.torodb.core.exceptions.UserWrappedException) ToroDocument(com.torodb.core.document.ToroDocument) CommandFailed(com.eightkdata.mongowp.exceptions.CommandFailed) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) Stream(java.util.stream.Stream) IndexFieldInfo(com.torodb.torod.IndexFieldInfo) UserException(com.torodb.core.exceptions.user.UserException) UpdateResult(com.torodb.mongodb.commands.signatures.general.UpdateCommand.UpdateResult) SetDocumentUpdateAction(com.torodb.mongodb.language.update.SetDocumentUpdateAction)

Example 5 with AttributeReference

use of com.torodb.core.language.AttributeReference in project torodb by torodb.

the class UpdateActionTranslator method translateMultiply.

private static void translateMultiply(CompositeUpdateAction.Builder builder, BsonDocument argument) throws UpdateException {
    for (Entry<?> entry : argument) {
        Collection<AttributeReference> attRefs = parseAttributeReference(entry.getKey());
        KvValue<?> translatedValue = MongoWpConverter.translate(entry.getValue());
        if (!(translatedValue instanceof KvNumeric)) {
            throw new UpdateException("Cannot multiply with a " + "non-numeric argument");
        }
        builder.add(new MultiplyUpdateAction(attRefs, (KvNumeric<?>) translatedValue), false);
    }
}
Also used : KvNumeric(com.torodb.kvdocument.values.KvNumeric) AttributeReference(com.torodb.core.language.AttributeReference) UpdateException(com.torodb.core.exceptions.user.UpdateException) MultiplyUpdateAction(com.torodb.mongodb.language.update.MultiplyUpdateAction)

Aggregations

AttributeReference (com.torodb.core.language.AttributeReference)21 IndexFieldInfo (com.torodb.torod.IndexFieldInfo)6 UserException (com.torodb.core.exceptions.user.UserException)5 ObjectKey (com.torodb.core.language.AttributeReference.ObjectKey)5 UpdateException (com.torodb.core.exceptions.user.UpdateException)4 FieldIndexOrdering (com.torodb.core.transaction.metainf.FieldIndexOrdering)4 ArrayList (java.util.ArrayList)4 Test (org.junit.Test)4 CommandFailed (com.eightkdata.mongowp.exceptions.CommandFailed)2 ImmutableList (com.google.common.collect.ImmutableList)2 UnsupportedCompoundIndexException (com.torodb.core.exceptions.user.UnsupportedCompoundIndexException)2 UnsupportedUniqueIndexException (com.torodb.core.exceptions.user.UnsupportedUniqueIndexException)2 KvDocument (com.torodb.kvdocument.values.KvDocument)2 KvNumeric (com.torodb.kvdocument.values.KvNumeric)2 IndexOptions (com.torodb.mongodb.commands.pojos.index.IndexOptions)2 AscIndexType (com.torodb.mongodb.commands.pojos.index.type.AscIndexType)2 DescIndexType (com.torodb.mongodb.commands.pojos.index.type.DescIndexType)2 IndexType (com.torodb.mongodb.commands.pojos.index.type.IndexType)2 CreateIndexesResult (com.torodb.mongodb.commands.signatures.admin.CreateIndexesCommand.CreateIndexesResult)2 JsonArrayBuilder (javax.json.JsonArrayBuilder)2