/* {{{ MySQL_Connection::getClientOption() -I- */
void
MySQL_Connection::getClientOption(const sql::SQLString & optionName, void * optionValue)
{
	CPP_ENTER_WL(intern->logger, "MySQL_Connection::getClientOption");
	if (!optionName.compare("metadataUseInfoSchema")) {
		*(static_cast<bool *>(optionValue)) = intern->metadata_use_info_schema;
	} else if (!optionName.compare("defaultStatementResultType")) {
		*(static_cast<int *>(optionValue)) = intern->defaultStatementResultType;
	} else if (!optionName.compare("defaultPreparedStatementResultType")) {
		*(static_cast<int *>(optionValue)) = intern->defaultPreparedStatementResultType;
	} else if (!optionName.compare("multiByteMinLength")) {
		MY_CHARSET_INFO cs;
		proxy->get_character_set_info(&cs);
		*(static_cast<int *>(optionValue)) = cs.mbminlen;
	} else if (!optionName.compare("multiByteMaxLength")) {
		MY_CHARSET_INFO cs;
		proxy->get_character_set_info(&cs);
		*(static_cast<int *>(optionValue)) = cs.mbmaxlen;
	/* mysql_get_option() was added in mysql 5.7.3 version */
	} else if ( proxy->get_server_version() >= 50703 ) {
		try {
			if (GET_CONN_OPTION(optionName, optionValue, intOptions)) {
				return;
			} else if (GET_CONN_OPTION(optionName, optionValue, booleanOptions)) {
				return;
			} else if (GET_CONN_OPTION(optionName, optionValue, stringOptions)) {
				return;
			}
		} catch (sql::SQLUnsupportedOptionException& e) {
			CPP_ERR_FMT("Unsupported option : %d:(%s) %s", proxy->errNo(), proxy->sqlstate().c_str(), proxy->error().c_str());
			throw e;
		}
	}
}
/* {{{ MySQL_Connection::getClientOption() -I- */
void
MySQL_Connection::getClientOption(const sql::SQLString & optionName, void * optionValue)
{
	CPP_ENTER_WL(intern->logger, "MySQL_Connection::getClientOption");
	if (!optionName.compare("metadataUseInfoSchema")) {
		*(static_cast<bool *>(optionValue)) = intern->metadata_use_info_schema;
	} else if (!optionName.compare("defaultStatementResultType")) {
		*(static_cast<int *>(optionValue)) = intern->defaultStatementResultType;
	} else if (!optionName.compare("defaultPreparedStatementResultType")) {
		*(static_cast<int *>(optionValue)) = intern->defaultPreparedStatementResultType;
	} else if (!optionName.compare("characterSetResults")) {
		*(static_cast<sql::SQLString **>(optionValue)) = new sql::SQLString(getSessionVariable("characterSetResults"));
	}
}
/* {{{ MySQL_Connection::getClientOption() -I- */
sql::SQLString
MySQL_Connection::getClientOption(const sql::SQLString & optionName)
{
	CPP_ENTER_WL(intern->logger, "MySQL_Connection::getClientOption");

	if (!optionName.compare("characterSetResults")) {
		return sql::SQLString(getSessionVariable("character_set_results"));
	} else if (!optionName.compare("characterSetDirectory")) {
		MY_CHARSET_INFO cs;
		proxy->get_character_set_info(&cs);
		return cs.dir ? sql::SQLString(cs.dir) : "";
	} else if ( proxy->get_server_version() >= 50703 ) {
		const char* optionValue= NULL;
		if (GET_CONN_OPTION(optionName, &optionValue, stringOptions)) {
			return optionValue ? sql::SQLString(optionValue) : "";
		}
	}
	return "";
}
/* {{{ MySQL_Connection::getSessionVariable() -I- */
sql::SQLString
MySQL_Connection::getSessionVariable(const sql::SQLString & varname)
{
	CPP_ENTER_WL(intern->logger, "MySQL_Connection::getSessionVariable");
	checkClosed();

	if (intern->cache_sql_mode && intern->sql_mode_set == true && !varname.compare("sql_mode")) {
		CPP_INFO_FMT("sql_mode=%s", intern->sql_mode.c_str());
		return intern->sql_mode;
	}
	sql::SQLString q("SHOW SESSION VARIABLES LIKE '");
	q.append(varname).append("'");

	boost::scoped_ptr< sql::ResultSet > rset(service->executeQuery(q));

	if (rset->next()) {
		if (intern->cache_sql_mode && intern->sql_mode_set == false && !varname.compare("sql_mode")) {
			intern->sql_mode = rset->getString(2);
			intern->sql_mode_set = true;
		}
		return rset->getString(2);
	}
	return "";
}
bool get_connection_option(const sql::SQLString optionName,
								void *optionValue,
								const String2IntMap options_map[],
								size_t map_size,
								boost::shared_ptr< NativeAPI::NativeConnectionWrapper > &proxy)
{
	for (size_t i = 0; i < map_size; ++i) {
		if (!optionName.compare(options_map[i].key)) {
			try {
				proxy->get_option(static_cast<sql::mysql::MySQL_Connection_Options>(options_map[i].value), optionValue);
			} catch (sql::InvalidArgumentException& e) {
				std::string errorOption(options_map[i].key);
				throw ::sql::SQLUnsupportedOptionException(e.what(), errorOption);
			}
			return true;
		}
	}
	return false;
}
/* {{{ MySQL_Connection::setSessionVariable() -I- */
void
MySQL_Connection::setSessionVariable(const sql::SQLString & varname, const sql::SQLString & value)
{
	CPP_ENTER_WL(intern->logger, "MySQL_Connection::setSessionVariable");
	checkClosed();

	sql::SQLString q("SET SESSION ");
	q.append(varname).append("=");

	if (!value.compare("NULL")) {
		q.append("NULL");
	} else {
		q.append("'").append(value).append("'");
	}

	service->executeUpdate(q);
	if (intern->cache_sql_mode && !strncasecmp(varname.c_str(), "sql_mode", sizeof("sql_mode") - 1)) {
		intern->sql_mode= value;
	}
}
/* URI formats tcp://[host]:port/schema
               unix://socket
               pipe://named_pipe
 */
bool parseUri(const sql::SQLString & str, MySQL_Uri& uri)
{
  if (!str.compare(0, sizeof(MYURI_SOCKET_PREFIX) - 1, MYURI_SOCKET_PREFIX))
  {
    uri.setSocket(str.substr(sizeof(MYURI_SOCKET_PREFIX) - 1, sql::SQLString::npos));

    return true;
  }

  if (!str.compare(0, sizeof(MYURI_PIPE_PREFIX) - 1 , MYURI_PIPE_PREFIX))
  {
    uri.setPipe(str.substr(sizeof(MYURI_PIPE_PREFIX) - 1, sql::SQLString::npos));

    return true;
  }

  sql::SQLString host;
  size_t start_sep, end_sep;

  /* i wonder how did it work with "- 1"*/
  if (!str.compare(0, sizeof(MYURI_TCP_PREFIX) - 1, MYURI_TCP_PREFIX) )
  {
    host= str.substr(sizeof(MYURI_TCP_PREFIX) - 1, sql::SQLString::npos);
  }
  else
  {
    /* allowing to have port and schema specified even w/out protocol
       specifier("tcp://") */
    host= str.c_str();
  }

  if (host[0] == MYURI_HOST_BEGIN)
  {
    end_sep= host.find(MYURI_HOST_END);

    /* No closing ] after [*/
    if (end_sep == sql::SQLString::npos)
    {
      return false;
    }

    uri.setHost(host.substr(1, end_sep - 1));
    /* Cutting host to continue w/ port and schema reading */
    host= host.substr(end_sep + 1);
  }

  /* Looking where schema part begins */
  start_sep = host.find('/');

  if (start_sep != sql::SQLString::npos)
  {
    if ((host.length() - start_sep) > 1/*Slash*/)
    {
      uri.setSchema(host.substr(start_sep + 1, host.length() - start_sep - 1));
    }

    host= host.substr(0, start_sep);
  }
  else
  {
    uri.setSchema("");
  }

  /* Looking where port part begins*/
  start_sep = host.find_last_of(':', sql::SQLString::npos);

  if (start_sep != sql::SQLString::npos)
  {
    uri.setPort(atoi(host.substr(start_sep + 1, sql::SQLString::npos).c_str()));
    host = host.substr(0, start_sep);
  }
  else
  {
    uri.setPort(DEFAULT_TCP_PORT);
  }

  /* If host was enclosed in [], it has been already set, and "host" variable is
     empty */
  if (host.length() > 0)
  {
    uri.setHost(host);
  }

  return true;
}