void QRLogger::logDiags(ComDiagsArea* diagsArea, std::string &cat)
{
  const NAWchar* diagMsg;
  NAString* diagStr;
  Int32 i;
  ComCondition* condition;
  
  log4cxx::LoggerPtr myLogger = log4cxx::Logger::getLogger(cat);
  if ( myLogger ) 
  {
    log4cxx::LevelPtr myLevel = myLogger->getLevel();
    if ( myLevel ) 
    {
      // If configured Level is the same or less restrictive than WARN (30000)
      // than report the warning
      if ( myLevel != log4cxx::Level::getOff() && myLevel->toInt() <= LL_WARN )
      {
        for (i=1; i<=diagsArea->getNumber(DgSqlCode::WARNING_); i++)
        {
          condition = diagsArea->getWarningEntry(i);
          diagMsg = condition->getMessageText();
          diagStr = unicodeToChar(diagMsg, NAWstrlen(diagMsg),
                                          CharInfo::ISO88591, NULL, TRUE);
          log(cat, LL_WARN, condition->getSQLCODE(), "",
            "  warn condition %d: %s", i, diagStr->data());
          delete diagStr;
        }
      }
    }
  }
}
Beispiel #2
0
// ----------------------------------------------------------------------------
// method:  getAuthDetails
//
// Create the CmpSeabaseDDLauth class containing auth details for the
// request authID
//
// Input:
//    authID - the database authorization ID to search for
//
//  Output:
//    A returned parameter:
//       0 - authorization details are available
//       < 0 - an error was returned trying to get details
//       100 - authorization details were not found
//       > 0 - (not 100) warning was returned
// ----------------------------------------------------------------------------
Int32 CmpSeabaseDDLauth::getAuthDetails (Int32 authID)
{
  try
  {
    NAString sysCat = CmpSeabaseDDL::getSystemCatalogStatic();
    char buf[1000];
   str_sprintf(buf, "select auth_id, auth_db_name, auth_ext_name, auth_type, auth_creator, auth_is_valid, auth_create_time, auth_redef_time from %s.\"%s\".%s where auth_id = %s ",
              sysCat.data(), SEABASE_MD_SCHEMA, SEABASE_AUTHS, authID);
    NAString cmd (buf);

    if (selectExactRow(cmd))
      return 0;
    return 100;
  }
  catch (DDLException e)
  {
    // At this time, an error should be in the diags area.
    return e.getSqlcode();
  }
  catch (...)
  {
    // If there is no error in the diags area, set up an internal error
    Int32 numErrors = CmpCommon::diags()->getNumber(DgSqlCode::ERROR_);
    if (numErrors == 0)
      *CmpCommon::diags() << DgSqlCode (-CAT_INTERNAL_EXCEPTION_ERROR)
                          << DgInt0(__LINE__)
                          << DgString0("getAuthDetails for authID");

    return -CAT_INTERNAL_EXCEPTION_ERROR;
  }
}
Beispiel #3
0
short
IsolatedScalarUDF::generateShape(CollHeap * c, char * buf,
                           NAString * shapeStr)
{
  Space *space = (Space *)c;
  char mybuf[100];

  sprintf (mybuf, "isolated_scalar_udf");
  outputBuffer (space, buf, mybuf, shapeStr);

  if (getRoutineDesc() &&
      getRoutineDesc()->getNARoutine() &&
      getRoutineDesc()->getNARoutine()->getRoutineName())
  {
    NAString fmtdStr;
    ToQuotedString(fmtdStr, getRoutineDesc()->getNARoutine()->
                             getRoutineName()->getQualifiedNameObj().
                             getQualifiedNameAsAnsiString().data());
    snprintf (mybuf, 100, "(scalar_udf %s", fmtdStr.data());
    outputBuffer (space, buf, mybuf, shapeStr);
    if (getRoutineDesc()->isUUDFRoutine() &&
        getRoutineDesc()->getActionNARoutine() &&
        getRoutineDesc()->getActionNARoutine()->getActionName())
    {
      ToQuotedString(fmtdStr, getRoutineDesc()->getActionNARoutine()->
                               getActionName()->data());
      snprintf (mybuf, 100, ", udf_action %s", fmtdStr.data());
      outputBuffer (space, buf, mybuf, shapeStr);
    }
    strcpy(mybuf, ")");
    outputBuffer (space, buf, mybuf, shapeStr);
  }
  return 0;
}
NABoolean SchemaName::matchDefaultPublicSchema()
{
  if (schemaName_.isNull())
    return TRUE;

  NABoolean matched = FALSE;

  // get default schema
  NAString defCat;
  NAString defSch;
  ActiveSchemaDB()->getDefaults().getCatalogAndSchema(defCat, defSch);
  ToInternalIdentifier(defCat);
  ToInternalIdentifier(defSch);

  // get public schema
  NAString publicSchema = ActiveSchemaDB()->getDefaults().getValue(PUBLIC_SCHEMA_NAME);
  ComSchemaName pubSchema(publicSchema);
  NAString pubCat = pubSchema.getCatalogNamePart().getInternalName();
  NAString pubSch = pubSchema.getSchemaNamePart().getInternalName();

  // if catalog was not specified
  NAString catName = (catalogName_.isNull()? defCat:catalogName_);
  pubCat = (pubCat.isNull()? defCat:pubCat);

  if (((catName==defCat) && (schemaName_==defSch)) ||
      ((catName==pubCat) && (schemaName_==pubSch)))
    matched = TRUE;

  return matched;
}
// This function copies the above applyDefaults() function
// and includes checking for the object existence and 
// search in the public schema if necessary.
// This is used to replace the above function when 
// we need to consider PUBLIC_SCHEMA_NAME
Int32 QualifiedName::applyDefaultsValidate(const SchemaName& defCatSch,
                                         ComAnsiNameSpace nameSpace)
{
  // need to try public schema if it is specified
  // and the object schema is not specified
  NAString publicSchema = "";
  CmpCommon::getDefault(PUBLIC_SCHEMA_NAME, publicSchema, FALSE);
  ComSchemaName pubSchema(publicSchema);
  NAString pubSchemaIntName = "";
  if ( getSchemaName().isNull() && 
       !pubSchema.isEmpty() )
  {
    pubSchemaIntName = pubSchema.getSchemaNamePart().getInternalName();
  }

  Int32 ret = extractAndDefaultNameParts( defCatSch 
				                              , catalogName_
                                      , schemaName_
                                      , objectName_
                                   );

  // try public schema if the table does not exist 
  if (!pubSchemaIntName.isNull())
  {
    *(CmpCommon::diags()) << DgSqlCode(-4222)
                          << DgString0("Public Access Schema");
  }

  return ret;
}
HDFS_Client_RetCode HdfsClient::hdfsCleanUnloadPath( const NAString& uldPath)
{
  QRLogger::log(CAT_SQL_HDFS, LL_DEBUG, "HdfsClient::hdfsCleanUnloadPath(%s) called.",
                                                                             uldPath.data());
  if (initJNIEnv() != JOI_OK)
     return HDFS_CLIENT_ERROR_HDFS_CLEANUP_PARAM;
  if (getInstance() == NULL)
     return HDFS_CLIENT_ERROR_HDFS_CLEANUP_PARAM;
  jstring js_UldPath = jenv_->NewStringUTF(uldPath.data());
  if (js_UldPath == NULL) {
    GetCliGlobals()->setJniErrorStr(getErrorText(HDFS_CLIENT_ERROR_HDFS_CLEANUP_PARAM));
    jenv_->PopLocalFrame(NULL);
    return HDFS_CLIENT_ERROR_HDFS_CLEANUP_PARAM;
  }

  tsRecentJMFromJNI = JavaMethods_[JM_HDFS_CLEAN_UNLOAD_PATH].jm_full_name;
  jboolean jresult = jenv_->CallStaticBooleanMethod(javaClass_, JavaMethods_[JM_HDFS_CLEAN_UNLOAD_PATH].methodID, js_UldPath);

  if (jenv_->ExceptionCheck())
  {
    getExceptionDetails();
    logError(CAT_SQL_HDFS, __FILE__, __LINE__);
    logError(CAT_SQL_HDFS, "HdfsClient::hdfsCleanUnloadPath()", getLastError());
    jenv_->PopLocalFrame(NULL);
    return HDFS_CLIENT_ERROR_HDFS_CLEANUP_EXCEPTION;
  }

  jenv_->PopLocalFrame(NULL);
  return HDFS_CLIENT_OK;
}
void StmtModule::applyModuleCatalogSchema(const NAString& cat, 
                                          const NAString& sch)
{
  // apply moduleCatalog if necessary
  if (name().getCatalogName().isNull()) {
    if (!cat.isNull())
      name().setCatalogName(cat);
  }

  // apply moduleSchema if necessary
  if (name().getSchemaName().isNull()) {
    if (!sch.isNull())
      name().setSchemaName(sch);
  }

  // module catalog & schema must be non-null now. Otherwise, a fatal
  // exception can occur in mxsqlc/mxsqlco in
  //   mod_def::setModule() --> mod_def::outputModule()
  //   --> StmtModule::unparseSimple() --> 
  //   QualifiedName::getQualifiedNameAsAnsiString() -->
  //   QualifiedName::getQualifiedNameAsString() -->
  //   CMPASSERT(NOT getSchemaName().isNull());
  // as reported in genesis case 10-030708-8735.
  if (name().getCatalogName().isNull() || name().getSchemaName().isNull()) {
    const SchemaName& defcs =
      ActiveSchemaDB()->getDefaultSchema(
        SchemaDB::REFRESH_CACHE | SchemaDB::FORCE_ANSI_NAMETYPE);
    if (name().getCatalogName().isNull())
      name().setCatalogName(defcs.getCatalogName());
    if (name().getSchemaName().isNull())
      name().setSchemaName(defcs.getSchemaName());
  }
}
// a helper function converting a hexdecimal digit to a single-byte string
static NAString * 
convHexToChar(const NAWchar *s, Int32 inputLen, CharInfo::CharSet cs, CollHeap* heap)
{
  ComASSERT((inputLen % SQL_DBCHAR_SIZE) == 0);
  NAString *r = new (heap) NAString(heap);
  if (!s || inputLen <= 0) return r;

  unsigned char upper4Bits;
  unsigned char lower4Bits;

  for (Int32 i = 0; i < inputLen; i=i+2) {
    if (isHexDigit8859_1(s[i]) AND isHexDigit8859_1(s[i+1])) {

#pragma warning (disable : 4244)   //warning elimination
#pragma nowarn(1506)   // warning elimination 
      upper4Bits = getHexDigitValue(s[i]);
#pragma warn(1506)  // warning elimination 
#pragma nowarn(1506)   // warning elimination 
      lower4Bits = getHexDigitValue(s[i+1]);
#pragma warn(1506)  // warning elimination 
#pragma warning (default : 4244)   //warning elimination

#pragma nowarn(1506)   // warning elimination 
      char c = (upper4Bits << 4) | lower4Bits;
#pragma warn(1506)  // warning elimination 
      r->append(c);
    } else { 
      NADELETE(r, NAString, heap);
      return NULL;
    }
  }
  return r;
}
HDFS_Client_RetCode HdfsClient::hdfsExists( const NAString& uldPath, NABoolean & exist)
{
  QRLogger::log(CAT_SQL_HDFS, LL_DEBUG, "HdfsClient::hdfsExists(%s) called.",
                                                      uldPath.data());
  if (initJNIEnv() != JOI_OK)
     return HDFS_CLIENT_ERROR_HDFS_EXISTS_PARAM;
  if (getInstance() == NULL)
     return HDFS_CLIENT_ERROR_HDFS_EXISTS_PARAM;

  jstring js_UldPath = jenv_->NewStringUTF(uldPath.data());
  if (js_UldPath == NULL) {
     jenv_->PopLocalFrame(NULL);
     return HDFS_CLIENT_ERROR_HDFS_EXISTS_PARAM;
  }

  tsRecentJMFromJNI = JavaMethods_[JM_HDFS_EXISTS].jm_full_name;
  jboolean jresult = jenv_->CallStaticBooleanMethod(javaClass_, JavaMethods_[JM_HDFS_EXISTS].methodID, js_UldPath);
  exist = jresult;
  if (jenv_->ExceptionCheck())
  {
    getExceptionDetails();
    logError(CAT_SQL_HDFS, __FILE__, __LINE__);
    logError(CAT_SQL_HDFS, "HdfsClient::hdfsExists()", getLastError());
    jenv_->PopLocalFrame(NULL);
    return HDFS_CLIENT_ERROR_HDFS_EXISTS_EXCEPTION;
  } 
  jenv_->PopLocalFrame(NULL);
  return HDFS_CLIENT_OK;
}
//
// data (begin or end) is in this format: 
//  <length><data> ... <length><data>
//
// a). length is 2-bytes long
// b). data is <length>-bytes long
// c). there are <n> such pairs, where <n> is determined by
//     the total length of the source and the length of each pair.
//
static NABoolean extractKeyValuePairs(const NAString& source, NAString& result) 
{
   char buf[1024];

   const char* data = source.data();
   const char* end = data + source.length();

   NABoolean hasData = ( data < end);

   while ( data < end ) {
       UInt16 len = 0;
       memcpy((char*)&len, data, sizeof(len));

       memcpy(buf, data+sizeof(len), len);
       buf[len] = NULL;

       result.append(buf);

       data += sizeof(len) + len;

       if ( data < end )
          result.append(",");
   }
   return hasData;
}
static NABoolean getCharsetsToUse(
     Lng32 msgCharSet, Lng32 &inputCS, Lng32 &defaultCS)
{
  if (msgCharSet == SQLCHARSETCODE_ISO_MAPPING)
    {
      // return the value isoMapping set for this system.
      NAString cs;
      CmpCommon::getDefault(ISO_MAPPING, cs);
      inputCS = (Lng32)CharInfo::getCharSetEnum(cs.data());
      defaultCS = (Lng32)SQLCHARSETCODE_ISO88591;

      SetSqlParser_DEFAULT_CHARSET(CharInfo::ISO88591);
    }
  else
    {
      inputCS = msgCharSet;
      defaultCS = (Lng32)SQLCHARSETCODE_UNKNOWN;

      // no change to default charset, if ISO_MAPPING was not specified.
      // Just set it to the same value as the original charset.
      SetSqlParser_DEFAULT_CHARSET(SqlParser_ORIG_DEFAULT_CHARSET);
    }

  return FALSE;
}
// The following method returns TRUE if parameter "output" is populated.
NABoolean
ComRoutineActionNamePart::getRoutineActionNameStoredInOBJECTS_OBJECT_NAME
(ComAnsiNamePart &output, // out
 ComBoolean performCheck) // in - default is TRUE
{
  if (NOT isValid())
    return FALSE;

  ComString funnyNameInInternalFormat;
  getUudfUID().convertTo19BytesFixedWidthStringWithZeroesPrefix(funnyNameInInternalFormat/*out*/);
  funnyNameInInternalFormat += "_";
  funnyNameInInternalFormat += getInternalName();

  NAWString ucs2FunnyInternalName;
  ComAnsiNameToUCS2(funnyNameInInternalFormat, ucs2FunnyInternalName /* out */);
  if (performCheck AND ucs2FunnyInternalName.length() > MAX_IDENTIFIER_INT_LEN)
    return FALSE;

  NAString extName = ToAnsiIdentifier(funnyNameInInternalFormat,
                                      performCheck);
  if (extName.isNull()) // the generated external name is invalid
    return FALSE;

  output.setInternalName(funnyNameInInternalFormat);
  output.setExternalName(extName);
  return TRUE;
}
Beispiel #13
0
// ----------------------------------------------------------------------------
// method: getAuthDetails
//
// Creates the CmpSeabaseDDLauth class containing auth details for the
// requested authName
//
// Input:
//    authName - the database auth name to retrieve details for
//    isExternal -
//       true - the auth name is the external name (auth_ext_name)
//       false - the auth name is the database name (auth_db_name)
//
// Output:
//    A returned parameter:
//       0 - authorization details are available
//       < 0 - an error was returned trying to get details
//       100 - authorization details were not found
//       > 0 - (not 100) warning was returned
// ----------------------------------------------------------------------------
Int32 CmpSeabaseDDLauth::getAuthDetails(const char *pAuthName,
                                        bool isExternal)
{
  try
  {
    NAString sysCat = CmpSeabaseDDL::getSystemCatalogStatic();
    char buf[1000];
    NAString authNameCol = isExternal ? "auth_ext_name " : "auth_db_name ";
   str_sprintf(buf, "select auth_id, auth_db_name, auth_ext_name, auth_type, auth_creator, auth_is_valid, auth_create_time, auth_redef_time from %s.\"%s\".%s where %s = '%s' ",
              sysCat.data(), SEABASE_MD_SCHEMA, SEABASE_AUTHS, authNameCol.data(), pAuthName);
    NAString cmd (buf);

    if (selectExactRow(cmd))
      return 0;
    return 100;
  }
  catch (DDLException e)
  {
    return e.getSqlcode();
  }
  catch (...)
  {
    return -1;
  }
}
NAString TDBDlgExprList::ExprNodeFlagsToString(ex_expr* exprNode)
{
   NAString string;
   
   if (exprNode->getFixupConstsAndTemps())
    string += "FIXUP_CONSTS_AND_TEMPS|";

   if (exprNode->generateNoPCode())
     string += "GENERATE_NO_PCODE|";

   if (exprNode->getPCodeGenCompile())
     string += "PCODE_GEN_COMPILE|";
   
   if (exprNode->getPCodeMoveFastpath())
     string += "PCODE_MOVE_FASTPATH|";

   if (exprNode->forInsertUpdate())
     string += "FOR_INSERT_UPDATE|";

   if (exprNode->usePCodeEvalAligned())
     string += "PCODE_EVAL_ALIGNED|";

   if (exprNode->handleIndirectVC())
     string += "HANDLE_INDIRECT_VC|";

   if (exprNode-> getPCodeNative())
     string += "PCODE_EVAL_NATIVE";
   
   int len = string.length();
   string.remove(len-1);

   return string;
}
Beispiel #15
0
NABoolean CmpInternalSP::OutputFormat(CmpSPOutputFormat& t)
{
  NABoolean retStatus = TRUE;
  
  CMPASSERT(state_ == COMPILE);
  
  initSP_ERROR_STRUCT();
  Lng32 num;
  NAString outTableName = OutTableName();
  if ( (*(procFuncs_.outNumFormatFunc_))( &num, compHandle_, 
    procFuncs_.spHandle_, &spError_[0])
    == SP_SUCCESS )
    {	 
      if ( num == 0 )
      {
        // Create a dummy column if there is no output, since otherwise
        // NATable generated later on will break later in binder.
        SP_FIELDDESC_STRUCT fields;
        strcpy(fields.COLUMN_DEF, "Dummy1 int");
        if ( !(t.SetFormat(1, outTableName.data(), &fields, 0, 0) ) )
          retStatus = FALSE;
      }
      else
      {
        SP_FIELDDESC_STRUCT* fields = allocSP_FIELDDESC_STRUCT(num);
        SP_KEYDESC_STRUCT* keys = allocSP_KEYDESC_STRUCT(num);
        Lng32 nKeys = 0;
        initSP_ERROR_STRUCT();
        if ( (*(procFuncs_.outFormatFunc_)) 
          (fields, keys, &nKeys, compHandle_, procFuncs_.spHandle_, &spError_[0])
          == SP_SUCCESS )
        {
          if (!(t.SetFormat(num, outTableName.data(), fields, nKeys, keys ) ) ) 
          {
            retStatus = FALSE;
          }	  
        }
        else
        {	  
          appendDiags();
          retStatus = FALSE;	  
        }
      
        // It is not supposed to jump out of this function before this  
        // delete[]
        deleteSP_FIELDDESC_STRUCT(fields);      
        deleteSP_KEYDESC_STRUCT(keys);
      }
    }
  else
    {
      appendDiags();
      retStatus = FALSE;
    }  
  if ( !retStatus )
    *(cmpContext()->diags()) << DgSqlCode(arkcmpErrorISPFieldDef);
  return retStatus;
}
const NAString ListOfRangeRows::getText() const
{
  NAString result;
  for (CollIndex i=0; i<entries(); i++) {
     HbaseRangeRows rangeRow = (*this)[i];
     result.append(rangeRow.getText());
  }
  return result;
}
//============================================================================
// This method writes the information related to the NAClusterInfo class to a
// logfile called "NAClusterInfo.txt".
//============================================================================
void NAClusterInfo::captureNAClusterInfo(ofstream & naclfile)
{
  CollIndex i, ci;
  char filepath[OSIM_PATHMAX];
  char filename[OSIM_FNAMEMAX];

  // We don't capture data members that are computed during the compilation of
  // a query. These include:
  //
  // * smpCount_;
  // * tableToClusterMap_;
  // * activeClusters_;
  //

  naclfile << "localCluster_: " << localCluster_ << endl
           << "localSMP_: " << localSMP_ << endl;

  CollIndex *key_collindex;  
  maps *val_maps;
  // Iterator for logging all the entries in clusterToCPUMap_ HashDictionary.
  NAHashDictionaryIterator<CollIndex, maps> C2CPUIter (*clusterToCPUMap_, NULL, NULL);  
  naclfile << "clusterToCPUMap_: " << C2CPUIter.entries() << " :" << endl;
  if (C2CPUIter.entries() > 0)
  {
    // Write the header line for the table.
    naclfile << "  ";
    naclfile.width(10); 
    naclfile << "clusterNum" << "  ";
    naclfile << "cpuList" << endl;
    for (i=0; i<C2CPUIter.entries(); i++)
    {
      C2CPUIter.getNext(key_collindex, val_maps);
      naclfile << "  ";
      naclfile.width(10); naclfile << *key_collindex << "  ";
                          naclfile << val_maps->list->entries() << " : ";
      for (ci=0; ci<val_maps->list->entries(); ci++)
      {
        naclfile.width(3); naclfile << (*(val_maps->list))[ci] << " ";
      }
      naclfile << endl;
    }
  }

  Int32 * nodeID = NULL;
  NAString* nodeName = NULL;
  NAHashDictionaryIterator<Int32, NAString> nodeNameAndIDIter (*nodeIdToNodeNameMap_);
  naclfile << "nodeIdAndNodeNameMap: " << nodeNameAndIDIter.entries() << endl;
  for(nodeNameAndIDIter.getNext(nodeID, nodeName); nodeID && nodeName; nodeNameAndIDIter.getNext(nodeID, nodeName))
  {
      naclfile << *nodeID << " " << nodeName->data() << endl;
  }

  // Now save the OS-specific information to the NAClusterInfo.txt file
  captureOSInfo(naclfile);
}
const NAString HbaseRangeRows::getText() const
{
   NAString result = HbaseSearchSpec::getText();

   result.append("begin_keys");
   result.append(beginKeyExclusive_ ? "(excl)" : "(incl)");
   result.append(": ");

   // rowId_ (begin or end) is in this format: 
   //  <length><data> ... <length><data>
   //
   // a). length is 2-bytes long
   // b). data is <length> bytes long
   // c). there are <n> such pairs, where <n> is determined by
   //     the total length of the data and the length of each pair.

   extractKeyValuePairs(beginRowId_, result); 
         
   result.append(" ");

   result.append("end_keys");
   result.append(endKeyExclusive_ ? "(excl)" : "(incl)");
   result.append(": ");

   extractKeyValuePairs(endRowId_, result);

   result.append(" ");

   return result;
}
//LCOV_EXCL_START /* : cnu -- not used on Linux */
// -----------------------------------------------------------------------
// makeSafeFilenamePart() and
// QualifiedName::getQualifiedNameAsAnsiNTFilenameString()
//
// Genesis 10-990113-5782
// Make sure that the end result of this function results in a valid
// file name for the system -- whether NT or OSS.
//
// Convert any invalid NT filename characters to underscores.
//
// A valid NT (or OSS) filename may be up to 255 characters including spaces.
// The characters
//	\/:*?<>|"
// are not allowed in the filename at all.
// Furthermore, a POSIX shell (MKS KornShell on NT, OSS on NSK)
// treats the following specially, so they do not make good chars for filenames:
//	$%&();' and space
//
// SQL identifiers can be up to 128 characters long in regular or
// delimited format.
//
// Regular identifiers begin with A-Z or a-z and can contain digits 0-9 or
// underscores.  Regular identifiers are not case sensitive.  Reserved words
// may not be used in a regular identifier.
//
// Delimited identifiers always begin with a " character, and can contain
// both upper and lowercase Latin-1 characters, as well as
//	\/|<>*?:"
//	$%&();' and space
//	+-=[],.
//	digits 0-9 and underscore
//
// This routine will convert all non-alphanumeric chars
// to the underscore character, and result in a filename which when treated
// as an Ansi qualified name (a MODULE name), is composed only of regular
// identifiers -- no "quoting" needed.
//
// The length of a module name that might get generated
// could be a string of over 255 characters.  128 for each of the three parts.
// 2 characters for each part if delimited plus the period separators not
// counting any quotes which are embedded and doubled which might be
// singled again.
//
// There might still be problems because NT is not case sensitive but
// SQL is where delimited identifiers are concerned and that is not being
// addressed here.  We're just going to assume that we won't have two
// catalogs and schemas that are the same delimited if case is not considered
// that will cause problems in NT.  We will be replacing all characters
// that cause the name to be delimited with underscore.
//
// If we need to truncate any one of the three parts (not generally the
// user supplied portion (mainly just the module name portion), then we
// will need to verify that the truncated result does not result in a
// reserved word.  Might possibly happen depending on how we decide to
// handle the case where the length of 2 of the parts nears the 255
// character file name limit for NT and we decide to truncate one part
// down to a size that might result in a reserved word.
// -----------------------------------------------------------------------
//
static void makeSafeFilenamePart(NAString &ns, const NAString &prefix)
{
  size_t len = ns.length();
  for (size_t i=0; i<len; i++) {
    if (!isalnum(ns[i]) && ns[i] != '_')
      ns[i] = '_';
  }

  if (!len || !isalpha(ns[(size_t)0]))	// must begin with an alphabetic
    ns.prepend(prefix);
}
NABoolean ISPIterator::initializeISPCaches(SP_ROW_DATA  inputData, SP_EXTRACT_FUNCPTR  eFunc, SP_ERROR_STRUCT* error, 
                                  const NAArray<CmpContextInfo*> & ctxs, //input 
                                  NAString & contextName, 
                                  Int32 & index           //output, set initial index in arrary of CmpContextInfos
                                  ) 
{
//extract ISP input, find QueryCache belonging to specified context
//and use it for fetch later
  Lng32 maxSize = 16;
  char receivingField[maxSize+1];
  if (eFunc (0, inputData, (Lng32)maxSize, receivingField, FALSE) == SP_ERROR_EXTRACT_DATA)
  {
      error->error = arkcmpErrorISPFieldDef;
      return FALSE;
  }
   //choose context
   // 1. Search ctxInfos_ for all context with specified name('USER', 'META', 'USTATS'),
   //    'ALL' option will fetch all context in ctxInfos_, index is set to 0, qcache is always NULL, 
   // 2. For remote arkcmp, which has 0 context in ctxInfos_, index is always -1, 

  NAString qCntxt = receivingField;
  qCntxt.toLower();
  //the receivingField is of pattern xxx$trafodion.yyy, 
  //where xxx is the desired input string.
  Int32 dollarIdx = qCntxt.index("$");
  CMPASSERT(dollarIdx > 0);
  //find the specified context
  if(ctxs.entries() == 0){
    //for remote compiler
    if( (dollarIdx==3 && strncmp(qCntxt.data(), "all", dollarIdx)==0) 
     ||(dollarIdx==4 && strncmp(qCntxt.data(), "user", dollarIdx)==0) )
      index = -1;
  }
  else
  {
    if(dollarIdx==3 && strncmp(qCntxt.data(), "all", dollarIdx)==0)
    {
       contextName = "ALL";
       index = 0;
    }
    else if(dollarIdx==4 && strncmp(qCntxt.data(), "user", dollarIdx)==0)
    {
       contextName = "NONE";
       index = 0;
    }
    else if(dollarIdx==4 && strncmp(qCntxt.data(), "meta", dollarIdx)==0)
    {
       contextName = "META";
       index = 0;
    }
    else if(dollarIdx==6 && strncmp(qCntxt.data(), "ustats", dollarIdx)==0)
    {
       contextName = "USTATS";
       index = 0;
    }
  }           
  return TRUE;
}
const NAString HbaseUniqueRows::getText() const
{
   NAString result = HbaseSearchSpec::getText();

   for ( CollIndex i=0; i<rowIds_.entries(); i++ ) {

      result.append("unique_rows: ");
      extractKeyValuePairs(rowIds_[i], result);
      result.append(" ");
   }

   return result;
}
void QRLogger::log(std::string &cat,
                   logLevel    level,
                   int         sqlCode,
                   const char  *queryId,
                   const char  *logMsgTemplate...)
{

  log4cxx::LoggerPtr myLogger = log4cxx::Logger::getLogger(cat);
  if ( myLogger ) 
  {
    log4cxx::LevelPtr myLevel = myLogger->getLevel();
    log4cxx::LevelPtr paramLevel = log4cxx::Level::toLevel(level);
    if ( myLevel && paramLevel ) 
    {
        if ( myLevel == log4cxx::Level::getOff() )
          return;

        int_32 configuredLevel = myLevel->toInt();
        int_32 requestedLevel = paramLevel->toInt();

        // If the configured logging level is greater (more restrictive) than
        // the requested level, don't log.  
        if ( configuredLevel > requestedLevel)
          return;
    }
  } else return;
  
  va_list args ;
  va_start(args, logMsgTemplate);

  char* buffer = buildMsgBuffer(cat, level, logMsgTemplate, args);
  NAString logData = QRLogger::instance().getMyProcessInfo();
  char sqlCodeBuf[30];
  snprintf(sqlCodeBuf, sizeof(sqlCodeBuf), "%d", sqlCode);
  logData += ",";
  if (sqlCode != 0)
    {
      logData += " SQLCODE: ";
      logData += sqlCodeBuf;
    }
  logData += ",";
  if (queryId != NULL && queryId[0] != '\0')
    {
      logData += " QID: ";
      logData += queryId;
    }
  logData += ", ";
  logData += buffer;
  log1(cat, level, logData.data());
  va_end(args);
}
NABoolean QualifiedName::isHive(const NAString &catName) 
{
  NAString hiveDefCatName = "";
  CmpCommon::getDefault(HIVE_CATALOG, hiveDefCatName, FALSE);
  hiveDefCatName.toUpper();
  
  if (CmpCommon::getDefault(MODE_SEAHIVE) == DF_ON &&
      ((NOT catName.isNull()) &&
       ((catName == HIVE_SYSTEM_CATALOG) ||
	(catName == hiveDefCatName))))
    return TRUE;

  return FALSE;
}
Beispiel #24
0
void CmpSqlSession::setSessionId(NAString &sessionID)
{
  sessionID_ = sessionID;

  if (NOT sessionID_.isNull())
    {
      volatileSchemaName_ = COM_VOLATILE_SCHEMA_PREFIX;
      volatileSchemaName_  += COM_SESSION_ID_PREFIX;
      
      char sName[200];
      Int64 cpu_l;
      Int64 pin_l;
      Int64 schemaNameCreateTime = 0;
      Int64 sessionUniqNum;
      Lng32 userNameLen = 0;
      Lng32 userSessionNameLen = 0;
      ComSqlId::extractSqlSessionIdAttrs
	((char*)sessionID.data(),
	 sessionID.length(),
	 segmentNum_,
	 cpu_l,
	 pin_l,
	 schemaNameCreateTime,
	 sessionUniqNum,
	 userNameLen, NULL,
	 userSessionNameLen, NULL);
      str_sprintf(sName, "%02d%03Ld%06Ld%018Ld%010Ld",
		  ComSqlId::SQ_SQL_ID_VERSION,
		  segmentNum_, pin_l, schemaNameCreateTime,
		  sessionUniqNum);
      volatileSchemaName_ += sName;

      volatileSchemaName_.toUpper();

      // get segment name
      segmentName_ = "NSK";

      sessionInUse_ = TRUE;
      volatileSchemaInUse_ = FALSE;
      //
      // it's a new session
      numSessions_++;
    }
  else
    {
      sessionInUse_ = FALSE;
      volatileSchemaInUse_ = FALSE;
    }
}
Beispiel #25
0
// ----------------------------------------------------------------------------
// method: isAuthNameReserved
//
// Checks to see if proposed name is reserved
//
// Input: authorization name
//
// Output:
//   true - name is reserved
//   false - name is not reserved
// ----------------------------------------------------------------------------
bool CmpSeabaseDDLauth::isAuthNameReserved (const NAString &authName)
{
  bool result;
  result = authName.length() >= strlen(RESERVED_AUTH_NAME_PREFIX)
           &&
           authName.operator()(0,strlen(RESERVED_AUTH_NAME_PREFIX)) ==
                                                   RESERVED_AUTH_NAME_PREFIX
           ||
           authName == "_SYSTEM"
           ||
           authName == "PUBLIC"
           ||
           authName == "NONE";

  return result;
}
HDFS_Client_RetCode HdfsClient::hdfsCreateDirectory(const NAString &dirName)
{
  QRLogger::log(CAT_SQL_HBASE, LL_DEBUG, "Enter HDFSClient_JNI::createDirectory() called.");
  if (initJNIEnv() != JOI_OK)
     return HDFS_CLIENT_ERROR_CREATE_DIRECTORY_PARAM;
  if (getInstance() == NULL)
     return HDFS_CLIENT_ERROR_CREATE_DIRECTORY_PARAM;

  jstring js_dirName = jenv_->NewStringUTF(dirName.data());
  if (js_dirName == NULL) {
     jenv_->PopLocalFrame(NULL);
     return HDFS_CLIENT_ERROR_CREATE_DIRECTORY_PARAM;
  }

  tsRecentJMFromJNI = JavaMethods_[JM_HDFS_CREATE_DIRECTORY].jm_full_name;
  jstring jresult = 
        (jstring)jenv_->CallStaticObjectMethod(javaClass_,
                              JavaMethods_[JM_HDFS_CREATE_DIRECTORY].methodID, js_dirName);
  if (jenv_->ExceptionCheck())
  {
    getExceptionDetails(jenv_);
    logError(CAT_SQL_HBASE, __FILE__, __LINE__);
    logError(CAT_SQL_HBASE, "HDFSClient_JNI::hdfsCreateDirectory()", getLastError());
    jenv_->PopLocalFrame(NULL);
    return HDFS_CLIENT_ERROR_CREATE_DIRECTORY_EXCEPTION;
  }
  if (jresult == false)
  {
    logError(CAT_SQL_HDFS, "HdfsClient::hdfsCreateDirectory()", getLastError());
    jenv_->PopLocalFrame(NULL);
    return HDFS_CLIENT_ERROR_HDFS_DELETE_PATH_EXCEPTION;
  }
  jenv_->PopLocalFrame(NULL);
  return HDFS_CLIENT_OK;
}
Beispiel #27
0
NABoolean CmpSqlSession::validateVolatileSchemaName(NAString &schName)
{
  if (NOT schName.isNull())
    {
      ComSchemaName csn(schName);

      if (NOT csn.isValid())
	{
	  // Schema name $0~SchemaName is not valid.
	  *CmpCommon::diags() << DgSqlCode(-8009) 
			      << DgSchemaName(schName);
	  return FALSE;
	}

      Lng32 len = MINOF(strlen(csn.getSchemaNamePartAsAnsiString().data()),
		       strlen(COM_VOLATILE_SCHEMA_PREFIX));
      NAString upSch(csn.getSchemaNamePartAsAnsiString().data());
      upSch.toUpper();
      if ((NOT Get_SqlParser_Flags(ALLOW_VOLATILE_SCHEMA_IN_TABLE_NAME)) &&
	  (len > 0) &&
	  (strncmp(upSch.data(), COM_VOLATILE_SCHEMA_PREFIX, len) == 0))
	{
	  *CmpCommon::diags() << DgSqlCode(-4193) 
			      << DgString0(COM_VOLATILE_SCHEMA_PREFIX);
	  return FALSE;
	}
    }

  return TRUE;
}
Beispiel #28
0
NABoolean HHDFSTableStats::connectHDFS(const NAString &host, Int32 port)
{
  NABoolean result = TRUE;

  // establish connection to HDFS . Conect to the connection cached in the context.
 
  
  fs_ = ((GetCliGlobals()->currContext())->getHdfsServerConnection((char *)host.data(),port));
     
      
      if (fs_ == NULL)
        {
          NAString errMsg("hdfsConnect to ");
          errMsg += host;
          errMsg += ":";
          errMsg += port;
          errMsg += " failed";
          diags_.recordError(errMsg, "HHDFSTableStats::connectHDFS");
          result = FALSE;
        }
      currHdfsHost_ = host;
      currHdfsPort_ = port;
      //  }
  return result;
}
Beispiel #29
0
// Delete a row from the AUTHS table based on the AUTH_ID
void CmpSeabaseDDLauth::deleteRow(const NAString &authName)
{
  NAString systemCatalog = CmpSeabaseDDL::getSystemCatalogStatic();
  char buf[1000];
  ExeCliInterface cliInterface(STMTHEAP);
  str_sprintf(buf, "delete from %s.\"%s\".%s where auth_db_name = '%s'",
              systemCatalog.data(), SEABASE_MD_SCHEMA, SEABASE_AUTHS, authName.data());
  Lng32 cliRC = cliInterface.executeImmediate(buf);
  
  if (cliRC < 0)
  {
    cliInterface.retrieveSQLDiagnostics(CmpCommon::diags());
    UserException excp (NULL, 0);
    excp.throwException();
  }
}
HDFS_Client_RetCode HdfsClient::hdfsMergeFiles( const NAString& srcPath,
                                                const NAString& dstPath)
{
  QRLogger::log(CAT_SQL_HDFS, LL_DEBUG, "HdfsClient::hdfsMergeFiles(%s, %s) called.",
                  srcPath.data(), dstPath.data());

  if (initJNIEnv() != JOI_OK)
     return HDFS_CLIENT_ERROR_HDFS_MERGE_FILES_PARAM;
  if (getInstance() == NULL)
     return HDFS_CLIENT_ERROR_HDFS_MERGE_FILES_PARAM;
  jstring js_SrcPath = jenv_->NewStringUTF(srcPath.data());

  if (js_SrcPath == NULL) {
     GetCliGlobals()->setJniErrorStr(getErrorText(HDFS_CLIENT_ERROR_HDFS_MERGE_FILES_PARAM));
     jenv_->PopLocalFrame(NULL);
     return HDFS_CLIENT_ERROR_HDFS_MERGE_FILES_PARAM;
  }
  jstring js_DstPath= jenv_->NewStringUTF(dstPath.data());
  if (js_DstPath == NULL) {
     GetCliGlobals()->setJniErrorStr(getErrorText(HDFS_CLIENT_ERROR_HDFS_MERGE_FILES_PARAM));
     jenv_->PopLocalFrame(NULL);
     return HDFS_CLIENT_ERROR_HDFS_MERGE_FILES_PARAM;
  }


  tsRecentJMFromJNI = JavaMethods_[JM_HDFS_MERGE_FILES].jm_full_name;
  jboolean jresult = jenv_->CallStaticBooleanMethod(javaClass_, JavaMethods_[JM_HDFS_MERGE_FILES].methodID, js_SrcPath, js_DstPath);

  if (jenv_->ExceptionCheck())
  {
    getExceptionDetails();
    logError(CAT_SQL_HDFS, __FILE__, __LINE__);
    logError(CAT_SQL_HDFS, "HdfsClient::hdfsMergeFiles()", getLastError());
    jenv_->PopLocalFrame(NULL);
    return HDFS_CLIENT_ERROR_HDFS_MERGE_FILES_EXCEPTION;
  }

  if (jresult == false)
  {
    logError(CAT_SQL_HDFS, "HdfsClient::hdfsMergeFiles()", getLastError());
    jenv_->PopLocalFrame(NULL);
    return HDFS_CLIENT_ERROR_HDFS_MERGE_FILES_EXCEPTION;
  } 

  jenv_->PopLocalFrame(NULL);
  return HDFS_CLIENT_OK;
}