package com.orientechnologies.orient.core.sql.functions.sequence;

import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.sql.filter.OSQLFilterItem;
import com.orientechnologies.orient.core.sql.functions.OSQLFunctionConfigurableAbstract;

/**
 * Returns a sequence by name.
 * 
 * @author Luca Garulli
 */
public class OSQLFunctionSequence extends OSQLFunctionConfigurableAbstract {
  public static final String NAME = "sequence";

  public OSQLFunctionSequence() {
    super(NAME, 1, 1);
  }

  @Override
  public Object execute(Object iThis, OIdentifiable iCurrentRecord, Object iCurrentResult, Object[] iParams,
      OCommandContext iContext) {
    final String seqName;
    if (configuredParameters[0] instanceof OSQLFilterItem)
      seqName = (String) ((OSQLFilterItem) configuredParameters[0]).getValue(iCurrentRecord, iCurrentResult, iContext);
    else
      seqName = configuredParameters[0].toString();

    return ODatabaseRecordThreadLocal.INSTANCE.get().getMetadata().getSequenceLibrary().getSequence(seqName);
  }

  @Override
  public Object getResult() {
    return null;
  }

  @Override
  public String getSyntax() {
    return "sequence(<name>)";
  }

  @Override
  public boolean aggregateResults() {
    return false;
  }

}

@@ -264,16 +264,165 @@
 fiable;%0A
+import com.orientechnologies.orient.core.exception.OCommandExecutionException;%0Aimport com.orientechnologies.orient.core.metadata.sequence.OSequence;%0A
 import c
@@ -608,17 +608,16 @@
 name.%0A *
- 
 %0A * @aut
@@ -1251,22 +1251,34 @@
 );%0A%0A    
-return
+OSequence result =
  ODataba
@@ -1369,16 +1369,145 @@
 qName);%0A
+    if (result == null) %7B%0A      throw new OCommandExecutionException(%22Sequence not found: %22 + seqName);%0A    %7D%0A    return result;%0A
   %7D%0A%0A  @

Throw exception on SELECT sequence("seqName").next() if the sequence does not exist