Exemple #1
0
  Object castOrConvertToType(SessionInterface session, Object a, Type otherType, boolean cast) {

    BlobData b;

    if (a == null) {
      return null;
    }

    switch (otherType.typeCode) {

        // non-SQL feature, for compatibility with previous versions
      case Types.SQL_VARCHAR:
      case Types.SQL_CHAR:
        {
          b = session.getScanner().convertToBinary((String) a);
          otherType = getBinaryType(Types.SQL_VARBINARY, b.length(session));

          break;
        }
      case Types.SQL_BIT:
        {
          b = (BlobData) a;
          otherType = getBinaryType(Types.SQL_VARBINARY, b.length(session));

          break;
        }
      case Types.SQL_BINARY:
      case Types.SQL_VARBINARY:
      case Types.SQL_BLOB:
        b = (BlobData) a;
        break;

      default:
        throw Error.error(ErrorCode.X_22501);
    }

    if (precision == 0) {
      return b; // never a blob
    }

    if (b.length(session) > precision && b.nonZeroLength(session) > precision) {
      if (!cast) {
        throw Error.error(ErrorCode.X_22001);
      }

      session.addWarning(Error.error(ErrorCode.W_01004));
    }

    if (otherType.typeCode == Types.SQL_BLOB) {
      byte[] bytes = b.getBytes(session, 0, (int) precision);

      b = new BinaryData(bytes, false);
    }

    switch (typeCode) {
      case Types.SQL_BINARY:
        {
          if (b.length(session) > precision) {
            byte[] data = b.getBytes(session, 0, (int) precision);

            b = new BinaryData(data, false);
          } else if (b.length(session) < precision) {
            byte[] data = (byte[]) ArrayUtil.resizeArray(b.getBytes(), (int) precision);

            b = new BinaryData(data, false);
          }

          return b;
        }
      case Types.SQL_VARBINARY:
        {
          if (b.length(session) > precision) {
            byte[] data = b.getBytes(session, 0, (int) precision);

            b = new BinaryData(data, false);
          }

          return b;
        }
      default:
    }

    throw Error.error(ErrorCode.X_22501);
  }