Пример #1
0
  /**
   * Get a BigDecimal representing the value of a DataValueDescriptor
   *
   * @param value Non-null value to be converted
   * @return BigDecimal value
   * @throws StandardException Invalid conversion or out of range.
   */
  public static BigDecimal getBigDecimal(DataValueDescriptor value) throws StandardException {
    if (SanityManager.DEBUG) {
      if (value.isNull())
        SanityManager.THROWASSERT("NULL value passed to SQLDecimal.getBigDecimal");
    }

    switch (value.typeToBigDecimal()) {
      case Types.DECIMAL:
        return (BigDecimal) value.getObject();
      case Types.CHAR:
        try {
          return new BigDecimal(value.getString().trim());
        } catch (NumberFormatException nfe) {
          throw StandardException.newException(
              SQLState.LANG_FORMAT_EXCEPTION, "java.math.BigDecimal");
        }
      case Types.BIGINT:
        return BigDecimal.valueOf(value.getLong());
      default:
        if (SanityManager.DEBUG)
          SanityManager.THROWASSERT(
              "invalid return from "
                  + value.getClass()
                  + ".typeToBigDecimal() "
                  + value.typeToBigDecimal());
        return null;
    }
  }
Пример #2
0
 /**
  * Write this object to a stream of stored objects.
  *
  * @param out write bytes here.
  * @exception IOException thrown on error
  */
 public void writeExternal(ObjectOutput out) throws IOException {
   if (SanityManager.DEBUG) {
     SanityManager.ASSERT(triggerSchemaId != null, "triggerSchemaId expected to be non-null");
     SanityManager.ASSERT(triggerTableId != null, "triggerTableId expected to be non-null");
   }
   out.writeObject(id);
   out.writeObject(name);
   out.writeObject(triggerSchemaId);
   out.writeObject(triggerTableId);
   out.writeInt(eventMask);
   out.writeBoolean(isBefore);
   out.writeBoolean(isRow);
   out.writeBoolean(isEnabled);
   out.writeObject(whenSPSId);
   out.writeObject(actionSPSId);
   if (referencedCols == null) {
     out.writeInt(0);
   } else {
     out.writeInt(referencedCols.length);
     for (int i = 0; i < referencedCols.length; i++) {
       out.writeInt(referencedCols[i]);
     }
   }
   out.writeObject(triggerDefinition);
   out.writeBoolean(referencingOld);
   out.writeBoolean(referencingNew);
   out.writeObject(oldReferencingName);
   out.writeObject(newReferencingName);
 }
  /**
   * Constructor
   *
   * @param activation The activation
   * @param source Source result set
   * @param rowAllocator
   * @param resultSetNumber The resultSetNumber
   * @param erdNumber Int for ResultDescription (so it can be turned back into an object)
   * @param restriction Restriction
   * @param optimizerEstimatedRowCount The optimizer's estimated number of rows.
   * @param optimizerEstimatedCost The optimizer's estimated cost
   */
  WindowResultSet(
      Activation activation,
      NoPutResultSet source,
      int rowAllocator,
      int resultSetNumber,
      int erdNumber,
      GeneratedMethod restriction,
      double optimizerEstimatedRowCount,
      double optimizerEstimatedCost)
      throws StandardException {

    super(activation, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost);

    if (SanityManager.DEBUG) {
      SanityManager.ASSERT(activation != null, "activation expected to be non-null");
      SanityManager.ASSERT(resultSetNumber >= 0, "resultSetNumber expected to be >= 0");
    }

    this.restriction = restriction;
    this.source = source;
    this.rownumber = 0;

    ExecPreparedStatement ps = activation.getPreparedStatement();

    this.allocatedRow =
        ((ExecRowBuilder) ps.getSavedObject(rowAllocator)).build(activation.getExecutionFactory());

    if (erdNumber != -1) {
      this.referencedColumns = (FormatableBitSet) ps.getSavedObject(erdNumber);
    }

    recordConstructorTime();
  }
  /**
   * restore the before image of the page
   *
   * @exception StandardException Standard Derby Error Policy
   * @exception IOException problem reading the complete log record from the input stream
   */
  public void restoreMe(
      Transaction xact, BasePage undoPage, LogInstant CLRInstant, LimitObjectInput in)
      throws StandardException, IOException {
    int slot = undoPage.findRecordById(recordId, Page.FIRST_SLOT_NUMBER);
    if (SanityManager.DEBUG) {
      if (!getPageId().equals(undoPage.getPageId()))
        SanityManager.THROWASSERT(
            "restoreMe cannot restore to a different page. "
                + "doMe page:"
                + getPageId()
                + " undoPage:"
                + undoPage.getPageId());
      if (slot != doMeSlot)
        SanityManager.THROWASSERT(
            "restoreMe cannot restore to a different slot. "
                + "doMe slot:"
                + doMeSlot
                + " undoMe slot: "
                + slot
                + " recordId:"
                + recordId);
    }

    undoPage.skipField(in); // skip the after image of the column
    undoPage.storeField(CLRInstant, slot, fieldId, in);
    undoPage.setAuxObject(null);
  }
  /**
   * Restore field to its old value.
   *
   * @exception IOException Can be thrown by any of the methods of ObjectInput.
   * @exception StandardException Standard Derby policy.
   * @see LogicalPageOperation#undoMe
   */
  public void undoMe(
      Transaction xact,
      BasePage undoPage,
      int undoRecordId,
      LogInstant CLRInstant,
      LimitObjectInput in)
      throws StandardException, IOException {
    int slot = undoPage.findRecordById(undoRecordId, Page.FIRST_SLOT_NUMBER);

    if (SanityManager.DEBUG) {
      // if the record Id has changed, the page had better changed
      // this can only happen during recovery since in run time undo,
      // this resetRecordHandle gets called and this object have the new
      // page number and recordId
      if (undoRecordId != this.recordId)
        if (undoPage.getPageNumber() == getPageId().getPageNumber())
          SanityManager.THROWASSERT(
              "recordId changed from "
                  + this.recordId
                  + " to "
                  + undoRecordId
                  + " but page number did not change "
                  + undoPage.getPageNumber());

      if (slot == -1)
        SanityManager.THROWASSERT(
            "recordId " + undoRecordId + " not found on page " + undoPage.getPageNumber());
    }

    undoPage.skipField((java.io.ObjectInput) in); // skip the after image of the column
    undoPage.storeField(CLRInstant, slot, fieldId, in);
    undoPage.setAuxObject(null);
  }
  /**
   * Write the old column value and and new column value as optional data. If logical undo, writes
   * out the entire row's before image.
   *
   * @exception IOException Can be thrown by any of the methods of ObjectOutput.
   * @exception StandardException Standard Derby policy.
   */
  private void writeOptionalDataToBuffer(RawTransaction t, Object column)
      throws StandardException, IOException {

    if (SanityManager.DEBUG) {
      SanityManager.ASSERT(this.page != null);
    }

    DynamicByteArrayOutputStream logBuffer = t.getLogBuffer();
    int optionalDataStart = logBuffer.getPosition();

    if (SanityManager.DEBUG) {
      SanityManager.ASSERT(
          optionalDataStart == 0, "Buffer for writing optional data should start at position 0");
    }

    this.page.logColumn(doMeSlot, fieldId, column, logBuffer, 100); // the after image of the column
    this.page.logField(doMeSlot, fieldId, logBuffer); // the BI of the column
    if (undo != null) {
      // RESOLVE: we want the AFTER image of the row, not the BEFORE
      // image.   This works for now because only btree needs a logical
      // undoable updateField and it always update only the pointer field
      // to point to something else.
      //
      // But in the future, it needs to be changed.

      this.page.logRecord(
          doMeSlot,
          BasePage.LOG_RECORD_DEFAULT,
          recordId,
          (FormatableBitSet) null,
          logBuffer,
          (RecordHandle) null);
      // log the BI of the entire row

    }

    int optionalDataLength = logBuffer.getPosition() - optionalDataStart;

    if (SanityManager.DEBUG) {
      if (optionalDataLength != logBuffer.getUsed())
        SanityManager.THROWASSERT(
            "wrong optional data length, optionalDataLength = "
                + optionalDataLength
                + ", logBuffer.getUsed() = "
                + logBuffer.getUsed());
    }

    // set the position to the beginning of the buffer
    logBuffer.setPosition(optionalDataStart);

    this.preparedLog =
        new ByteArray(logBuffer.getByteArray(), optionalDataStart, optionalDataLength);
  }
  /**
   * Create a new item and set the identity of the object to represent it. The object will be in the
   * No Identity state, ie. it will have just been created or clearIdentity() was just called. <br>
   * The object must copy the information out of key, not just store a reference to key. After this
   * call the expression getIdentity().equals(key) must return true. <br>
   * If the class of the object needs to change (e.g. to support a different format) then the object
   * should create a new object, call its initParameter() with the parameters the original object
   * was called with, set its identity and return a reference to it. The cache manager will discard
   * the reference to the old object. <br>
   * If an exception is thrown the object must be left in the no-identity state. <br>
   * MT - single thread required - Method must only be called be cache manager and the cache manager
   * will guarantee only one thread can be calling it.
   *
   * @return an object reference if the object can take on the identity, null otherwise.
   * @exception StandardException If forCreate is true and the object cannot be created.
   * @see org.apache.derby.iapi.services.cache.CacheManager#create
   */
  public Cacheable createIdentity(Object key, Object createParameter) throws StandardException {
    if (SanityManager.DEBUG) {
      SanityManager.ASSERT(key instanceof Long, "key is not instanceof Long");
      SanityManager.ASSERT(
          createParameter instanceof Conglomerate,
          "createParameter is not instanceof Conglomerate");
    }

    this.conglomid = (Long) key;
    this.conglom = ((Conglomerate) createParameter);

    return (this);
  }
Пример #8
0
  /**
   * Restore the in-memory representation from the stream.
   *
   * <p>
   *
   * @exception ClassNotFoundException Thrown if the stored representation is serialized and a class
   *     named in the stream could not be found.
   * @see java.io.Externalizable#readExternal
   */
  private final void localReadExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    super.readExternal(in);
    baseConglomerateId = in.readLong();
    rowLocationColumn = in.readInt();

    // read the column sort order info
    FormatableBitSet ascDescBits = new FormatableBitSet();
    ascDescBits.readExternal(in);
    ascDescInfo = new boolean[ascDescBits.getLength()];
    for (int i = 0; i < ascDescBits.getLength(); i++) ascDescInfo[i] = ascDescBits.isSet(i);

    // In memory maintain a collation id per column in the template.
    collation_ids = new int[format_ids.length];
    if (SanityManager.DEBUG) {
      SanityManager.ASSERT(!hasCollatedTypes);
    }

    // initialize all the entries to COLLATION_TYPE_UCS_BASIC,
    // and then reset as necessary.  For version ACCESS_B2I_V3_ID,
    // this is the default and no resetting is necessary.
    for (int i = 0; i < format_ids.length; i++)
      collation_ids[i] = StringDataValue.COLLATION_TYPE_UCS_BASIC;

    // initialize the unique with null setting to false, to be reset
    // below when read from disk.  For version ACCESS_B2I_V3_ID and
    // ACCESS_B2I_V4_ID, this is the default and no resetting is necessary.
    setUniqueWithDuplicateNulls(false);

    if (conglom_format_id == StoredFormatIds.ACCESS_B2I_V4_ID
        || conglom_format_id == StoredFormatIds.ACCESS_B2I_V5_ID) {
      // current format id, read collation info from disk
      if (SanityManager.DEBUG) {
        // length must include row location column and at least
        // one other field.
        SanityManager.ASSERT(collation_ids.length >= 2, "length = " + collation_ids.length);
      }

      hasCollatedTypes = ConglomerateUtil.readCollationIdArray(collation_ids, in);
    } else if (conglom_format_id != StoredFormatIds.ACCESS_B2I_V3_ID) {
      // Currently only V3, V4 and V5 should be possible in a Derby DB.
      // Actual work for V3 is handled by default code above, so no
      // special work is necessary.

      if (SanityManager.DEBUG) {
        SanityManager.THROWASSERT("Unexpected format id: " + conglom_format_id);
      }
    }
    if (conglom_format_id == StoredFormatIds.ACCESS_B2I_V5_ID) {
      setUniqueWithDuplicateNulls(in.readBoolean());
    }
  }
Пример #9
0
  /**
   * Distill the BigDecimal to a byte array and write out:
   *
   * <UL>
   *   <LI>scale (zero or positive) as a byte
   *   <LI>length of byte array as a byte
   *   <LI>the byte array
   * </UL>
   */
  public void writeExternal(ObjectOutput out) throws IOException {
    // never called when value is null
    if (SanityManager.DEBUG) SanityManager.ASSERT(!isNull());

    int scale;
    byte[] byteArray;

    if (value != null) {
      scale = value.scale();

      // J2SE 5.0 introduced negative scale value for BigDecimals.
      // In previouse Java releases a negative scale was not allowed
      // (threw an exception on setScale and the constructor that took
      // a scale).
      //
      // Thus the Derby format for DECIMAL implictly assumed a
      // positive or zero scale value, and thus now must explicitly
      // be positive. This is to allow databases created under J2SE 5.0
      // to continue to be supported under JDK 1.3/JDK 1.4, ie. to continue
      // the platform independence, independent of OS/cpu and JVM.
      //
      // If the scale is negative set the scale to be zero, this results
      // in an unchanged value with a new scale. A BigDecimal with a
      // negative scale by definition is a whole number.
      // e.g. 1000 can be represented by:
      //    a BigDecimal with scale -3 (unscaled value of 1)
      // or a BigDecimal with scale 0 (unscaled value of 1000)

      if (scale < 0) {
        scale = 0;
        value = value.setScale(0);
      }

      BigInteger bi = value.unscaledValue();
      byteArray = bi.toByteArray();
    } else {
      scale = rawScale;
      byteArray = rawData;
    }

    if (SanityManager.DEBUG) {
      if (scale < 0)
        SanityManager.THROWASSERT(
            "DECIMAL scale at writeExternal is negative " + scale + " value " + toString());
    }

    out.writeByte(scale);
    out.writeByte(byteArray.length);
    out.write(byteArray);
  }
Пример #10
0
  /**
   * Insert rows while we keep getting duplicates from the merge run whose scan is in the open scan
   * array entry indexed by scanindex.
   */
  void mergeARow(int scanindex) throws StandardException {
    if (SanityManager.DEBUG) {
      // Unless there's a bug, the scan index will refer
      // to an open scan.  That's because we never put
      // a scan index for a closed scan into the sort
      // buffer (via setNextAux).
      SanityManager.ASSERT(openScans[scanindex] != null);
    }

    DataValueDescriptor[] row;

    // Read rows from the merge run and stuff them into the
    // sort buffer for as long as we encounter duplicates.
    do {
      row = sortObserver.getArrayClone();

      // Fetch the row from the merge run.
      if (!openScans[scanindex].fetchNext(row)) {
        // If we're out of rows in the merge run, close the scan.

        openScans[scanindex].close();
        openScans[scanindex] = null;
        return;
      }

      // Save the index of this merge run with
      // the row we're putting in the sort buffer.
      sortBuffer.setNextAux(scanindex);
    } while (sortBuffer.insert(row) == SortBuffer.INSERT_DUPLICATE);
  }
  /** @see TypeCompiler#getCastToCharWidth */
  public int getCastToCharWidth(DataTypeDescriptor dts) {
    int formatId = getStoredFormatIdFromTypeId();
    switch (formatId) {
      case StoredFormatIds.DECIMAL_TYPE_ID:
        // Need to have space for '-' and decimal point.
        return dts.getPrecision() + 2;

      case StoredFormatIds.DOUBLE_TYPE_ID:
        return TypeCompiler.DOUBLE_MAXWIDTH_AS_CHAR;

      case StoredFormatIds.INT_TYPE_ID:
        return TypeCompiler.INT_MAXWIDTH_AS_CHAR;

      case StoredFormatIds.LONGINT_TYPE_ID:
        return TypeCompiler.LONGINT_MAXWIDTH_AS_CHAR;

      case StoredFormatIds.REAL_TYPE_ID:
        return TypeCompiler.REAL_MAXWIDTH_AS_CHAR;

      case StoredFormatIds.SMALLINT_TYPE_ID:
        return TypeCompiler.SMALLINT_MAXWIDTH_AS_CHAR;

      case StoredFormatIds.TINYINT_TYPE_ID:
        return TypeCompiler.TINYINT_MAXWIDTH_AS_CHAR;

      default:
        if (SanityManager.DEBUG) {
          SanityManager.THROWASSERT("unexpected formatId in getCastToCharWidth() - " + formatId);
        }
        return 0;
    }
  }
Пример #12
0
  synchronized void transfer(Object oldGroup, Object newGroup) {
    HashMap from = (HashMap) groups.get(oldGroup);
    if (from == null) return;

    HashMap to = (HashMap) groups.get(newGroup);
    if (to == null) {
      // simple case
      groups.put(newGroup, from);
      clearLimit(oldGroup);
      groups.remove(oldGroup);
      return;
    }

    if (to.size() < from.size()) {

      // place the contents of to into from
      mergeGroups(to, from);

      Object oldTo = groups.put(newGroup, from);
      if (SanityManager.DEBUG) {
        SanityManager.ASSERT(oldTo == to, "inconsistent state in LockSpace");
      }

    } else {
      mergeGroups(from, to);
    }

    clearLimit(oldGroup);
    groups.remove(oldGroup);
  }
Пример #13
0
 /**
  * Get the method name for getting out the corresponding primitive Java type.
  *
  * @return String The method call name for getting the corresponding primitive Java type.
  */
 public String getPrimitiveMethodName() {
   if (SanityManager.DEBUG) {
     SanityManager.THROWASSERT(
         "getPrimitiveMethodName not applicable for " + getClass().toString());
   }
   return null;
 }
  /** @see TypeCompiler#getCorrespondingPrimitiveTypeName */
  public String getCorrespondingPrimitiveTypeName() {
    /* Only numerics and booleans get mapped to Java primitives */
    int formatId = getStoredFormatIdFromTypeId();
    switch (formatId) {
      case StoredFormatIds.DOUBLE_TYPE_ID:
        return "double";

      case StoredFormatIds.INT_TYPE_ID:
        return "int";

      case StoredFormatIds.LONGINT_TYPE_ID:
        return "long";

      case StoredFormatIds.REAL_TYPE_ID:
        return "float";

      case StoredFormatIds.SMALLINT_TYPE_ID:
        return "short";

      case StoredFormatIds.TINYINT_TYPE_ID:
        return "byte";

      case StoredFormatIds.DECIMAL_TYPE_ID:
      default:
        if (SanityManager.DEBUG) {
          SanityManager.THROWASSERT(
              "unexpected formatId in getCorrespondingPrimitiveTypeName() - " + formatId);
        }
        return null;
    }
  }
  /**
   * Get the method name for getting out the corresponding primitive Java type.
   *
   * @return String The method call name for getting the corresponding primitive Java type.
   */
  public String getPrimitiveMethodName() {
    int formatId = getStoredFormatIdFromTypeId();
    switch (formatId) {
      case StoredFormatIds.DOUBLE_TYPE_ID:
        return "getDouble";

      case StoredFormatIds.INT_TYPE_ID:
        return "getInt";

      case StoredFormatIds.LONGINT_TYPE_ID:
        return "getLong";

      case StoredFormatIds.REAL_TYPE_ID:
        return "getFloat";

      case StoredFormatIds.SMALLINT_TYPE_ID:
        return "getShort";

      case StoredFormatIds.TINYINT_TYPE_ID:
        return "getByte";

      case StoredFormatIds.DECIMAL_TYPE_ID:
      default:
        if (SanityManager.DEBUG) {
          SanityManager.THROWASSERT(
              "unexpected formatId in getPrimitiveMethodName() - " + formatId);
        }
        return null;
    }
  }
  String nullMethodName() {
    int formatId = getStoredFormatIdFromTypeId();
    switch (formatId) {
      case StoredFormatIds.DECIMAL_TYPE_ID:
        return "getNullDecimal";

      case StoredFormatIds.DOUBLE_TYPE_ID:
        return "getNullDouble";

      case StoredFormatIds.INT_TYPE_ID:
        return "getNullInteger";

      case StoredFormatIds.LONGINT_TYPE_ID:
        return "getNullLong";

      case StoredFormatIds.REAL_TYPE_ID:
        return "getNullFloat";

      case StoredFormatIds.SMALLINT_TYPE_ID:
        return "getNullShort";

      case StoredFormatIds.TINYINT_TYPE_ID:
        return "getNullByte";

      default:
        if (SanityManager.DEBUG) {
          SanityManager.THROWASSERT("unexpected formatId in nullMethodName() - " + formatId);
        }
        return null;
    }
  }
 /**
  * Make the ConstantAction for a CREATE TRIGGER statement.
  *
  * @param triggerSchemaName name for the schema that trigger lives in.
  * @param triggerName Name of trigger
  * @param eventMask TriggerDescriptor.TRIGGER_EVENT_XXXX
  * @param isBefore is this a before (as opposed to after) trigger
  * @param isRow is this a row trigger or statement trigger
  * @param isEnabled is this trigger enabled or disabled
  * @param triggerTable the table upon which this trigger is defined
  * @param whenSPSId the sps id for the when clause (may be null)
  * @param whenText the text of the when clause (may be null)
  * @param actionSPSId the spsid for the trigger action (may be null)
  * @param actionText the text of the trigger action
  * @param spsCompSchemaId the compilation schema for the action and when spses. If null, will be
  *     set to the current default schema
  * @param creationTimestamp when was this trigger created? if null, will be set to the time that
  *     executeConstantAction() is invoked
  * @param referencedCols what columns does this trigger reference (may be null)
  * @param originalActionText The original user text of the trigger action
  * @param referencingOld whether or not OLD appears in REFERENCING clause
  * @param referencingNew whether or not NEW appears in REFERENCING clause
  * @param oldReferencingName old referencing table name, if any, that appears in REFERENCING
  *     clause
  * @param newReferencingName new referencing table name, if any, that appears in REFERENCING
  *     clause
  */
 CreateTriggerConstantAction(
     String triggerSchemaName,
     String triggerName,
     int eventMask,
     boolean isBefore,
     boolean isRow,
     boolean isEnabled,
     TableDescriptor triggerTable,
     UUID whenSPSId,
     String whenText,
     UUID actionSPSId,
     String actionText,
     UUID spsCompSchemaId,
     Timestamp creationTimestamp,
     int[] referencedCols,
     String originalActionText,
     boolean referencingOld,
     boolean referencingNew,
     String oldReferencingName,
     String newReferencingName) {
   super(triggerTable.getUUID());
   this.triggerName = triggerName;
   this.triggerSchemaName = triggerSchemaName;
   this.triggerTable = triggerTable;
   this.eventMask = eventMask;
   this.isBefore = isBefore;
   this.isRow = isRow;
   this.isEnabled = isEnabled;
   this.whenSPSId = whenSPSId;
   this.whenText = whenText;
   this.actionSPSId = actionSPSId;
   this.actionText = actionText;
   this.spsCompSchemaId = spsCompSchemaId;
   this.creationTimestamp = creationTimestamp;
   this.referencedCols = referencedCols;
   this.originalActionText = originalActionText;
   this.referencingOld = referencingOld;
   this.referencingNew = referencingNew;
   this.oldReferencingName = oldReferencingName;
   this.newReferencingName = newReferencingName;
   if (SanityManager.DEBUG) {
     SanityManager.ASSERT(triggerSchemaName != null, "triggerSchemaName sd is null");
     SanityManager.ASSERT(triggerName != null, "trigger name is null");
     SanityManager.ASSERT(triggerTable != null, "triggerTable is null");
     SanityManager.ASSERT(actionText != null, "actionText is null");
   }
 }
Пример #18
0
 /**
  * ************************************************************************ Protected concrete
  * impl of abstract methods of GenericConglomerateController class:
  * *************************************************************************
  */
 protected final void getRowPositionFromRowLocation(RowLocation row_loc, RowPosition pos)
     throws StandardException {
   if (SanityManager.DEBUG) {
     SanityManager.ASSERT(row_loc instanceof HeapRowLocation);
   }
   pos.current_rh = ((HeapRowLocation) row_loc).getRecordHandle(open_conglom.getContainer());
   pos.current_rh_qualified = true;
 }
Пример #19
0
  protected boolean lockRow(RecordHandle rh, int lock_oper, boolean wait, int lock_duration)
      throws StandardException {
    boolean ret_val;
    boolean forUpdate = ((ConglomerateController.LOCK_UPD & lock_oper) != 0);
    boolean forUpdateLock = ((ConglomerateController.LOCK_UPDATE_LOCKS & lock_oper) != 0);

    if (forUpdate && !forUpdateLock) {
      boolean forInsert = ((ConglomerateController.LOCK_INS & lock_oper) != 0);
      boolean forInsertPrevKey = ((ConglomerateController.LOCK_INS_PREVKEY & lock_oper) != 0);

      if (SanityManager.DEBUG) {
        SanityManager.ASSERT(!(forInsertPrevKey && forInsert));
      }

      if (lock_duration == TransactionManager.LOCK_INSTANT_DURATION) {
        ret_val =
            open_conglom
                .getContainer()
                .getLockingPolicy()
                .zeroDurationLockRecordForWrite(
                    open_conglom.getRawTran(), rh, forInsertPrevKey, wait);
      } else {
        ret_val =
            open_conglom
                .getContainer()
                .getLockingPolicy()
                .lockRecordForWrite(open_conglom.getRawTran(), rh, forInsert, wait);
      }
    } else {
      if (SanityManager.DEBUG) {
        SanityManager.ASSERT((ConglomerateController.LOCK_INS & lock_oper) == 0);
        SanityManager.ASSERT((ConglomerateController.LOCK_INS_PREVKEY & lock_oper) == 0);
      }

      ret_val =
          open_conglom
              .getContainer()
              .getLockingPolicy()
              .lockRecordForRead(
                  open_conglom.getRawTran(), open_conglom.getContainer(), rh, wait, forUpdate);
    }

    return (ret_val);
  }
Пример #20
0
  /**
   * Flatten this FSqry into the outer query block. The steps in flattening are: o Mark all
   * ResultColumns as redundant, so that they are "skipped over" at generate(). o Append the
   * wherePredicates to the outer list. o Return the fromList so that the caller will merge the 2
   * lists RESOLVE - FSqrys with subqueries are currently not flattenable. Some of them can be
   * flattened, however. We need to merge the subquery list when we relax this restriction.
   *
   * <p>NOTE: This method returns NULL when flattening RowResultSetNodes (the node for a VALUES
   * clause). The reason is that no reference is left to the RowResultSetNode after flattening is
   * done - the expressions point directly to the ValueNodes in the RowResultSetNode's
   * ResultColumnList.
   *
   * @param rcl The RCL from the outer query
   * @param outerPList PredicateList to append wherePredicates to.
   * @param sql The SubqueryList from the outer query
   * @param gbl The group by list, if any
   * @param havingClause The HAVING clause, if any
   * @return FromList The fromList from the underlying SelectNode.
   * @exception StandardException Thrown on error
   */
  public FromList flatten(
      ResultColumnList rcl,
      PredicateList outerPList,
      SubqueryList sql,
      GroupByList gbl,
      ValueNode havingClause)
      throws StandardException {
    FromList fromList = null;
    SelectNode selectNode;

    resultColumns.setRedundant();

    subquery.getResultColumns().setRedundant();

    /*
     ** RESOLVE: Each type of result set should know how to remap itself.
     */
    if (subquery instanceof SelectNode) {
      selectNode = (SelectNode) subquery;
      fromList = selectNode.getFromList();

      // selectNode.getResultColumns().setRedundant();

      if (selectNode.getWherePredicates().size() > 0) {
        outerPList.destructiveAppend(selectNode.getWherePredicates());
      }

      if (selectNode.getWhereSubquerys().size() > 0) {
        sql.destructiveAppend(selectNode.getWhereSubquerys());
      }
    } else if (!(subquery instanceof RowResultSetNode)) {
      if (SanityManager.DEBUG) {
        SanityManager.THROWASSERT(
            "subquery expected to be either a SelectNode or a RowResultSetNode, but is a "
                + subquery.getClass().getName());
      }
    }

    /* Remap all ColumnReferences from the outer query to this node.
     * (We replace those ColumnReferences with clones of the matching
     * expression in the SELECT's RCL.
     */
    rcl.remapColumnReferencesToExpressions();
    outerPList.remapColumnReferencesToExpressions();
    if (gbl != null) {
      gbl.remapColumnReferencesToExpressions();
    }

    if (havingClause != null) {
      havingClause.remapColumnReferencesToExpressions();
    }

    return fromList;
  }
Пример #21
0
  /**
   * Called when setting a DECIMAL value internally or from through a procedure or function. Handles
   * long in addition to BigDecimal to handle identity being stored as a long but returned as a
   * DECIMAL.
   */
  public void setValue(Number theValue) throws StandardException {
    if (SanityManager.ASSERT) {
      if (theValue != null
          && !(theValue instanceof java.math.BigDecimal)
          && !(theValue instanceof java.lang.Long))
        SanityManager.THROWASSERT("SQLDecimal.setValue(Number) passed a " + theValue.getClass());
    }

    if (theValue instanceof BigDecimal || theValue == null) setCoreValue((BigDecimal) theValue);
    else setValue(theValue.longValue());
  }
Пример #22
0
  /** Initialize the scan, returning false if there was some error. */
  public boolean init(TransactionManager tran) throws StandardException {
    if (SanityManager.DEBUG) {
      // We really expect to have at least one
      // merge run.
      SanityManager.ASSERT(mergeRuns != null);
      SanityManager.ASSERT(mergeRuns.size() > 0);

      // This sort scan also expects that the
      // caller has ensured that the sort buffer
      // capacity will hold a row from all the
      // merge runs.
      SanityManager.ASSERT(sortBuffer.capacity() >= mergeRuns.size());
    }

    // Clear the sort buffer.
    sortBuffer.reset();

    // Create an array to hold a scan controller
    // for each merge run.
    openScans = new StreamContainerHandle[mergeRuns.size()];
    if (openScans == null) return false;

    // Open a scan on each merge run.
    int scanindex = 0;
    Enumeration e = mergeRuns.elements();
    while (e.hasMoreElements()) {
      // get the container id
      long id = ((Long) e.nextElement()).longValue();

      Transaction rawTran = tran.getRawStoreXact(); // get raw transaction
      int segmentId = StreamContainerHandle.TEMPORARY_SEGMENT;
      openScans[scanindex++] = rawTran.openStreamContainer(segmentId, id, hold);
    }

    // Load the initial rows.
    for (scanindex = 0; scanindex < openScans.length; scanindex++) mergeARow(scanindex);

    // Success!
    return true;
  }
Пример #23
0
  /** Close the scan, a commit or abort is about to happen. */
  public boolean closeForEndTransaction(boolean closeHeldScan) throws StandardException {
    boolean ret_val = super.closeForEndTransaction(closeHeldScan);

    if (SanityManager.DEBUG)
      SanityManager.ASSERT(ret_val, "B2IMaxScan never should be held across a commit.");

    if (base_cc_for_locking != null) {
      base_cc_for_locking.close();
      base_cc_for_locking = null;
    }

    return (ret_val);
  }
  /**
   * Get the constraint type out of the row.
   *
   * @param row The row from sysconstraints
   * @return int The constraint type as an int
   * @exception StandardException thrown on failure
   */
  protected int getConstraintType(ExecRow row) throws StandardException {
    DataValueDescriptor col;
    int constraintIType;
    String constraintSType;

    /* 4th column is TYPE (char(1)) */
    col = row.getColumn(SYSCONSTRAINTS_TYPE);
    constraintSType = col.getString();
    if (SanityManager.DEBUG) {
      SanityManager.ASSERT(constraintSType.length() == 1, "Fourth column type incorrect");
    }

    switch (constraintSType.charAt(0)) {
      case 'P':
        constraintIType = DataDictionary.PRIMARYKEY_CONSTRAINT;
        break;

      case 'U':
        constraintIType = DataDictionary.UNIQUE_CONSTRAINT;
        break;

      case 'C':
        constraintIType = DataDictionary.CHECK_CONSTRAINT;
        break;

      case 'F':
        constraintIType = DataDictionary.FOREIGNKEY_CONSTRAINT;
        break;

      default:
        if (SanityManager.DEBUG) {
          SanityManager.THROWASSERT("Fourth column value invalid");
        }
        constraintIType = -1;
    }

    return constraintIType;
  }
  /**
   * Reopen this ResultSet.
   *
   * @exception StandardException thrown if cursor finished.
   */
  public void reopenCore() throws StandardException {
    if (SanityManager.DEBUG) {
      SanityManager.ASSERT(isOpen, "WindowResultSet already open");
    }

    beginTime = getCurrentTimeMillis();

    /* Reopen the source */
    source.reopenCore();

    rownumber = 0;
    numOpens++;
    openTime += getElapsedMillis(beginTime);
  }
Пример #26
0
  public void insertAndFetchLocation(DataValueDescriptor[] row, RowLocation templateRowLocation)
      throws StandardException {
    if (open_conglom.isClosed()) {
      if (open_conglom.getHold()) {
        open_conglom.reopen();
      } else {
        throw (StandardException.newException(
            SQLState.HEAP_IS_CLOSED, open_conglom.getConglomerate().getId()));
      }
    }

    RecordHandle rh = doInsert(row);
    if (SanityManager.DEBUG) {
      SanityManager.ASSERT(templateRowLocation instanceof HeapRowLocation);
    }
    HeapRowLocation hrl = (HeapRowLocation) templateRowLocation;
    hrl.setFrom(rh);
  }
  /**
   * If the result set has been opened, close the open scan, else throw.
   *
   * @exception StandardException thrown on error
   */
  public void close() throws StandardException {
    beginTime = getCurrentTimeMillis();

    if (isOpen) {
      clearCurrentRow();

      /*
       * Make sure to close the source
       */
      source.close();
      super.close();

    } else if (SanityManager.DEBUG) {
      SanityManager.DEBUG("CloseRepeatInfo", "Close of WindowResultSet repeated");
    }

    closeTime += getElapsedMillis(beginTime);
  }
  /**
   * Initializer for a CreateTableNode for a base table
   *
   * @param newObjectName The name of the new object being created (ie base table)
   * @param tableElementList The elements of the table: columns, constraints, etc.
   * @param properties The optional list of properties associated with the table.
   * @param lockGranularity The lock granularity.
   * @exception StandardException Thrown on error
   */
  public void init(
      Object newObjectName, Object tableElementList, Object properties, Object lockGranularity)
      throws StandardException {
    tableType = TableDescriptor.BASE_TABLE_TYPE;
    this.lockGranularity = ((Character) lockGranularity).charValue();
    implicitCreateSchema = true;

    if (SanityManager.DEBUG) {
      if (this.lockGranularity != TableDescriptor.TABLE_LOCK_GRANULARITY
          && this.lockGranularity != TableDescriptor.ROW_LOCK_GRANULARITY) {
        SanityManager.THROWASSERT("Unexpected value for lockGranularity = " + this.lockGranularity);
      }
    }

    initAndCheck(newObjectName);
    this.tableElementList = (TableElementList) tableElementList;
    this.properties = (Properties) properties;
  }
Пример #29
0
  /**
   * Find the container and then read the page from that container.
   *
   * <p>This is the way new pages enter the page cache.
   *
   * <p>
   *
   * @return always true, higher levels have already checked the page number is valid for an open.
   * @exception StandardException Standard Derby policy.
   * @see Cacheable#setIdentity
   */
  public Cacheable setIdentity(Object key) throws StandardException {
    if (SanityManager.DEBUG) {
      SanityManager.ASSERT(key instanceof PageKey);
    }

    initialize();

    PageKey newIdentity = (PageKey) key;

    FileContainer myContainer = (FileContainer) containerCache.find(newIdentity.getContainerId());

    setContainerRowCount(myContainer.getEstimatedRowCount(0));

    try {
      if (!alreadyReadPage) {
        // Fill in the pageData array by reading bytes from disk.
        readPage(myContainer, newIdentity);
      } else {
        // pageData array already filled
        alreadyReadPage = false;
      }

      // if the formatID on disk is not the same as this page instance's
      // format id, instantiate the real page object
      int fmtId = getTypeFormatId();

      int onPageFormatId = FormatIdUtil.readFormatIdInteger(pageData);
      if (fmtId != onPageFormatId) {
        return changeInstanceTo(onPageFormatId, newIdentity).setIdentity(key);
      }

      // this is the correct page instance
      initFromData(myContainer, newIdentity);
    } finally {
      containerCache.release(myContainer);
      myContainer = null;
    }

    fillInIdentity(newIdentity);

    initialRowCount = 0;

    return this;
  }
  private int getDefaultAccessLevel() throws StandardException {
    PersistentSet tc = lcc.getTransactionExecute();

    String modeS =
        (String) PropertyUtil.getServiceProperty(tc, Property.DEFAULT_CONNECTION_MODE_PROPERTY);
    if (modeS == null) return FULL_ACCESS;
    else if (StringUtil.SQLEqualsIgnoreCase(modeS, Property.NO_ACCESS)) return NO_ACCESS;
    else if (StringUtil.SQLEqualsIgnoreCase(modeS, Property.READ_ONLY_ACCESS)) return READ_ACCESS;
    else if (StringUtil.SQLEqualsIgnoreCase(modeS, Property.FULL_ACCESS)) return FULL_ACCESS;
    else {
      if (SanityManager.DEBUG)
        SanityManager.THROWASSERT(
            "Invalid value for property "
                + Property.DEFAULT_CONNECTION_MODE_PROPERTY
                + " "
                + modeS);
      return FULL_ACCESS;
    }
  }