OGRFeature *OGRMySQLTableLayer::GetFeature( GIntBig nFeatureId )

{
    if( pszFIDColumn == NULL )
        return OGRMySQLLayer::GetFeature( nFeatureId );

/* -------------------------------------------------------------------- */
/*      Discard any existing resultset.                                 */
/* -------------------------------------------------------------------- */
    ResetReading();

/* -------------------------------------------------------------------- */
/*      Prepare query command that will just fetch the one record of    */
/*      interest.                                                       */
/* -------------------------------------------------------------------- */
    char        *pszFieldList = BuildFields();
    CPLString    osCommand;

    osCommand.Printf(
             "SELECT %s FROM `%s` WHERE `%s` = " CPL_FRMT_GIB,
             pszFieldList, poFeatureDefn->GetName(), pszFIDColumn,
             nFeatureId );
    CPLFree( pszFieldList );

/* -------------------------------------------------------------------- */
/*      Issue the command.                                              */
/* -------------------------------------------------------------------- */
    if( mysql_query( poDS->GetConn(), osCommand ) )
    {
        poDS->ReportError( osCommand );
        return NULL;
    }

    hResultSet = mysql_store_result( poDS->GetConn() );
    if( hResultSet == NULL )
    {
        poDS->ReportError( "mysql_store_result() failed on query." );
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Fetch the result record.                                        */
/* -------------------------------------------------------------------- */
    char **papszRow;
    unsigned long *panLengths;

    papszRow = mysql_fetch_row( hResultSet );
    if( papszRow == NULL )
        return NULL;

    panLengths = mysql_fetch_lengths( hResultSet );

/* -------------------------------------------------------------------- */
/*      Transform into a feature.                                       */
/* -------------------------------------------------------------------- */
    iNextShapeId = nFeatureId;

    OGRFeature *poFeature = RecordToFeature( papszRow, panLengths );

    iNextShapeId = 0;

/* -------------------------------------------------------------------- */
/*      Cleanup                                                         */
/* -------------------------------------------------------------------- */
    if( hResultSet != NULL )
        mysql_free_result( hResultSet );
 		hResultSet = NULL;

    return poFeature;
}
Beispiel #2
0
extern int setup_job_cluster_cond_limits(mysql_conn_t *mysql_conn,
					 slurmdb_job_cond_t *job_cond,
					 char *cluster_name, char **extra)
{
	int set = 0;
	ListIterator itr = NULL;
	char *object = NULL;

	if (!job_cond)
		return SLURM_SUCCESS;

	/* this must be done before resvid_list since we set
	   resvid_list up here */
	if (job_cond->resv_list && list_count(job_cond->resv_list)) {
		char *query = xstrdup_printf(
			"select distinct job_db_inx from \"%s_%s\" where (",
			cluster_name, job_table);
		int my_set = 0;
		MYSQL_RES *result = NULL;
		MYSQL_ROW row;

		itr = list_iterator_create(job_cond->resv_list);
		while ((object = list_next(itr))) {
			if (my_set)
				xstrcat(query, " || ");
			xstrfmtcat(query, "resv_name='%s'", object);
			my_set = 1;
		}
		list_iterator_destroy(itr);
		xstrcat(query, ")");
		if (!(result = mysql_db_query_ret(
			      mysql_conn, query, 0))) {
			xfree(query);
			error("couldn't query the database");
			goto no_resv;
		}
		xfree(query);
		if (!job_cond->resvid_list)
			job_cond->resvid_list = list_create(slurm_destroy_char);
		while ((row = mysql_fetch_row(result))) {
			list_append(job_cond->resvid_list, xstrdup(row[0]));
		}
		mysql_free_result(result);
	}
no_resv:

	if (job_cond->resvid_list && list_count(job_cond->resvid_list)) {
		set = 0;
		if (*extra)
			xstrcat(*extra, " && (");
		else
			xstrcat(*extra, " where (");
		itr = list_iterator_create(job_cond->resvid_list);
		while ((object = list_next(itr))) {
			if (set)
				xstrcat(*extra, " || ");
			xstrfmtcat(*extra, "t1.id_resv='%s'", object);
			set = 1;
		}
		list_iterator_destroy(itr);
		xstrcat(*extra, ")");
	}

	if (job_cond->state_list && list_count(job_cond->state_list)) {
		itr = list_iterator_create(job_cond->state_list);
		while ((object = list_next(itr))) {
			uint32_t state = (uint32_t)slurm_atoul(object);
			state &= JOB_STATE_BASE;
			if (state == JOB_SUSPENDED)
				break;
		}
		list_iterator_destroy(itr);

		if (object) {
			MYSQL_RES *result = NULL;
			MYSQL_ROW row;
			char *query = xstrdup_printf(
				"select job_db_inx from \"%s_%s\"",
				cluster_name, suspend_table);
			if (job_cond->usage_start) {
				if (!job_cond->usage_end) {
					xstrfmtcat(query,
						   " where (!time_end "
						   "|| (%d between "
						   "time_start and time_end))",
						   (int)job_cond->usage_start);
				} else {
					xstrfmtcat(query,
						   " where (!time_end "
						   "|| (time_start && "
						   "((%d between time_start "
						   "and time_end) "
						   "|| (time_start between "
						   "%d and %d))))",
						   (int)job_cond->usage_start,
						   (int)job_cond->usage_start,
						   (int)job_cond->usage_end);
				}
			} else if (job_cond->usage_end) {
				xstrfmtcat(query, " where (time_start && "
					   "time_start < %d)",
					   (int)job_cond->usage_end);
			}

			debug3("%d(%s:%d) query\n%s",
			       mysql_conn->conn, THIS_FILE, __LINE__, query);
			result = mysql_db_query_ret(mysql_conn, query, 0);
			xfree(query);
			if (!result)
				return SLURM_ERROR;
			set = 0;
			while ((row = mysql_fetch_row(result))) {
				if (set)
					xstrfmtcat(*extra,
						   " || t1.job_db_inx=%s",
						   row[0]);
				else {
					set = 1;
					if (*extra)
						xstrfmtcat(
							*extra,
							" || (t1.job_db_inx=%s",
							row[0]);
					else
						xstrfmtcat(*extra, " where "
							   "(t1.job_db_inx=%s",
							   row[0]);
				}
			}
			mysql_free_result(result);
			if (set)
				xstrcat(*extra, ")");
		}
	}

	return SLURM_SUCCESS;
}
Beispiel #3
0
static int test1(MYSQL *mysql)
{
  MYSQL_ROW row;
  MYSQL_RES *res;
  int rc;

  MYSQL *my= mysql_init(NULL);
  FAIL_IF(!my, "mysql_init() failed");

  mysql_options(my, MYSQL_DATABASE_DRIVER, "sqlite");

  FAIL_IF(!mysql_real_connect(my, hostname, username, password, (schema) ? schema : "test",
                         port, socketname, 0), mysql_error(my));

  diag("Server name: %s", mysql_get_server_name(my));

  diag("Connected to: %s (%lu)", mysql_get_server_info(my), mysql_get_server_version(my));

  rc= mysql_query(my, "CREATE TABLE t1 (a int, b varchar(255))");
  rc= mysql_query(my, "DELETE FROM t1");
  check_mysql_rc(rc, my);

  rc= mysql_query(my, "BEGIN");
  check_mysql_rc(rc, my);
  rc= mysql_query(my, "INSERT INTO t1 VALUES (1, 'Monty')");
  check_mysql_rc(rc, my);
  rc= mysql_query(my, "INSERT INTO t1 VALUES (2, 'Serg')");
  check_mysql_rc(rc, my);
  rc= mysql_query(my, "INSERT INTO t1 VALUES (3, 'Holyfoot')");
  check_mysql_rc(rc, my);
  rc= mysql_query(my, "INSERT INTO t1 VALUES (4, 'Rasmus')");
  check_mysql_rc(rc, my);
  rc= mysql_query(my, "INSERT INTO t1 VALUES (5, 'Sanja')");
  check_mysql_rc(rc, my);
  rc= mysql_query(my, "COMMIT");
  check_mysql_rc(rc, my);

  rc= mysql_query(my, "SELECT a,b FROM t1");
  check_mysql_rc(rc, my);
  res= mysql_use_result(my);
  FAIL_IF(!res, mysql_error(my));

  while ((row= mysql_fetch_row(res)) != NULL)
  {
    FAIL_IF(mysql_num_fields(res) != 2, "Got the wrong number of fields");
  }
  FAIL_IF(mysql_num_rows(res) != 5, "expected 5 rows");
  FAIL_IF(mysql_errno(my), mysql_error(my));

  mysql_free_result(res);

  rc= mysql_query(my, "SELECT a FROM t1");
  check_mysql_rc(rc, my);
  res= mysql_use_result(my);
  mysql_free_result(res);

  FAIL_IF(mysql_errno(my), mysql_error(my));

  mysql_close(my);

  return OK;
}
Beispiel #4
0
//We run this on nodes with clone containers.
//It compares the md5sum hash of the clone container
//against the ssh remote gathered md5sum of the clone
//container uSource container.
//Only reporting those that do not match.
void CheckConf(void)
{
        MYSQL_RES *res;
        MYSQL_ROW field;
	unsigned uDatacenter=0;
	unsigned uNode=0;
	unsigned uContainer=0;
	unsigned uSource=0;
	FILE *fp;
	char cCommand[128];
	char cLocalMD5Sum[64];
	char cRemoteMD5Sum[64];

	if(gethostname(cHostname,99)!=0)
	{
		logfileLine("CheckConf","gethostname() failed",uContainer);
		exit(1);
	}

	//Uses login data from local.h
	TextConnectDb();
	guLoginClient=1;//Root user

	sprintf(gcQuery,"SELECT uNode,uDatacenter,uOwner FROM tNode WHERE cLabel='%.99s'",cHostname);
	mysql_query(&gMysql,gcQuery);
	if(mysql_errno(&gMysql))
	{
		logfileLine("CheckConf",mysql_error(&gMysql),uContainer);
		mysql_close(&gMysql);
		exit(2);
	}
        res=mysql_store_result(&gMysql);
	if((field=mysql_fetch_row(res)))
	{
		sscanf(field[0],"%u",&uNode);
		sscanf(field[1],"%u",&uDatacenter);
		sscanf(field[2],"%u",&guNodeOwner);
	}
	mysql_free_result(res);
	if(!uNode)
	{
		char *cp;

		//FQDN vs short name of 2nd NIC mess
		if((cp=strchr(cHostname,'.')))
			*cp=0;
		sprintf(gcQuery,"SELECT uNode,uDatacenter,uOwner FROM tNode WHERE cLabel='%.99s'",cHostname);
		mysql_query(&gMysql,gcQuery);
		if(mysql_errno(&gMysql))
		{
			logfileLine("CheckConf",mysql_error(&gMysql),uContainer);
			mysql_close(&gMysql);
			exit(2);
		}
		res=mysql_store_result(&gMysql);
		if((field=mysql_fetch_row(res)))
		{
			sscanf(field[0],"%u",&uNode);
			sscanf(field[1],"%u",&uDatacenter);
			sscanf(field[2],"%u",&guNodeOwner);
		}
		mysql_free_result(res);
	}

	if(!uNode)
	{
		logfileLine("CheckConf","Could not determine uNode",uContainer);
		mysql_close(&gMysql);
		exit(1);
	}

	//debug only
	printf("CheckConf() for %s (uNode=%u,uDatacenter=%u)\n",
			cHostname,uNode,uDatacenter);

	//Main loop. TODO use defines for tStatus.uStatus values.
	sprintf(gcQuery,"SELECT uContainer,uSource FROM tContainer WHERE uNode=%u"
				" AND uDatacenter=%u"
				" AND uSource>0"
				" AND (uStatus=1"//Active OR
				" OR uStatus=31)"//Stopped
						,uNode,uDatacenter);
	mysql_query(&gMysql,gcQuery);
	if(mysql_errno(&gMysql))
	{
		logfileLine("CheckConf",mysql_error(&gMysql),uContainer);
		mysql_close(&gMysql);
		exit(2);
	}
        res=mysql_store_result(&gMysql);
	while((field=mysql_fetch_row(res)))
	{
		if(sysinfo(&structSysinfo))
		{
			logfileLine("CheckConf","sysinfo() failed",0);
			exit(1);
		}
		if(structSysinfo.loads[1]/LINUX_SYSINFO_LOADS_SCALE>JOBQUEUE_MAXLOAD)
		{
			logfileLine("CheckConf","structSysinfo.loads[1] larger than JOBQUEUE_MAXLOAD",0);
			mysql_free_result(res);
			mysql_close(&gMysql);
			return;
		}

		sscanf(field[0],"%u",&uContainer);
		sscanf(field[1],"%u",&uSource);

		//local first
		sprintf(cCommand,"cat /etc/vz/conf/%u.conf|grep -v IP_ADDRESS|grep -v ONBOOT|grep -v NAME|/usr/bin/md5sum",
					uContainer);
		if((fp=popen(cCommand,"r"))==NULL)
		{
			logfileLine("CheckConf",cCommand,0);
			pclose(fp);
			continue;
		}
		fgets(cLocalMD5Sum,33,fp);
		pclose(fp);

		//remote
		char cHost[100]={""};
		GetNodeHostnameFromContainer(uSource,cHost);
		sprintf(cCommand,"/usr/bin/ssh -c arcfour %s "
				"\"cat /etc/vz/conf/%u.conf|grep -v IP_ADDRESS|grep -v ONBOOT|grep -v NAME|/usr/bin/md5sum\"",
					cHost,uSource);
		if((fp=popen(cCommand,"r"))==NULL)
		{
			logfileLine("CheckConf",cCommand,0);
			pclose(fp);
			continue;
		}
		fgets(cRemoteMD5Sum,33,fp);

		if(strcmp(cLocalMD5Sum,cRemoteMD5Sum))
			printf("/etc/vz/conf/ file mismatch for %u %s %u %s\n",uContainer,cLocalMD5Sum,uSource,cRemoteMD5Sum);
	}
	mysql_free_result(res);
	mysql_close(&gMysql);

}//void CheckConf(void)
Beispiel #5
0
static int _cluster_get_jobs(mysql_conn_t *mysql_conn,
			     slurmdb_user_rec_t *user,
			     slurmdb_job_cond_t *job_cond,
			     char *cluster_name,
			     char *job_fields, char *step_fields,
			     char *sent_extra,
			     bool is_admin, int only_pending, List sent_list)
{
	char *query = NULL;
	char *extra = xstrdup(sent_extra);
	uint16_t private_data = slurm_get_private_data();
	slurmdb_selected_step_t *selected_step = NULL;
	MYSQL_RES *result = NULL, *step_result = NULL;
	MYSQL_ROW row, step_row;
	slurmdb_job_rec_t *job = NULL;
	slurmdb_step_rec_t *step = NULL;
	time_t now = time(NULL);
	List job_list = list_create(slurmdb_destroy_job_rec);
	ListIterator itr = NULL;
	List local_cluster_list = NULL;
	int set = 0;
	char *prefix="t2";
	int rc = SLURM_SUCCESS;
	int last_id = -1, curr_id = -1;
	local_cluster_t *curr_cluster = NULL;

	/* This is here to make sure we are looking at only this user
	 * if this flag is set.  We also include any accounts they may be
	 * coordinator of.
	 */
	if (!is_admin && (private_data & PRIVATE_DATA_JOBS)) {
		query = xstrdup_printf("select lft from \"%s_%s\" "
				       "where user='%s'",
				       cluster_name, assoc_table, user->name);
		if (user->coord_accts) {
			slurmdb_coord_rec_t *coord = NULL;
			itr = list_iterator_create(user->coord_accts);
			while ((coord = list_next(itr))) {
				xstrfmtcat(query, " || acct='%s'",
					   coord->name);
			}
			list_iterator_destroy(itr);
		}
		debug3("%d(%s:%d) query\n%s",
		       mysql_conn->conn, THIS_FILE, __LINE__, query);
		if (!(result = mysql_db_query_ret(
			      mysql_conn, query, 0))) {
			xfree(extra);
			xfree(query);
			rc = SLURM_ERROR;
			goto end_it;
		}
		xfree(query);
		set = 0;
		while ((row = mysql_fetch_row(result))) {
			if (set) {
				xstrfmtcat(extra,
					   " || (%s between %s.lft and %s.rgt)",
					   row[0], prefix, prefix);
			} else {
				set = 1;
				if (extra)
					xstrfmtcat(extra,
						   " && ((%s between %s.lft "
						   "and %s.rgt)",
						   row[0], prefix,
						   prefix);
				else
					xstrfmtcat(extra,
						   " where ((%s between %s.lft "
						   "and %s.rgt)",
						   row[0], prefix,
						   prefix);
			}
		}
		if (set)
			xstrcat(extra,")");
		mysql_free_result(result);
	}

	setup_job_cluster_cond_limits(mysql_conn, job_cond,
				      cluster_name, &extra);

	query = xstrdup_printf("select %s from \"%s_%s\" as t1 "
			       "left join \"%s_%s\" as t2 "
			       "on t1.id_assoc=t2.id_assoc",
			       job_fields, cluster_name, job_table,
			       cluster_name, assoc_table);
	if (extra) {
		xstrcat(query, extra);
		xfree(extra);
	}

	/* Here we want to order them this way in such a way so it is
	   easy to look for duplicates, it is also easy to sort the
	   resized jobs.
	*/
	xstrcat(query, " group by id_job, time_submit desc");

	debug3("%d(%s:%d) query\n%s",
	       mysql_conn->conn, THIS_FILE, __LINE__, query);
	if (!(result = mysql_db_query_ret(mysql_conn, query, 0))) {
		xfree(query);
		rc = SLURM_ERROR;
		goto end_it;
	}
	xfree(query);


	/* Here we set up environment to check used nodes of jobs.
	   Since we store the bitmap of the entire cluster we can use
	   that to set up a hostlist and set up the bitmap to make
	   things work.  This should go before the setup of conds
	   since we could update the start/end time.
	*/
	if (job_cond && job_cond->used_nodes) {
		local_cluster_list = setup_cluster_list_with_inx(
			mysql_conn, job_cond, (void **)&curr_cluster);
		if (!local_cluster_list) {
			rc = SLURM_ERROR;
			goto end_it;
		}
	}

	while ((row = mysql_fetch_row(result))) {
		char *id = row[JOB_REQ_ID];
		bool job_ended = 0;
		int submit = slurm_atoul(row[JOB_REQ_SUBMIT]);

		curr_id = slurm_atoul(row[JOB_REQ_JOBID]);

		if (job_cond && !job_cond->duplicates
		    && (curr_id == last_id)
		    && (slurm_atoul(row[JOB_REQ_STATE]) != JOB_RESIZING))
			continue;

		/* check the bitmap to see if this is one of the jobs
		   we are looking for */
		if (!good_nodes_from_inx(local_cluster_list,
					 (void **)&curr_cluster,
					 row[JOB_REQ_NODE_INX], submit)) {
			last_id = curr_id;
			continue;
		}

		job = slurmdb_create_job_rec();
		job->state = slurm_atoul(row[JOB_REQ_STATE]);
		if (curr_id == last_id)
			/* put in reverse so we order by the submit getting
			   larger which it is given to us in reverse
			   order from the database */
			list_prepend(job_list, job);
		else
			list_append(job_list, job);
		last_id = curr_id;

		job->alloc_cpus = slurm_atoul(row[JOB_REQ_ALLOC_CPUS]);
		job->alloc_nodes = slurm_atoul(row[JOB_REQ_ALLOC_NODES]);
		job->associd = slurm_atoul(row[JOB_REQ_ASSOCID]);
		job->resvid = slurm_atoul(row[JOB_REQ_RESVID]);

		job->cluster = xstrdup(cluster_name);

		/* we want a blank wckey if the name is null */
		if (row[JOB_REQ_WCKEY])
			job->wckey = xstrdup(row[JOB_REQ_WCKEY]);
		else
			job->wckey = xstrdup("");
		job->wckeyid = slurm_atoul(row[JOB_REQ_WCKEYID]);

		if (row[JOB_REQ_USER_NAME])
			job->user = xstrdup(row[JOB_REQ_USER_NAME]);
		else
			job->uid = slurm_atoul(row[JOB_REQ_UID]);

		if (row[JOB_REQ_LFT])
			job->lft = slurm_atoul(row[JOB_REQ_LFT]);

		if (row[JOB_REQ_ACCOUNT] && row[JOB_REQ_ACCOUNT][0])
			job->account = xstrdup(row[JOB_REQ_ACCOUNT]);
		else if (row[JOB_REQ_ACCOUNT1] && row[JOB_REQ_ACCOUNT1][0])
			job->account = xstrdup(row[JOB_REQ_ACCOUNT1]);

		if (row[JOB_REQ_BLOCKID])
			job->blockid = xstrdup(row[JOB_REQ_BLOCKID]);

		job->eligible = slurm_atoul(row[JOB_REQ_ELIGIBLE]);
		job->submit = submit;
		job->start = slurm_atoul(row[JOB_REQ_START]);
		job->end = slurm_atoul(row[JOB_REQ_END]);
		job->timelimit = slurm_atoul(row[JOB_REQ_TIMELIMIT]);

		/* since the job->end could be set later end it here */
		if (job->end) {
			job_ended = 1;
			if (!job->start || (job->start > job->end))
				job->start = job->end;
		}

		if (job_cond && !job_cond->without_usage_truncation
		    && job_cond->usage_start) {
			if (job->start && (job->start < job_cond->usage_start))
				job->start = job_cond->usage_start;

			if (!job->end || job->end > job_cond->usage_end)
				job->end = job_cond->usage_end;

			if (!job->start)
				job->start = job->end;

			job->elapsed = job->end - job->start;

			if (row[JOB_REQ_SUSPENDED]) {
				MYSQL_RES *result2 = NULL;
				MYSQL_ROW row2;
				/* get the suspended time for this job */
				query = xstrdup_printf(
					"select time_start, time_end from "
					"\"%s_%s\" where "
					"(time_start < %ld && (time_end >= %ld "
					"|| time_end = 0)) && job_db_inx=%s "
					"order by time_start",
					cluster_name, suspend_table,
					job_cond->usage_end,
					job_cond->usage_start,
					id);

				debug4("%d(%s:%d) query\n%s",
				       mysql_conn->conn, THIS_FILE,
				       __LINE__, query);
				if (!(result2 = mysql_db_query_ret(
					      mysql_conn,
					      query, 0))) {
					list_destroy(job_list);
					job_list = NULL;
					break;
				}
				xfree(query);
				while ((row2 = mysql_fetch_row(result2))) {
					time_t local_start =
						slurm_atoul(row2[0]);
					time_t local_end =
						slurm_atoul(row2[1]);

					if (!local_start)
						continue;

					if (job->start > local_start)
						local_start = job->start;
					if (job->end < local_end)
						local_end = job->end;

					if ((local_end - local_start) < 1)
						continue;

					job->elapsed -=
						(local_end - local_start);
					job->suspended +=
						(local_end - local_start);
				}
				mysql_free_result(result2);

			}
		} else {
			job->suspended = slurm_atoul(row[JOB_REQ_SUSPENDED]);

			/* fix the suspended number to be correct */
			if (job->state == JOB_SUSPENDED)
				job->suspended = now - job->suspended;
			if (!job->start) {
				job->elapsed = 0;
			} else if (!job->end) {
				job->elapsed = now - job->start;
			} else {
				job->elapsed = job->end - job->start;
			}

			job->elapsed -= job->suspended;
		}

		if ((int)job->elapsed < 0)
			job->elapsed = 0;

		job->jobid = curr_id;
		job->jobname = xstrdup(row[JOB_REQ_NAME]);
		job->gid = slurm_atoul(row[JOB_REQ_GID]);
		job->exitcode = slurm_atoul(row[JOB_REQ_EXIT_CODE]);
		job->derived_ec = slurm_atoul(row[JOB_REQ_DERIVED_EC]);
		job->derived_es = xstrdup(row[JOB_REQ_DERIVED_ES]);

		if (row[JOB_REQ_PARTITION])
			job->partition = xstrdup(row[JOB_REQ_PARTITION]);

		if (row[JOB_REQ_NODELIST])
			job->nodes = xstrdup(row[JOB_REQ_NODELIST]);

		if (!job->nodes || !strcmp(job->nodes, "(null)")) {
			xfree(job->nodes);
			job->nodes = xstrdup("(unknown)");
		}

		job->track_steps = slurm_atoul(row[JOB_REQ_TRACKSTEPS]);
		job->priority = slurm_atoul(row[JOB_REQ_PRIORITY]);
		job->req_cpus = slurm_atoul(row[JOB_REQ_REQ_CPUS]);
		job->requid = slurm_atoul(row[JOB_REQ_KILL_REQUID]);
		job->qosid = slurm_atoul(row[JOB_REQ_QOS]);
		job->show_full = 1;

		if (only_pending || (job_cond && job_cond->without_steps))
			goto skip_steps;

		if (job_cond && job_cond->step_list
		    && list_count(job_cond->step_list)) {
			set = 0;
			itr = list_iterator_create(job_cond->step_list);
			while ((selected_step = list_next(itr))) {
				if (selected_step->jobid != job->jobid) {
					continue;
				} else if (selected_step->stepid == NO_VAL) {
					job->show_full = 1;
					break;
				} else if (selected_step->stepid == INFINITE)
					selected_step->stepid =
						SLURM_BATCH_SCRIPT;

				if (set)
					xstrcat(extra, " || ");
				else
					xstrcat(extra, " && (");

				/* The stepid could be -2 so use %d not %u */
				xstrfmtcat(extra, "t1.id_step=%d",
					   selected_step->stepid);
				set = 1;
				job->show_full = 0;
			}
			list_iterator_destroy(itr);
			if (set)
				xstrcat(extra, ")");
		}
		query =	xstrdup_printf("select %s from \"%s_%s\" as t1 "
				       "where t1.job_db_inx=%s",
				       step_fields, cluster_name,
				       step_table, id);
		if (extra) {
			xstrcat(query, extra);
			xfree(extra);
		}

		debug4("%d(%s:%d) query\n%s",
		       mysql_conn->conn, THIS_FILE, __LINE__, query);

		if (!(step_result = mysql_db_query_ret(
			      mysql_conn, query, 0))) {
			xfree(query);
			rc = SLURM_ERROR;
			goto end_it;
		}
		xfree(query);

		/* Querying the steps in the fashion was faster than
		   doing only 1 query and then matching the steps up
		   later with the job.
		*/
		while ((step_row = mysql_fetch_row(step_result))) {
			/* check the bitmap to see if this is one of the steps
			   we are looking for */
			if (!good_nodes_from_inx(local_cluster_list,
						 (void **)&curr_cluster,
						 step_row[STEP_REQ_NODE_INX],
						 submit))
				continue;

			step = slurmdb_create_step_rec();
			step->tot_cpu_sec = 0;
			step->tot_cpu_usec = 0;
			step->job_ptr = job;
			if (!job->first_step_ptr)
				job->first_step_ptr = step;
			list_append(job->steps, step);
			step->stepid = slurm_atoul(step_row[STEP_REQ_STEPID]);
			/* info("got step %u.%u", */
/* 			     job->header.jobnum, step->stepnum); */
			step->state = slurm_atoul(step_row[STEP_REQ_STATE]);
			step->exitcode =
				slurm_atoul(step_row[STEP_REQ_EXIT_CODE]);
			step->ncpus = slurm_atoul(step_row[STEP_REQ_CPUS]);
			step->nnodes = slurm_atoul(step_row[STEP_REQ_NODES]);

			step->ntasks = slurm_atoul(step_row[STEP_REQ_TASKS]);
			step->task_dist =
				slurm_atoul(step_row[STEP_REQ_TASKDIST]);
			if (!step->ntasks)
				step->ntasks = step->ncpus;

			step->start = slurm_atoul(step_row[STEP_REQ_START]);

			step->end = slurm_atoul(step_row[STEP_REQ_END]);
			/* if the job has ended end the step also */
			if (!step->end && job_ended) {
				step->end = job->end;
				step->state = job->state;
			}

			if (job_cond && !job_cond->without_usage_truncation
			    && job_cond->usage_start) {
				if (step->start
				    && (step->start < job_cond->usage_start))
					step->start = job_cond->usage_start;

				if (!step->start && step->end)
					step->start = step->end;

				if (!step->end
				    || (step->end > job_cond->usage_end))
					step->end = job_cond->usage_end;
			}

			/* figure this out by start stop */
			step->suspended =
				slurm_atoul(step_row[STEP_REQ_SUSPENDED]);
			if (!step->end) {
				step->elapsed = now - step->start;
			} else {
				step->elapsed = step->end - step->start;
			}
			step->elapsed -= step->suspended;

			if ((int)step->elapsed < 0)
				step->elapsed = 0;

			step->user_cpu_sec =
				slurm_atoul(step_row[STEP_REQ_USER_SEC]);
			step->user_cpu_usec =
				slurm_atoul(step_row[STEP_REQ_USER_USEC]);
			step->sys_cpu_sec =
				slurm_atoul(step_row[STEP_REQ_SYS_SEC]);
			step->sys_cpu_usec =
				slurm_atoul(step_row[STEP_REQ_SYS_USEC]);
			step->tot_cpu_sec +=
				step->user_cpu_sec + step->sys_cpu_sec;
			step->tot_cpu_usec +=
				step->user_cpu_usec + step->sys_cpu_usec;
			step->stats.vsize_max =
				slurm_atoul(step_row[STEP_REQ_MAX_VSIZE]);
			step->stats.vsize_max_taskid =
				slurm_atoul(step_row[STEP_REQ_MAX_VSIZE_TASK]);
			step->stats.vsize_ave =
				atof(step_row[STEP_REQ_AVE_VSIZE]);
			step->stats.rss_max =
				slurm_atoul(step_row[STEP_REQ_MAX_RSS]);
			step->stats.rss_max_taskid =
				slurm_atoul(step_row[STEP_REQ_MAX_RSS_TASK]);
			step->stats.rss_ave =
				atof(step_row[STEP_REQ_AVE_RSS]);
			step->stats.pages_max =
				slurm_atoul(step_row[STEP_REQ_MAX_PAGES]);
			step->stats.pages_max_taskid =
				slurm_atoul(step_row[STEP_REQ_MAX_PAGES_TASK]);
			step->stats.pages_ave =
				atof(step_row[STEP_REQ_AVE_PAGES]);
			step->stats.cpu_min =
				slurm_atoul(step_row[STEP_REQ_MIN_CPU]);
			step->stats.cpu_min_taskid =
				slurm_atoul(step_row[STEP_REQ_MIN_CPU_TASK]);
			step->stats.cpu_ave = atof(step_row[STEP_REQ_AVE_CPU]);
			step->stepname = xstrdup(step_row[STEP_REQ_NAME]);
			step->nodes = xstrdup(step_row[STEP_REQ_NODELIST]);
			step->stats.vsize_max_nodeid =
				slurm_atoul(step_row[STEP_REQ_MAX_VSIZE_NODE]);
			step->stats.rss_max_nodeid =
				slurm_atoul(step_row[STEP_REQ_MAX_RSS_NODE]);
			step->stats.pages_max_nodeid =
				slurm_atoul(step_row[STEP_REQ_MAX_PAGES_NODE]);
			step->stats.cpu_min_nodeid =
				slurm_atoul(step_row[STEP_REQ_MIN_CPU_NODE]);

			step->requid =
				slurm_atoul(step_row[STEP_REQ_KILL_REQUID]);
		}
		mysql_free_result(step_result);

		if (!job->track_steps) {
			/* If we don't have track_steps we want to see
			   if we have multiple steps.  If we only have
			   1 step check the job name against the step
			   name in most all cases it will be
			   different.  If it is different print out
			   the step separate.
			*/
			if (list_count(job->steps) > 1)
				job->track_steps = 1;
			else if (step && step->stepname && job->jobname) {
				if (strcmp(step->stepname, job->jobname))
					job->track_steps = 1;
			}
		}
	skip_steps:
		/* need to reset here to make the above test valid */
		step = NULL;
	}
	mysql_free_result(result);

end_it:
	if (local_cluster_list)
		list_destroy(local_cluster_list);

	if (rc == SLURM_SUCCESS)
		list_transfer(sent_list, job_list);

	list_destroy(job_list);
	return rc;
}
Beispiel #6
0
// 服务器启动读取数据库所有城池信息到内存
int city_load()
{
	// 提前分配好空间
	g_city_allinited = 0;
	g_city_maxcount = g_Config.max_citycount;
#ifdef SHM_USE
	int shmret = shm_pool_add( SHM_KEY_CITY, sizeof(City)*g_city_maxcount, (void**)&g_city );
	if ( shmret == SHM_ERROR )
	{
		printf( "City shm_pool_add error\n" );
		return -1;
	}
	else if ( shmret == SHM_ATTACH )
	{
		printf( "City shm_pool_add attach\n" );
		return 0;
	}
#else
	g_city = (City*)malloc( sizeof(City)* g_city_maxcount );
	memset( g_city, 0, sizeof(City)* g_city_maxcount );
#endif // SHM_USE

	printf( "City  maxcount=%d  memory=%0.2fMB\n", g_city_maxcount, (sizeof(City)* g_city_maxcount) / 1024.0 / 1024.0 );

	// 读数据库
	MYSQL_RES *res;
	MYSQL_ROW row;
	char szSQL[2048];
	char reconnect_flag = 0;
	int city_index = 0;
RE_CITY_LOAD:
	sprintf( szSQL, "select * from city" );
	if ( mysql_query( myGame, szSQL ) )
	{
		printf( "Query failed (%s)\n", mysql_error( myGame ) );
		write_gamelog( "%s", szSQL );
		if ( reconnect_flag )
			return -1;
		if ( mysql_ping( myGame ) != 0 )
		{
			db_reconnect_game();
			reconnect_flag = 1;
			goto RE_CITY_LOAD;
		}
		return -1;
	}
	res = mysql_store_result( myGame );
	while ( (row = mysql_fetch_row( res )) )
	{
		int index = 0;
		if ( city_index >= g_city_maxcount )
		{
			printf( "warning!!!warning!!!  city_index >= g_city_maxcount \n" );
			return -1;
		}
		g_city[city_index].cityid = atoi( row[index++] );
		g_city[city_index].laird_type = atoi( row[index++] );
		g_city[city_index].laird_actorid = atoi( row[index++] );
		memcpy( g_city[city_index].laird_name, row[index++], sizeof(char)*NAME_SIZE );
		g_city[city_index].laird_shape = atoi( row[index++] );
		g_city[city_index].laird_level = atoi( row[index++] );
		g_city[city_index].laird_lastlogin = atoi( row[index++] );
		g_city[city_index].match_cityid = atoi( row[index++] );
		g_city[city_index].aclass = atoi( row[index++] );
		g_city[city_index].skin = atoi( row[index++] );
		g_city[city_index].clubid = atoi( row[index++] );
		g_city[city_index].posx = atoi( row[index++] );
		g_city[city_index].posy = atoi( row[index++] );
		g_city[city_index].wood = atoi( row[index++] );
		g_city[city_index].food = atoi( row[index++] );
		g_city[city_index].iron = atoi( row[index++] );
		g_city[city_index].mithril = atoi( row[index++] );
		g_city[city_index].gold = atoi( row[index++] );
		for ( int tmpi = 0; tmpi < CityCorpsMax; tmpi++ )
		{
			memcpy( g_city[city_index].corps_num[tmpi], row[index], sizeof(int)*CityCorpsLevelMax );
			memcpy(g_city[city_index].corps_wound[tmpi], row[CityCorpsMax + index], sizeof(int)*CityCorpsLevelMax);
			index++;
		}

		g_city[city_index].actor_index = -1;
		// 读取建筑
		building_load( &g_city[city_index] );
		// 重新计算临时数据
		city_reset( &g_city[city_index] );
		// 添加到地图显示单元
		if ( g_city[city_index].laird_type != CityLairdType_Match )
		{
			mapunit_add( MAPUNIT_TYPE_CITY, city_index );
		}
		city_index++;
		g_city_maxindex = city_index;
	}
	mysql_free_result( res );
	// 创建机器人城池
	robot_city_create();
	// 所有城池初始化完毕
	g_city_allinited = 1;
	return 0;
}
Beispiel #7
0
// Clan Manager
bool CWorldServer::pakClanManager ( CPlayer* thisclient, CPacket* P )
{
    int action = GETBYTE((*P),0);
    switch(action)
    {
        case 0xf0:
        {
            //LMA: is this one really used at all?
            MYSQL_ROW row;
            /*int charid = GETWORD((*P),1);
            int clanid = GETWORD((*P),3);*/
            DWORD charid = GETDWORD((*P),1);
            int clanid = GETWORD((*P),5);

            CPlayer* otherclient = GetClientByCID ( charid );
            if(otherclient==NULL)
                return true;
    	    MYSQL_RES *result = DB->QStore("SELECT logo,back,name,grade FROM list_clan where id=%i", clanid);
    	    if(result==NULL) return true;
        	if(mysql_num_rows(result)!=1)
        	{
                Log(MSG_WARNING, "Invalid clan %i", clanid );
                DB->QFree( );
          	    return true;
            }
            row = mysql_fetch_row(result);
        	otherclient->Clan->logo = atoi(row[0]);
    	    otherclient->Clan->back = atoi(row[1]);
    	    strcpy(otherclient->Clan->clanname,row[2]);
    	    otherclient->Clan->grade = atoi(row[3]);
        	DB->QFree( );
            BEGINPACKET( pak, 0x7e0 );
            ADDBYTE    ( pak, 0x35 );//funcion
            ADDWORD    ( pak, otherclient->clientid );//cleint id
            ADDDWORD    ( pak, clanid );
            ADDWORD    ( pak, otherclient->Clan->back );//?
            ADDWORD    ( pak, otherclient->Clan->logo );//?
            ADDBYTE    ( pak, otherclient->Clan->grade );
            ADDBYTE    ( pak, otherclient->Clan->clanrank);
            ADDSTRING  ( pak, otherclient->Clan->clanname );
            ADDBYTE    ( pak, 0x00 );
            SendToVisible( &pak, otherclient );
            Log(MSG_INFO,"[WS] pakClanManager 0x7e1, case 0xf0 (new member too?) %s",otherclient->CharInfo->charname);
        }
        case 0xfa://new member added
        {
        	MYSQL_ROW row;
            /*int charid = GETWORD((*P),1);
            int clanid = GETWORD((*P),3);*/
            DWORD charid = GETDWORD((*P),1);
            int clanid = GETWORD((*P),5);

            CPlayer* otherclient = GetClientByCID ( charid );
            if(otherclient==NULL)
                return true;
    	    MYSQL_RES *result = DB->QStore("SELECT logo,back,name,grade FROM list_clan where id=%i", clanid);
    	    if(result==NULL) return true;
        	if(mysql_num_rows(result)!=1)
        	{
                Log(MSG_WARNING, "Invalid clan %i", clanid );
                DB->QFree( );
          	    return true;
            }

            row = mysql_fetch_row(result);
        	otherclient->Clan->logo = atoi(row[0]);
    	    otherclient->Clan->back = atoi(row[1]);
    	    strcpy(otherclient->Clan->clanname,row[2]);
    	    otherclient->Clan->grade = atoi(row[3]);
        	DB->QFree( );
            otherclient->Clan->clanid=clanid;
            otherclient->Clan->clanrank=1;
            BEGINPACKET( pak, 0x7e0 );
            ADDBYTE    ( pak, 0x35 );//funcion
            ADDWORD    ( pak, otherclient->clientid );//cleint id
            ADDDWORD   ( pak, clanid );//?
            ADDWORD    ( pak, otherclient->Clan->back );//?
            ADDWORD    ( pak, otherclient->Clan->logo );//?
            ADDBYTE    ( pak, otherclient->Clan->grade );
            ADDBYTE    ( pak, otherclient->Clan->clanrank );
            ADDSTRING  ( pak, otherclient->Clan->clanname );
            ADDBYTE    ( pak, 0x00 );
            SendToVisible( &pak, otherclient );
            Log(MSG_INFO,"[WS] pakClanManager 0x7e1, new member %s",otherclient->CharInfo->charname);
        }
        break;
        case 0xfb://Member Kicked
        {
           char nick[30];
           memcpy( nick, &P->Buffer[1], P->Size );
           CPlayer* otherclient = GetClientByCharName( nick );
           if(otherclient!=NULL)
           {
                otherclient->Clan->clanid=0;
                otherclient->Clan->clanrank=1;
	            otherclient->Clan->back=0;
	            otherclient->Clan->logo=0;
	            otherclient->Clan->grade=0;
	            strcpy(otherclient->Clan->clanname,"");
                BEGINPACKET( pak, 0x7e0 );
                ADDBYTE    ( pak, 0x35 );
                ADDWORD    ( pak, otherclient->clientid );
                ADDQWORD   ( pak, 0 );
                ADDWORD    ( pak, 0x0001 );
                SendToVisible( &pak, otherclient );
                Log(MSG_INFO,"[WS] pakClanManager 0x7e1, member kicked, %s",nick);
           }
        }
        break;
        case 0xfc://member change rank
        {
           char nick[30];
           int newrank = GETBYTE((*P),1);
           memcpy( nick, &P->Buffer[2], P->Size );
           CPlayer* otherclient = GetClientByCharName( nick );
           if(otherclient!=NULL)
           {
                otherclient->Clan->clanrank = newrank;
                Log(MSG_INFO,"[WS] pakClanManager 0x7e1, change rank for %s to %i",nick,newrank);
           }
        }
        break;
        case 0xfd://disorg
        {
            unsigned int clanid = GETWORD((*P),1);
            //unsigned int charid = GETWORD((*P),3);
            DWORD charid = GETDWORD((*P),3);
            CPlayer* tclient = GetClientByCID( charid );
            if(tclient==NULL)
                return true;
            tclient->Clan->clanid = 0;
            tclient->Clan->clanrank = 1;
            tclient->Clan->grade = 0;
            tclient->Clan->back = 0;
            tclient->Clan->logo = 0;
            memset( &tclient->Clan->clanname, '\0', 17 );
            BEGINPACKET( pak, 0x7e0 );
            ADDBYTE    ( pak, 0x35 );
            ADDWORD    ( pak, tclient->clientid );
            ADDQWORD   ( pak, 0 );
            ADDWORD    ( pak, 0x0001 );
            SendToVisible( &pak, tclient );
            Log(MSG_INFO,"[WS] pakClanManager 0x7e1, disorg");
        }
        break;
        case 0xfe://Member Leave
        {
           char nick[17];
           memcpy( nick, &P->Buffer[1], P->Size );
           CPlayer* otherclient = GetClientByCharName(nick);
           if(otherclient!=NULL)
           {
                otherclient->Clan->clanid=0;
                otherclient->Clan->clanrank=0;
	            otherclient->Clan->back=0;
	            otherclient->Clan->logo=0;
	            otherclient->Clan->grade=0;
	            strcpy(otherclient->Clan->clanname,"");
                BEGINPACKET( pak, 0x7e0 );
                ADDBYTE    ( pak, 0x35 );
                ADDWORD    ( pak, otherclient->clientid );
                ADDQWORD   ( pak, 0 );
                ADDWORD    ( pak, 0x0001 );
                SendToVisible( &pak, otherclient );
                Log(MSG_INFO,"[WS] pakClanManager 0x7e1, member left");
           }
        }
        break;
        case 0xff: // update clan mark
        {
            unsigned int clanid = GETWORD((*P),1);
            unsigned int clanlogo = GETDWORD((*P), 3 );
            for(unsigned int i=0;i<ClientList.size();i++)
            {
                if(ClientList.at(i)->player==NULL) continue;
                CPlayer* player = (CPlayer*)ClientList.at(i)->player;
                if(player->Clan->clanid==clanid)
                {
                    player->Clan->back = 0;
                    player->Clan->logo = clanlogo;
                    BEGINPACKET( pak, 0x7e0 );
                    ADDBYTE    ( pak, 0x35 );//funcion
                    ADDWORD    ( pak, player->clientid );//cleint id
                    ADDDWORD    ( pak, clanid );//?
                    ADDWORD    ( pak, player->Clan->back );//?
                    ADDWORD    ( pak, player->Clan->logo );//?
                    ADDBYTE    ( pak, player->Clan->grade );
                    ADDBYTE    ( pak, player->Clan->clanrank );
                    ADDSTRING  ( pak, player->Clan->clanname );
                    ADDBYTE    ( pak, 0x00 );
                    SendToVisible( &pak, player );
                }
            }
        }
        break;
        default:
            Log( MSG_INFO, "[WS] Clan manager 0x7e1 unknown action %i", action );
    }
    return true;
}
int OGRMySQLDataSource::FetchSRSId( OGRSpatialReference * poSRS )

{
    char           **papszRow;  
    MYSQL_RES       *hResult=NULL;
    
    CPLString            osCommand;
    char                *pszWKT = NULL;
    int                 nSRSId;

    if( poSRS == NULL )
        return -1;

/* -------------------------------------------------------------------- */
/*      Translate SRS to WKT.                                           */
/* -------------------------------------------------------------------- */
    if( poSRS->exportToWkt( &pszWKT ) != OGRERR_NONE )
        return -1;
    
/* -------------------------------------------------------------------- */
/*      Try to find in the existing table.                              */
/* -------------------------------------------------------------------- */
    osCommand.Printf( 
             "SELECT srid FROM spatial_ref_sys WHERE srtext = '%s'",
             pszWKT );

    if( !mysql_query( GetConn(), osCommand ) )
        hResult = mysql_store_result( GetConn() );

    if (!mysql_num_rows(hResult))
    {
        CPLDebug("MYSQL", "No rows exist currently exist in spatial_ref_sys");
        mysql_free_result( hResult );
        hResult = NULL;
    }
    papszRow = NULL;
    if( hResult != NULL )
        papszRow = mysql_fetch_row( hResult );
        
    if( papszRow != NULL && papszRow[0] != NULL )
    {
        nSRSId = atoi(papszRow[0]);
        if( hResult != NULL )
            mysql_free_result( hResult );
        hResult = NULL;
        CPLFree(pszWKT);
        return nSRSId;
    }

    // make sure to attempt to free results of successful queries
    hResult = mysql_store_result( GetConn() );
    if( hResult != NULL )
        mysql_free_result( hResult );
    hResult = NULL;

/* -------------------------------------------------------------------- */
/*      Get the current maximum srid in the srs table.                  */
/* -------------------------------------------------------------------- */
    osCommand = "SELECT MAX(srid) FROM spatial_ref_sys";
    if( !mysql_query( GetConn(), osCommand ) )
    {
        hResult = mysql_store_result( GetConn() );
        papszRow = mysql_fetch_row( hResult );
    }
        
    if( papszRow != NULL && papszRow[0] != NULL )
    {
        nSRSId = atoi(papszRow[0]) + 1;
    }
    else
        nSRSId = 1;

    if( hResult != NULL )
        mysql_free_result( hResult );
    hResult = NULL;

/* -------------------------------------------------------------------- */
/*      Try adding the SRS to the SRS table.                            */
/* -------------------------------------------------------------------- */
    osCommand.Printf(
             "INSERT INTO spatial_ref_sys (srid,srtext) VALUES (%d,'%s')",
             nSRSId, pszWKT );

    if( !mysql_query( GetConn(), osCommand ) )
        hResult = mysql_store_result( GetConn() );

    // make sure to attempt to free results of successful queries
    hResult = mysql_store_result( GetConn() );
    if( hResult != NULL )
        mysql_free_result( hResult );
    hResult = NULL;

    CPLFree(pszWKT);

    return nSRSId;
}
Beispiel #9
0
int main(int argc, char *argv[], char *envp[])
{
  int res,i,status;
  const char *userp = getenv("USER");	// vem är inloggad?
  char databas[25]="olfix";
  char usr[21];				/* userid 20070213 utökad från 15 till 21 tecken */

  char temp1[]="SELECT ARID,BENAMNING,KONTOPLAN FROM BOKFAR ORDER BY ARID";
  char temp5[200]="";

/* fprintf(stderr,"BARLST argc = %d\n",argc);			*/
/*  for (i=0;i< argc;i++){
  	fprintf(stderr,"BARLST argv%d = %s\n",i,argv[i]);
    }
*/
/* ================================================================================ */
/* 		Val av databas, START						    */
/* ================================================================================ */

  status = which_database(envp);

  if (status != 0)
	exit(status);

  strncpy(usr,userp,sizeof(usr));			/* Den inloggades userid 20070213 */
/*  fprintf(stderr,"status=%d ANTARG=%d len(database)=%d\n",status,ANTARG,strlen(database));	*/
  if (argc < ANTARG+1){
    	if (strlen(database)!= 0){
		strncpy(databas,database,15);
	}else{
  		strncpy(databas,"olfixtst",15);	/* olfixtst = testföretag	*/
	}
  }else{
	if (strlen(argv[ANTARG]) != 0){
  		if (strncmp(argv[ANTARG],"99",2)==0){
			strncpy(databas,"olfixtst",15);
		}else{
  			strncpy(databas,argv[ANTARG],15);
  		}
  	}
  }
/*  fprintf(stderr,"ANTARG=%d,argv[ANTARG]=%s\n",ANTARG,argv[ANTARG]);	*/
/* Om usr (userid) börjar på 'test' eller 'prov' använd databas 'olfixtst' */
  if (strncmp(usr,"test",4)==0 || strncmp(usr,"prov",4)==0 ) {
  	strncpy(databas,"olfixtst",15);
  }
/* fprintf(stderr,"Databas=%s\n",databas);	*/
/* ================================================================================ */
/* 		Val av databas, END!						    */
/* ================================================================================ */

  strncpy(temp5,temp1,strlen(temp1));
/*  fprintf(stderr,"BARLST temp5=%s\n",temp5);		*/
  mysql_init(&my_connection);
  if (mysql_real_connect(&my_connection, "localhost",  "olfix", "olfix", databas, 0, NULL, 0)){
/*  	fprintf(stdout,"BARLST_Connection success\n");	*/
  	res = mysql_query(&my_connection,temp5);
/*  	fprintf(stderr,"BARLST hit res=%d\n",res);	*/
  	if (res){
		fprintf(stderr,"Error: BARLST SELECT errno: %d\n",mysql_errno(&my_connection));
        }else{
		res_ptr=mysql_store_result(&my_connection);
		if (res_ptr){
			i=1;
/*			fprintf(stdout,"BARLST:Retrieved %lu rows\n",(unsigned long)mysql_num_rows(res_ptr));	*/
			fprintf(stdout,"OK: NR_%lu_:",(unsigned long)mysql_num_rows(res_ptr));
			while ((sqlrow=mysql_fetch_row(res_ptr)))  {
/*				fprintf(stderr,"BARLST:Fetched data....}");	*/
				display_row();
				i++;
			}
			fprintf(stdout,"\n");
			if (mysql_errno(&my_connection))  {
				fprintf(stderr,"Error: BARLST Retriev error:  %s\n", mysql_error(&my_connection));
			}
		}
	mysql_free_result(res_ptr);
	}
    	mysql_close(&my_connection);
  }
  else {
    	fprintf(stderr,"Error: BARLST Connection failed\n");
    	if (mysql_errno(&my_connection))   {
    		fprintf(stderr,"Error: BARLST Connection error %d:  %s\n",
			mysql_errno(&my_connection), mysql_error(&my_connection));
	}
    }
  return EXIT_SUCCESS;
}
int OGRMySQLDataSource::Open( const char * pszNewName, int bUpdate,
                              int bTestOpen )

{
    CPLAssert( nLayers == 0 );

/* -------------------------------------------------------------------- */
/*      Verify MySQL prefix.                                            */
/* -------------------------------------------------------------------- */
    if( !EQUALN(pszNewName,"MYSQL:",6) )
    {
        if( !bTestOpen )
            CPLError( CE_Failure, CPLE_AppDefined, 
                      "%s does not conform to MySQL naming convention,"
                      " MYSQL:dbname[, user=..][,password=..][,host=..][,port=..][tables=table;table;...]",
                      pszNewName );
        return FALSE;
    }
    
/* -------------------------------------------------------------------- */
/*      Use options process to get .my.cnf file contents.               */
/* -------------------------------------------------------------------- */
    int nPort = 0, i;
    char **papszTableNames=NULL;
    std::string oHost, oPassword, oUser, oDB;
    char *apszArgv[2] = { (char*) "org", NULL };
    char **papszArgv = apszArgv;
    int  nArgc = 1;
    const char *client_groups[] = {"client", "ogr", NULL };

    my_init(); // I hope there is no problem with calling this multiple times!
    load_defaults( "my", client_groups, &nArgc, &papszArgv );

    for( i = 0; i < nArgc; i++ )
    {
        if( EQUALN(papszArgv[i],"--user=",7) )
            oUser = papszArgv[i] + 7;
        else if( EQUALN(papszArgv[i],"--host=",7) )
            oHost = papszArgv[i] + 7;
        else if( EQUALN(papszArgv[i],"--password=",11) )
            oPassword = papszArgv[i] + 11;
        else if( EQUALN(papszArgv[i],"--port=",7) )
            nPort = atoi(papszArgv[i] + 7);
    }

    // cleanup
    free_defaults( papszArgv );

/* -------------------------------------------------------------------- */
/*      Parse out connection information.                               */
/* -------------------------------------------------------------------- */
    char **papszItems = CSLTokenizeString2( pszNewName+6, ",", 
                                            CSLT_HONOURSTRINGS );

    if( CSLCount(papszItems) < 1 )
    {
        CSLDestroy( papszItems );
        CPLError( CE_Failure, CPLE_AppDefined, 
                  "MYSQL: request missing databasename." );
        return FALSE;
    }

    oDB = papszItems[0];

    for( i = 1; papszItems[i] != NULL; i++ )
    {
        if( EQUALN(papszItems[i],"user=",5) )
            oUser = papszItems[i] + 5;
        else if( EQUALN(papszItems[i],"password=",9) )
            oPassword = papszItems[i] + 9;
        else if( EQUALN(papszItems[i],"host=",5) )
            oHost = papszItems[i] + 5;
        else if( EQUALN(papszItems[i],"port=",5) )
            nPort = atoi(papszItems[i] + 5);
        else if( EQUALN(papszItems[i],"tables=",7) )
        {
            papszTableNames = CSLTokenizeStringComplex( 
                papszItems[i] + 7, ";", FALSE, FALSE );
        }
        else
            CPLError( CE_Warning, CPLE_AppDefined, 
                      "'%s' in MYSQL datasource definition not recognised and ignored.", papszItems[i] );
    }

    CSLDestroy( papszItems );

/* -------------------------------------------------------------------- */
/*      Try to establish connection.                                    */
/* -------------------------------------------------------------------- */
    hConn = mysql_init( NULL );

    if( hConn == NULL )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "mysql_init() failed." );
    }

/* -------------------------------------------------------------------- */
/*      Set desired options on the connection: charset and timeout.     */
/* -------------------------------------------------------------------- */
    if( hConn )
    {
        const char *pszTimeoutLength = 
            CPLGetConfigOption( "MYSQL_TIMEOUT", "0" );  
        
        unsigned int timeout = atoi(pszTimeoutLength);        
        mysql_options(hConn, MYSQL_OPT_CONNECT_TIMEOUT, (char*)&timeout);

        mysql_options(hConn, MYSQL_SET_CHARSET_NAME, "utf8" );
    }
    
/* -------------------------------------------------------------------- */
/*      Perform connection.                                             */
/* -------------------------------------------------------------------- */
    if( hConn
        && mysql_real_connect( hConn, 
                               oHost.length() ? oHost.c_str() : NULL,
                               oUser.length() ? oUser.c_str() : NULL,
                               oPassword.length() ? oPassword.c_str() : NULL,
                               oDB.length() ? oDB.c_str() : NULL,
                               nPort, NULL, CLIENT_INTERACTIVE ) == NULL )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "MySQL connect failed for: %s\n%s", 
                  pszNewName + 6, mysql_error( hConn ) );
        mysql_close( hConn );
        hConn = NULL;
    }

    if( hConn == NULL )
    {
        CSLDestroy( papszTableNames );
        return FALSE;
    }
    
    pszName = CPLStrdup( pszNewName );
    
    bDSUpdate = bUpdate;

/* -------------------------------------------------------------------- */
/*      Get a list of available tables.                                 */
/* -------------------------------------------------------------------- */
    if( papszTableNames == NULL )
    {
        MYSQL_RES *hResultSet;
        MYSQL_ROW papszRow;

        if( mysql_query( hConn, "SHOW TABLES" ) )
        {
            ReportError( "SHOW TABLES Failed" );
            return FALSE;
        }

        hResultSet = mysql_store_result( hConn );
        if( hResultSet == NULL )
        {
            ReportError( "mysql_store_result() failed on SHOW TABLES result.");
            return FALSE;
        }
    
        while( (papszRow = mysql_fetch_row( hResultSet )) != NULL )
        {
            if( papszRow[0] == NULL )
                continue;

            if( EQUAL(papszRow[0],"spatial_ref_sys")
                || EQUAL(papszRow[0],"geometry_columns") )
                continue;

            papszTableNames = CSLAddString(papszTableNames, papszRow[0] );
        }

        mysql_free_result( hResultSet );
    }

/* -------------------------------------------------------------------- */
/*      Get the schema of the available tables.                         */
/* -------------------------------------------------------------------- */
    int iRecord;

    for( iRecord = 0; 
         papszTableNames != NULL && papszTableNames[iRecord] != NULL;
         iRecord++ )
    {
        //  FIXME: This should be fixed to deal with tables 
        //  for which we can't open because the name is bad/ 
        OpenTable( papszTableNames[iRecord], bUpdate, FALSE );
    }

    CSLDestroy( papszTableNames );
    
    return nLayers > 0 || bUpdate;
}
OGRSpatialReference *OGRMySQLDataSource::FetchSRS( int nId )
{
    char         szCommand[128];
    char           **papszRow;  
    MYSQL_RES       *hResult;
            
    if( nId < 0 )
        return NULL;

/* -------------------------------------------------------------------- */
/*      First, we look through our SRID cache, is it there?             */
/* -------------------------------------------------------------------- */
    int  i;

    for( i = 0; i < nKnownSRID; i++ )
    {
        if( panSRID[i] == nId )
            return papoSRS[i];
    }

    OGRSpatialReference *poSRS = NULL;
 
    // make sure to attempt to free any old results
    hResult = mysql_store_result( GetConn() );
    if( hResult != NULL )
        mysql_free_result( hResult );
    hResult = NULL;   
                        
    sprintf( szCommand,
         "SELECT srtext FROM spatial_ref_sys WHERE srid = %d",
         nId );
    
    if( !mysql_query( GetConn(), szCommand ) )
        hResult = mysql_store_result( GetConn() );
        
    char  *pszWKT = NULL;
    papszRow = NULL;
    

    if( hResult != NULL )
        papszRow = mysql_fetch_row( hResult );

    if( papszRow != NULL && papszRow[0] != NULL )
    {
        pszWKT = CPLStrdup(papszRow[0]);
    }

    if( hResult != NULL )
        mysql_free_result( hResult );
    hResult = NULL;

    poSRS = new OGRSpatialReference();
    char* pszWKTOri = pszWKT;
    if( pszWKT == NULL || poSRS->importFromWkt( &pszWKT ) != OGRERR_NONE )
    {
        delete poSRS;
        CPLFree(pszWKTOri);
        poSRS = NULL;
    }

    CPLFree(pszWKTOri);

/* -------------------------------------------------------------------- */
/*      Add to the cache.                                               */
/* -------------------------------------------------------------------- */
    panSRID = (int *) CPLRealloc(panSRID,sizeof(int) * (nKnownSRID+1) );
    papoSRS = (OGRSpatialReference **) 
        CPLRealloc(papoSRS, sizeof(void*) * (nKnownSRID + 1) );
    panSRID[nKnownSRID] = nId;
    papoSRS[nKnownSRID] = poSRS;
    nKnownSRID ++;

    return poSRS;
}
int main(int argc, char** argv) {
	char host[1024];
	char user[1024];
	char passwd[1024];
	char db[1024];
	char query[1024];
	char table[1024];
	MYSQL link;
	MYSQL_RES* result, *result2;
	MYSQL_ROW row, row2;
	char ch;


	unsigned long long int table_id;
	unsigned long long int index_id[128];
	char* charset;
	char* collation;
	unsigned long maxlen;
	/* Set default values */
	strcpy(host, "localhost");
	getlogin_r(user, sizeof(user));
	strcpy(passwd, "");
	strcpy(db, "test");

	while((ch = getopt(argc, argv, "h:u:p:d:g")) != -1){
		switch(ch){
			case 'h': strncpy(host, optarg, sizeof(host)); break;
			case 'u': strncpy(user, optarg, sizeof(user)); break;
			case 'p': strncpy(passwd, optarg, sizeof(passwd)); break;
			case 'd': strncpy(db, optarg, sizeof(db)); break;
			case 'g': debug=1; break;
			default : usage(basename(argv[0])); exit(EXIT_FAILURE);
			}
		}
	if(argv[optind] != NULL){
		strncpy(table, argv[optind], sizeof(table)); 	
		}
	else{
		usage(basename(argv[0])); exit(EXIT_FAILURE);
		}
	/* Connect to MySQL*/
	mysql_init(&link);
	if(NULL == mysql_real_connect(&link, host, user, passwd, db, 0, NULL, 0)){
		fprintf(stderr,"Error: %s\n", mysql_error(&link));
		exit(EXIT_FAILURE);
		}

	/* Get table_id from SYS_TABLES */
	snprintf(query, sizeof(query), "SELECT ID FROM SYS_TABLES WHERE `NAME` = '%s' ", table);
	if(0 != mysql_query(&link, query)){
		fprintf(stderr,"Error: %s\n", mysql_error(&link));
		exit(EXIT_FAILURE);
		}
	result = mysql_store_result(&link);
	int n = mysql_num_rows(result);
	row = mysql_fetch_row(result);
	if(n == 0){
		fprintf(stderr, "Table '%s' not found in SYS_TABLES\n", table);
		exit(EXIT_FAILURE);
		}
	table_id = strtoull(row[0], NULL, 10);
	if(debug) printf("-- `%s`: table_id = %llu\n", table, table_id);
	mysql_free_result(result);

	/* Get array of index_id */
	snprintf(query, sizeof(query), "SELECT ID FROM SYS_INDEXES WHERE TABLE_ID='%llu' ORDER BY ID", table_id);
	if(0 != mysql_query(&link, query)){
		fprintf(stderr,"Error: %s\n", mysql_error(&link));
		exit(EXIT_FAILURE);
		}
	result = mysql_store_result(&link);
	n = mysql_num_rows(result);
	if(n == 0){
		fprintf(stderr, "Index records are not found for table '%s' in SYS_INDEXES\n", table);
		exit(EXIT_FAILURE);
		}
	int i = 0;
	for(i = 0; i < n; i++){
		row = mysql_fetch_row(result);
		index_id[i] = strtoull(row[0], NULL, 10);
		if(debug) printf("-- `%s`: index_id = %llu\n", table, index_id[i]);
		}
	mysql_free_result(result);

	/* Get array of fields */
	snprintf(query, sizeof(query), "SELECT TABLE_ID, POS, NAME, MTYPE, PRTYPE, LEN, PREC FROM SYS_COLUMNS WHERE TABLE_ID='%llu' ORDER BY POS", table_id);
	if(0 != mysql_query(&link, query)){
		fprintf(stderr,"Error: %s\n", mysql_error(&link));
		exit(EXIT_FAILURE);
		}
	result = mysql_store_result(&link);
	n = mysql_num_rows(result);
	if(n == 0){
		fprintf(stderr, "Fields are not found for table '%s' in SYS_COLUMNS\n", table);
		exit(EXIT_FAILURE);
		}
	printf("CREATE TABLE `%s`(\n", strstr(table, "/")+1);
	for(i = 0; i < n; i++){
		row = mysql_fetch_row(result);
		unsigned long mtype = strtoul(row[3], NULL, 10);
		if(debug) printf("-- `%s`: mtype = %lu\n", row[2], mtype);
		unsigned long prtype = strtoul(row[4], NULL, 10);
		if(debug) printf("-- `%s`: prtype = 0x%08lX(%lu)\n", row[2], prtype, prtype);
		unsigned char type_code = prtype & DATA_MYSQL_TYPE_MASK; 
		if(debug) printf("-- `%s`: mysql type = %u\n", row[2], type_code);
		int unsigned_flag = (prtype & DATA_UNSIGNED) ? 1 : 0;
		int not_null_flag = (prtype & DATA_NOT_NULL) ? 1 : 0;
		int binarytype_flag = (prtype & DATA_BINARY_TYPE)? 1 : 0;
		int logn_true_varchar_flag = (prtype & DATA_LONG_TRUE_VARCHAR)? 1 : 0;
		unsigned c_code = ((prtype >> 16) & 0xFFUL);
		unsigned long len = strtoul(row[5], NULL, 10);
		if(c_code != 0){
			snprintf(query, sizeof(query), "SELECT COLLATIONS.CHARACTER_SET_NAME, COLLATIONS.COLLATION_NAME, CHARACTER_SETS.MAXLEN  FROM information_schema.COLLATIONS LEFT JOIN information_schema.CHARACTER_SETS ON  COLLATIONS.CHARACTER_SET_NAME = CHARACTER_SETS.CHARACTER_SET_NAME WHERE COLLATIONS.ID = '%u';", c_code);
			if(0 != mysql_query(&link, query)){
				fprintf(stderr,"Error: %s\n", mysql_error(&link));
				exit(EXIT_FAILURE);
				}
			result2 = mysql_store_result(&link);
			if(mysql_num_rows(result2)>0){
				row2 = mysql_fetch_row(result2);
				charset = row2[0];
				collation = row2[1];
				maxlen = strtoul(row2[2], NULL, 10);
				mysql_free_result(result2);
				if(debug) printf("-- charset: %s , collation %s maxlen = %lu\n", charset, collation, maxlen);
				}
			else{
				fprintf(stderr, "Couldn't find charset-collcation details for collation id = %u\n", c_code);
				exit(EXIT_FAILURE);
				}
			}	
		if(debug) printf("-- `%s`: c_code = %u\n", row[2], c_code);
		printf("\t`%s` ", row[2]);
		print_type(mtype, prtype);
		if(mtype == DATA_VARCHAR ||
				mtype == DATA_CHAR ||
				mtype == DATA_VARMYSQL || 
				mtype == DATA_MYSQL){
			len /= maxlen;
			printf("(%lu)", len);
			printf(" CHARACTER SET '%s'", charset);
			printf(" COLLATE '%s'", collation);
			}
		if(mtype == DATA_FIXBINARY && type_code == MYSQL_TYPE_NEWDECIMAL){
			printf("(%lu,0)", len * 2);
			}
		if(type_code == MYSQL_TYPE_TINY ||
				type_code == MYSQL_TYPE_SHORT ||
				type_code == MYSQL_TYPE_LONG ||
				type_code == MYSQL_TYPE_LONGLONG ||
				type_code == MYSQL_TYPE_INT24
				){
			if(unsigned_flag) printf(" UNSIGNED");
			}
		if(not_null_flag) printf(" NOT NULL");
		if(mtype == DATA_VARCHAR ||
				mtype == DATA_CHAR ){
			if(binarytype_flag) printf(" BINARY");
			}
		printf(",\n");

		}
	mysql_free_result(result);
	/* Now print PRIMARY KEY */
	snprintf(query, sizeof(query), "SELECT COL_NAME from SYS_FIELDS WHERE INDEX_ID = %llu ORDER BY POS;", index_id[0]);
	if(0 != mysql_query(&link, query)){
		fprintf(stderr,"Error: %s\n", mysql_error(&link));
		exit(EXIT_FAILURE);
		}
	result = mysql_store_result(&link);
	n = mysql_num_rows(result);
	if(n == 0){
		fprintf(stderr, "Fields are not found for table '%s' in SYS_FIELDS\n", table);
		exit(EXIT_FAILURE);
		}
	printf("\tPRIMARY KEY (", table);
	int comma=0;
	for(i = 0; i < n; i++){
		row = mysql_fetch_row(result);
		if(comma) printf(", ");
		printf("`%s`", row[0]);
		comma=1;
		}
	printf(")\n", table);
	printf(") ENGINE=InnoDB;\n", table);







        exit(EXIT_SUCCESS);
}
Beispiel #13
0
int get_datos_cliente(MYSQL *my_con, int codigo, Cliente &c)
{
    std::string     consulta = "SELECT * FROM cliente WHERE COD_CLIENTE=" + utiles::to_string(codigo, 6);
    MYSQL_RES       *resultado;
    MYSQL_ROW       fila;

    if(mysql_query(my_con, consulta.c_str()) != 0) {
        print_mysql_error(my_con, "Fallo al seleccionar un cliente.");
        return 1;
    }
    else {
        if((resultado = mysql_store_result(my_con)) == NULL) {
            print_mysql_error(my_con, "Fallo al almacenar el resultado.");
            return 2;
        }
        else {
            if(static_cast<int>(mysql_num_rows(resultado)) > 1) {
                print_mysql_error(my_con, "Varios clientes con el mismo codigo.");
                return 3;
            }

            if(static_cast<int>(mysql_num_fields(resultado)) != 15) {
                print_mysql_error(my_con, "El numero de columnas no coincide.");
                return 4;
            }

            // Columna      Contenido       Tipo
            // -------      ---------       ----
            //  0           id_cliente      Entero (No usable, interno BD)
            //  1           cod_cliente     Entero
            //  2           razon_social    Texto
            //  3           domicilio       Texto
            //  4           cod_postal      Texto
            //  5           poblacion       Texto
            //  6           provincia       Texto
            //  7           nif             Texto
            //  8           tel1            Texto
            //  9           tel2            Texto
            //  10          fax             Texto
            //  11          forma_pago      Entero
            //  12          categoria       Entero
            //  13          swift_bic       Texto
            //  14          iban            Texto

            while((fila = mysql_fetch_row(resultado)) != NULL) {
                c.codigo        = (fila[1] != NULL) ? utiles::to_integer(fila[1]) : 0;
                c.razon_social  = fila[2];
                c.domicilio     = fila[3];
                c.codigo_postal = fila[4];
                c.poblacion     = fila[5];
                c.provincia     = fila[6];
                c.nif           = fila[7];
                c.tel1          = fila[8];
                c.tel2          = fila[9];
                c.fax           = fila[10];
                c.forma_pago    = (fila[11] != NULL) ? utiles::to_integer(fila[11]) : 0;
                c.categoria     = (fila[12] != NULL) ? utiles::to_integer(fila[12]) : 0;
                c.swift_bic     = fila[13];
                c.iban          = fila[14];
            }

            mysql_free_result(resultado);
        }
    }

    return 0;
}
Beispiel #14
0
OGRErr OGRMySQLTableLayer::GetExtent(OGREnvelope *psExtent, CPL_UNUSED int bForce )
{
	if( GetLayerDefn()->GetGeomType() == wkbNone )
    {
        psExtent->MinX = 0.0;
        psExtent->MaxX = 0.0;
        psExtent->MinY = 0.0;
        psExtent->MaxY = 0.0;

        return OGRERR_FAILURE;
    }

	OGREnvelope oEnv;
	CPLString   osCommand;
	GBool       bExtentSet = FALSE;

	osCommand.Printf( "SELECT Envelope(`%s`) FROM `%s`;", pszGeomColumn, pszGeomColumnTable);

	if (mysql_query(poDS->GetConn(), osCommand) == 0)
	{
		MYSQL_RES* result = mysql_use_result(poDS->GetConn());
		if ( result == NULL )
        {
            poDS->ReportError( "mysql_use_result() failed on extents query." );
            return OGRERR_FAILURE;
        }

		MYSQL_ROW row;
		unsigned long *panLengths = NULL;
		while ((row = mysql_fetch_row(result)) != NULL)
		{
			if (panLengths == NULL)
			{
				panLengths = mysql_fetch_lengths( result );
				if ( panLengths == NULL )
				{
					poDS->ReportError( "mysql_fetch_lengths() failed on extents query." );
					return OGRERR_FAILURE;
				}
			}

			OGRGeometry *poGeometry = NULL;
			// Geometry columns will have the first 4 bytes contain the SRID.
			OGRGeometryFactory::createFromWkb(((GByte *)row[0]) + 4,
											  NULL,
											  &poGeometry,
											  static_cast<int>(panLengths[0] - 4) );

			if ( poGeometry != NULL )
			{
				if (poGeometry && !bExtentSet)
				{
					poGeometry->getEnvelope(psExtent);
					bExtentSet = TRUE;
				}
				else if (poGeometry)
				{
					poGeometry->getEnvelope(&oEnv);
					if (oEnv.MinX < psExtent->MinX)
						psExtent->MinX = oEnv.MinX;
					if (oEnv.MinY < psExtent->MinY)
						psExtent->MinY = oEnv.MinY;
					if (oEnv.MaxX > psExtent->MaxX)
						psExtent->MaxX = oEnv.MaxX;
					if (oEnv.MaxY > psExtent->MaxY)
						psExtent->MaxY = oEnv.MaxY;
				}
				delete poGeometry;
			}
		}

		mysql_free_result(result);
	}

	return (bExtentSet ? OGRERR_NONE : OGRERR_FAILURE);
}
Beispiel #15
0
static Variant HHVM_FUNCTION(mysql_result, const Resource& result, int row,
                                    const Variant& field /* = 0 */) {
  MySQLResult *res = php_mysql_extract_result(result);
  if (res == NULL) return false;

  MYSQL_RES *mysql_result = NULL;
  MYSQL_ROW sql_row = NULL;
  unsigned long *sql_row_lengths = NULL;

  if (res->isLocalized()) {
    if (!res->seekRow(row)) return false;
    if (!res->fetchRow()) return false;
  } else {
    mysql_result = res->get();
    if (row < 0 || row >= (int)mysql_num_rows(mysql_result)) {
      raise_warning("Unable to jump to row %d on MySQL result index %d",
                      row, result->o_getId());
      return false;
    }
    mysql_data_seek(mysql_result, row);

    sql_row = mysql_fetch_row(mysql_result);
    if (!sql_row) {
      return false;
    }
    sql_row_lengths = mysql_fetch_lengths(mysql_result);
    if (!sql_row_lengths) {
      return false;
    }
  }

  int field_offset = 0;
  if (!field.isNull()) {
    if (field.isString()) {
      String sfield = field.toString();
      const char *tmp = strchr(sfield.data(), '.');
      String table_name, field_name;
      if (tmp) {
        int pos = tmp - sfield.data();
        table_name = sfield.substr(0, pos);
        field_name = sfield.substr(pos + 1);
      } else {
        field_name = sfield;
      }

      int i = 0;
      bool found = false;
      res->seekField(0);
      while (i < res->getFieldCount()) {
        MySQLFieldInfo *info = res->getFieldInfo(i);
        if ((table_name.empty() || table_name.same(info->table)) &&
            field_name.same(info->name)) {
          field_offset = i;
          found = true;
          break;
        }
        i++;
      }
      if (!found) { /* no match found */
        raise_warning("%s%s%s not found in MySQL result index %d",
                        table_name.data(), (table_name.empty() ? "" : "."),
                        field_name.data(), result->o_getId());
        return false;
      }
    } else {
      field_offset = field.toInt32();
      if (field_offset < 0 ||
          field_offset >= (int)res->getFieldCount()) {
        raise_warning("Bad column offset specified");
        return false;
      }
    }
  }

  if (res->isLocalized()) {
    Variant f = res->getField(field_offset);
    if (!f.isNull()) {
      return f.toString();
    }
  } else {
    if (sql_row[field_offset]) {
      return String(sql_row[field_offset], sql_row_lengths[field_offset],
                    CopyString);
    }
  }
  return init_null();
}
//---------------------------------------------------------------------------
red_students __fastcall  TFormReportStudsCandRedDiplom::GetRedStudents(int idGroup)
{
    ClearRedStudentsQuery();

    MYSQL_RES *result;
    MYSQL_ROW row;

    AnsiString query = "set @grpid = " + IntToStr(idGroup);
    mysql_query(mysql, query.c_str());
    mysql_query(mysql,"CREATE TEMPORARY TABLE temp_stud TYPE = HEAP "
                "SELECT st.id, st.firstname, st.secondname, st.thirdname, st.znum "
                "FROM students as st "
                "WHERE  st.grpid = @grpid AND st.deleted = 0 ");

    mysql_query(mysql,"CREATE TEMPORARY TABLE temp_progress1 TYPE = HEAP "
                "SELECT pr.*, st.firstname, st.secondname, st.thirdname, st.znum "
                "FROM progress as pr, temp_stud  as st "
                "WHERE  pr.idstud = st.id AND pr.deleted = 0 AND pr.estimation < 3 ");

    mysql_query(mysql,"CREATE TEMPORARY TABLE temp_progress2 TYPE = HEAP "
                "SELECT idstud, iddiscip, MAX(numplansemestr) as numplansemestr "
                "FROM temp_progress1 "
                "GROUP BY idstud, iddiscip ");

    mysql_query(mysql,"CREATE TEMPORARY TABLE temp_progress3 TYPE = HEAP "
                "SELECT pr1.* "
                "FROM temp_progress1 as pr1, temp_progress2 as pr2 "
                "WHERE pr1.idstud = pr2.idstud AND pr1.iddiscip = pr2.iddiscip "
                "AND pr1.numplansemestr = pr2.numplansemestr ");

    mysql_query(mysql,"select idstud,secondname,firstname, thirdname, znum, "
                "sum(case  when estimation=0 then 1 else 0 end) as otl, "
                "sum(case  when estimation=1 then 1 else 0 end) as hor, "
                "sum(case  when estimation=2 then 1 else 0 end) as ud, "
                "AVG(ball) as sr "
                "from temp_progress3 "
                "group by idstud "
                "order by secondname ");

    std::vector<red_student> redStudents;

    result=mysql_store_result(mysql);
    if (result && mysql_num_rows(result))
    {
        while (row = mysql_fetch_row(result))
        {
            red_student redStudent;
            redStudent.name = row[1] + AnsiString(" ") + row[2] + AnsiString(" ") + row[3];
            redStudent.znum = row[4];

            int CountZero = 6 - redStudent.znum.Length();
            for (int it = 0; it < CountZero; it++)
                redStudent.znum = "0" + redStudent.znum;

            redStudent.count_otl = AnsiString(row[5]).ToInt();
            redStudent.count_hor = AnsiString(row[6]).ToInt();
            redStudent.count_ud  = AnsiString(row[7]).ToInt();

            int ballCount = redStudent.count_otl + redStudent.count_hor + redStudent.count_ud;
            if (ballCount == 0)
                continue;

            redStudent.perc_otl = 100.0 * double(redStudent.count_otl) / double(ballCount);
            redStudent.perc_hor = 100.0 * double(redStudent.count_hor) / double(ballCount);
            redStudent.perc_ud  = 100.0 * double(redStudent.count_ud) / double(ballCount);

            TReplaceFlags flags;
            flags << rfReplaceAll << rfIgnoreCase;
            redStudent.avrBall = StringReplace(row[8], ".", ",", flags);
            char str[10];
            sprintf(str,"%4.2lf", redStudent.avrBall.ToDouble());
            redStudent.avrBall = AnsiString(str);

            if (redStudent.count_ud <= 1 && redStudent.perc_otl >= 75.00)
                redStudents.push_back(redStudent);
        }
    }
    mysql_free_result(result);

    ClearRedStudentsQuery();
    return redStudents;
}
Beispiel #17
0
int sqlrow(DB db,SQL sql,const char *format,...)
{
	sqlchain *q;
	sqlchain *r;
	MYSQL_ROW row;
	char *p;
	int *i;
	int j;
	char **t;
	int column;
	va_list ap;
	char cmd[8192];

	if(!db||!sql)
	{
		printf("sqlrow: bad database/query handle\n");
		return -1;
	}

	for(q=sql->sql;q;q=q->next)if(q->type==SQLTYPE_RESULT)break;
	if(!q)
	{
		printf("sql row: internal error\n");
		goto out0;
	}
	if(!q->u.r)
	{
		for(j=1,r=sql->sql;r;r=r->next)if(r->type!=SQLTYPE_RESULT)
			j+=r->len;
		if(j<sizeof(cmd))p=cmd;
		else if(!(p=malloc(j)))goto out1;
		for(j=0,r=sql->sql;r;r=r->next)if(r->type!=SQLTYPE_RESULT)
		{
			memcpy(p+j,r->u.string,r->len);
			j+=r->len;
		}
		p[j]=0;
		if(mysql_query(db,p))
		{
			printf("mysql query for %s: %s\n",p,
				mysql_error(db));
			if(p!=cmd)free(p);
			goto out0;
		}
		if(p!=cmd)free(p);
		if(!(q->u.r=mysql_store_result(db)))
		{
			q->len=0;
			if(mysql_field_count(db))goto out1;
			else return 1;
		}
		q->len=(int)mysql_num_fields(q->u.r);
	}

	if(!(row=mysql_fetch_row(q->u.r)))return 1;

	va_start(ap,format);
	for(column=0;*format;column++)switch(*format++)
	{
	case 'i':
		if(column==q->len)
		{
			printf("format error\n");
			goto out0;
		}
		i=va_arg(ap,int *);
		*i=atoi(row[column]);
		break;
	case 't':
		if(column==q->len)
		{
			printf("format error\n");
			goto out0;
		}
		t=va_arg(ap,char **);
		*t=row[column];
		break;
	default:printf("unknown format %c\n",format[-1]);
		va_end(ap);
		goto out0;
	}
	va_end(ap);

	return 0;

out1:   printf("sqlrow: out of memory\n");
out0:   return -1;
}
Beispiel #18
0
/**
 * Monitor an individual server. Does not deal with the setting of master or
 * slave bits, except for clearing them when a server is not joined to the
 * cluster.
 *
 * @param handle        The MySQL Monitor object
 * @param database      The database to probe
 */
static void
monitorDatabase(MONITOR *mon, MONITOR_SERVERS *database)
{
    GALERA_MONITOR* handle = (GALERA_MONITOR*) mon->handle;
    MYSQL_ROW row;
    MYSQL_RES *result, *result2;
    int isjoined = 0;
    unsigned long int server_version = 0;
    char *server_string;
    SERVER temp_server;

    /* Don't even probe server flagged as in maintenance */
    if (SERVER_IN_MAINT(database->server))
        return;

    /** Store previous status */
    database->mon_prev_status = database->server->status;

    server_transfer_status(&temp_server, database->server);
    server_clear_status(&temp_server, SERVER_RUNNING);
    /* Also clear Joined */
    server_clear_status(&temp_server, SERVER_JOINED);

    connect_result_t rval = mon_connect_to_db(mon, database);
    if (rval != MONITOR_CONN_OK)
    {
        if (mysql_errno(database->con) == ER_ACCESS_DENIED_ERROR)
        {
            server_set_status(&temp_server, SERVER_AUTH_ERROR);
        }
        else
        {
            server_clear_status(&temp_server, SERVER_AUTH_ERROR);
        }

        database->server->node_id = -1;

        if (mon_status_changed(database) && mon_print_fail_status(database))
        {
            mon_log_connect_error(database, rval);
        }

        server_transfer_status(database->server, &temp_server);

        return;
    }

    /* If we get this far then we have a working connection */
    server_set_status(&temp_server, SERVER_RUNNING);

    /* get server version string */
    server_string = (char *) mysql_get_server_info(database->con);
    if (server_string)
    {
        server_set_version_string(database->server, server_string);
    }

    /* Check if the the Galera FSM shows this node is joined to the cluster */
    if (mysql_query(database->con, "SHOW STATUS LIKE 'wsrep_local_state'") == 0
        && (result = mysql_store_result(database->con)) != NULL)
    {
        if (mysql_field_count(database->con) < 2)
        {
            mysql_free_result(result);
            MXS_ERROR("Unexpected result for \"SHOW STATUS LIKE 'wsrep_local_state'\". "
                      "Expected 2 columns."
                      " MySQL Version: %s", version_str);
            return;
        }

        while ((row = mysql_fetch_row(result)))
        {
            if (strcmp(row[1], "4") == 0)
                isjoined = 1;

                /* Check if the node is a donor and is using xtrabackup, in this case it can stay alive */
            else if (strcmp(row[1], "2") == 0 && handle->availableWhenDonor == 1)
            {
                if (mysql_query(database->con, "SHOW VARIABLES LIKE 'wsrep_sst_method'") == 0
                    && (result2 = mysql_store_result(database->con)) != NULL)
                {
                    if (mysql_field_count(database->con) < 2)
                    {
                        mysql_free_result(result);
                        mysql_free_result(result2);
                        MXS_ERROR("Unexpected result for \"SHOW VARIABLES LIKE "
                                  "'wsrep_sst_method'\". Expected 2 columns."
                                  " MySQL Version: %s", version_str);
                        return;
                    }
                    while ((row = mysql_fetch_row(result2)))
                    {
                        if (strncmp(row[1], "xtrabackup", 10) == 0)
                            isjoined = 1;
                    }
                    mysql_free_result(result2);
                }
            }
        }
        mysql_free_result(result);
    }

    /* Check the the Galera node index in the cluster */
    if (mysql_query(database->con, "SHOW STATUS LIKE 'wsrep_local_index'") == 0
        && (result = mysql_store_result(database->con)) != NULL)
    {
        long local_index = -1;

        if (mysql_field_count(database->con) < 2)
        {
            mysql_free_result(result);
            MXS_ERROR("Unexpected result for \"SHOW STATUS LIKE 'wsrep_local_index'\". "
                      "Expected 2 columns."
                      " MySQL Version: %s", version_str);
            return;
        }

        while ((row = mysql_fetch_row(result)))
        {
            char* endchar;
            local_index = strtol(row[1], &endchar, 10);
            if (*endchar != '\0' ||
                (errno == ERANGE && (local_index == LONG_MAX || local_index == LONG_MIN)))
            {
                ss_dassert(false);
                local_index = -1;
            }
            database->server->node_id = local_index;
        }
        mysql_free_result(result);
    }

    if (isjoined)
    {
        server_set_status(&temp_server, SERVER_JOINED);
    }
    else
    {
        server_clear_status(&temp_server, SERVER_JOINED);
    }

    /* clear bits for non member nodes */
    if (!SERVER_IN_MAINT(database->server) && (!SERVER_IS_JOINED(&temp_server)))
    {
        database->server->depth = -1;

        /* clear M/S status */
        server_clear_status(&temp_server, SERVER_SLAVE);
        server_clear_status(&temp_server, SERVER_MASTER);

        /* clear master sticky status */
        server_clear_status(&temp_server, SERVER_MASTER_STICKINESS);
    }

    server_transfer_status(database->server, &temp_server);
}
int main(int argc, char *argv[]) {

    MYSQL my_conn;
    MYSQL_RES *res_ptr;
    MYSQL_ROW sqlrow;
    int res;

    if (!mysql_init(&my_conn)) {
        fprintf(stderr, "mysql_init failed\n");
        return EXIT_FAILURE;
    }

    if (mysql_real_connect(
                &my_conn, "localhost", "trox", "trox", "foo", 0, NULL, 0)) {
        printf("Connection success\n");

        /* update Jenny to be 8 and not 7 */
        res = mysql_query(&my_conn,
                "UPDATE children SET age = 8 WHERE fname = 'Jenny'");
        if (!res) { // return of zero means success
            printf("Updated %lu rows\n",
                   (unsigned long) mysql_affected_rows(&my_conn));
        } else {
            fprintf(stderr, "UPDATE error %d: %s\n",
                    mysql_errno(&my_conn), mysql_error(&my_conn));
        }

        /* Add a new entry, Flora */
        res = mysql_query(
                &my_conn,
                "INSERT INTO children(fname, age) VALUES('Flora', 10)"
        );
        if (!res) { // return of zero means success
            printf("Inserted %lu rows\n",
                   (unsigned long) mysql_affected_rows(&my_conn));
        } else {
            fprintf(stderr, "INSERT error %d: %s\n",
                    mysql_errno(&my_conn), mysql_error(&my_conn));
        }

        /* See what the auto-incremented childno was for Flora */
        res = mysql_query(&my_conn, "SELECT LAST_INSERT_ID()");
        if (!res) { // return of zero means success
            // get the result, in a single batch
            res_ptr = mysql_store_result(&my_conn);
            if (res_ptr) {
                // count the number of rows. This works for a result that
                // was obtained via mysql_store_result, but not if you get
                // it from mysql_use_result (see next example)... the same
                // goes for the mysql_row_seek function, which you will rarely
                // use but lets you seek rows in batched result sets.
                printf("Selecting for last insert id gave %lu rows\n",
                       (unsigned long) mysql_num_rows(res_ptr));
                // there should only be one row, but this is the typical
                // pattern for iterating over a result.
                while ((sqlrow = mysql_fetch_row(res_ptr))) {
                    printf("We inserted childno %s\n", sqlrow[0]);
                }
                // use this method to release allocated resources
                mysql_free_result(res_ptr);
            }
        } else {
            fprintf(stderr, "SELECT error %d: %s\n",
                    mysql_errno(&my_conn), mysql_error(&my_conn));
        }
    } else {
        fprintf(stderr, "Connection failed %d: %s\n",
                mysql_errno(&my_conn), mysql_error(&my_conn));
    }
    return 0;
}
Beispiel #20
0
static int mysql_read_slave_stats (mysql_database_t *db, MYSQL *con)
{
	MYSQL_RES *res;
	MYSQL_ROW  row;

	char *query;
	int   field_num;

	/* WTF? libmysqlclient does not seem to provide any means to
	 * translate a column name to a column index ... :-/ */
	const int READ_MASTER_LOG_POS_IDX   = 6;
	const int SLAVE_IO_RUNNING_IDX      = 10;
	const int SLAVE_SQL_RUNNING_IDX     = 11;
	const int EXEC_MASTER_LOG_POS_IDX   = 21;
	const int SECONDS_BEHIND_MASTER_IDX = 32;

	query = "SHOW SLAVE STATUS";

	res = exec_query (con, query);
	if (res == NULL)
		return (-1);

	row = mysql_fetch_row (res);
	if (row == NULL)
	{
		ERROR ("mysql plugin: Failed to get slave statistics: "
				"`%s' did not return any rows.", query);
		return (-1);
	}

	field_num = mysql_num_fields (res);
	if (field_num < 33)
	{
		ERROR ("mysql plugin: Failed to get slave statistics: "
				"`%s' returned less than 33 columns.", query);
		return (-1);
	}

	if (db->slave_stats)
	{
		unsigned long long counter;
		double gauge;

		counter = atoll (row[READ_MASTER_LOG_POS_IDX]);
		counter_submit ("mysql_log_position", "slave-read", counter, db);

		counter = atoll (row[EXEC_MASTER_LOG_POS_IDX]);
		counter_submit ("mysql_log_position", "slave-exec", counter, db);

		if (row[SECONDS_BEHIND_MASTER_IDX] != NULL)
		{
			gauge = atof (row[SECONDS_BEHIND_MASTER_IDX]);
			gauge_submit ("time_offset", NULL, gauge, db);
		}
	}

	if (db->slave_notif)
	{
		notification_t n = { 0, time (NULL), "", "",
			"mysql", "", "time_offset", "", NULL };

		char *io, *sql;

		io  = row[SLAVE_IO_RUNNING_IDX];
		sql = row[SLAVE_SQL_RUNNING_IDX];

		set_host (db, n.host, sizeof (n.host));
		set_plugin_instance (db,
				n.plugin_instance, sizeof (n.plugin_instance));

		if (((io == NULL) || (strcasecmp (io, "yes") != 0))
				&& (db->slave_io_running))
		{
			n.severity = NOTIF_WARNING;
			ssnprintf (n.message, sizeof (n.message),
					"slave I/O thread not started or not connected to master");
			plugin_dispatch_notification (&n);
			db->slave_io_running = 0;
		}
		else if (((io != NULL) && (strcasecmp (io, "yes") == 0))
				&& (! db->slave_io_running))
		{
			n.severity = NOTIF_OKAY;
			ssnprintf (n.message, sizeof (n.message),
					"slave I/O thread started and connected to master");
			plugin_dispatch_notification (&n);
			db->slave_io_running = 1;
		}

		if (((sql == NULL) || (strcasecmp (sql, "yes") != 0))
				&& (db->slave_sql_running))
		{
			n.severity = NOTIF_WARNING;
			ssnprintf (n.message, sizeof (n.message),
					"slave SQL thread not started");
			plugin_dispatch_notification (&n);
			db->slave_sql_running = 0;
		}
		else if (((sql != NULL) && (strcasecmp (sql, "yes") == 0))
				&& (! db->slave_sql_running))
		{
			n.severity = NOTIF_OKAY;
			ssnprintf (n.message, sizeof (n.message),
					"slave SQL thread started");
			plugin_dispatch_notification (&n);
			db->slave_sql_running = 0;
		}
	}

	row = mysql_fetch_row (res);
	if (row != NULL)
		WARNING ("mysql plugin: `%s' returned more than one row - "
				"ignoring further results.", query);

	mysql_free_result (res);

	return (0);
} /* mysql_read_slave_stats */
Beispiel #21
0
int stmd_SmsSelect(int time_type, char *table_type)
{
    char        condBuf[4096], tmpBuf[1024];
    int         sts_code;
    char        str_time[10];
    int         select_cnt = 0;

    char        query[4096];
    MYSQL_RES   *result;
    MYSQL_ROW   row;

    time_t      now;
    char        tm[DIR_NUM][8];
    char        path[60];
    char        fileName[60];
    FILE        *fp;

    int         i,j;
    char title[5][16]={"SYSTEM", "SMSC_IP", "REQ", "SUCC","FAIL"};
	char title1[6][16]={"", "", "SMPP_ERR","SVR_ERR","SMSC_ERR","ETC_ERR"};
    int row_index;
    char SysName[2][8] = {"SCMA", "SCMB"};
    int realSysCnt =2;
    int realItemCnt[2] = {0, 0};
	char smsc_ip[2][16];
	int	exist = 0;

    now = time(0);
    if(time_type != STMD_WEEK)
        now = now - (printTIME[time_type]*60) - STAT_OFFSET_UNIT;
    else
        now = now - (printTIME[time_type]*60);

    getFilePath (path, tm, &now); // ~/LOG/STAT 까지 만든다.
    makeDirectory (time_type,path,tm);

    sprintf(fileName,"%s", path );
    makeFileName ( fileName, STMD_SMS, time_type, tm );

    if ( ( fp = fopen(fileName, APPEND ) ) == NULL ){
        sprintf(trcBuf, "%s Open Fail\n", fileName);
        trclib_writeLog(FL, trcBuf);
        return -1;
    }

    switch (time_type) {
        case    STMD_HOUR :
            sts_code = STSCODE_STM_PERIODIC_SMS_HOUR;
            sprintf(str_time, "%s", STMD_STR_HOUR);
            break;
        case    STMD_DAY :
            sts_code = STSCODE_STM_PERIODIC_SMS_DAY;
            sprintf(str_time, "%s", STMD_STR_DAY);
            break;
        case    STMD_WEEK :
            sts_code = STSCODE_STM_PERIODIC_SMS_WEEK;
            sprintf (str_time, "%s", STMD_STR_WEEK);
            break;
        case    STMD_MONTH :
            sts_code = STSCODE_STM_PERIODIC_SMS_MONTH;
            sprintf (str_time, "%s", STMD_STR_MONTH);
            break;
    }

    sprintf(condBuf,"    %s %s\n    S%04d SMS PERIODIC STATISTICS MESSAGE\n",
        "SCM", // 현재는 OMP로 고정하지만 실질적인 시스템 이름으로 변경 필요 hslim_oper
        commlib_printTStamp(), // 현재시각 time stamp (년,월,일,시,분,초,요일)
        sts_code);

    sprintf(tmpBuf, "    PERIOD = %s\n    MEASURETIME = %s  -  %s\n\n",
        str_time,
        get_period_start_time(time_type), get_period_end_time(time_type));

    strcat(condBuf,tmpBuf);

    sprintf(tmpBuf, "    ====================================================================================\n");
    strcat(condBuf, tmpBuf);
    sprintf(tmpBuf, "%3s %8s %18s %12s %12s %12s\n","",title[0],title[1],title[2],title[3],title[4] );
    strcat(condBuf, tmpBuf);
    sprintf(tmpBuf, "%3s %8s %18s %12s %12s %12s %12s\n", "","", "", title1[2],title1[3],title1[4],title1[5]);
    strcat(condBuf, tmpBuf);
    sprintf(tmpBuf, "    ====================================================================================\n");
    strcat(condBuf, tmpBuf);

	memset(smsc_ip, 0x00, sizeof(smsc_ip));
    for(i = 0; i < realSysCnt; i++)
	{
	   sprintf(query, "SELECT code, count(*) from ip_code_tbl where type = 2 group by code");

		if (stmd_mysql_query (query) < 0) {
            sprintf(trcBuf,">>> mysql_query fail; err=%s\n", mysql_error(conn));
            trclib_writeLogErr (FL,trcBuf);
            if(fp != NULL) fclose(fp);
            return -1;
	   }
	   result = mysql_store_result(conn);
	   row = mysql_fetch_row(result);
	   if( row == NULL )
	   {
		   exist = 0;
		   realItemCnt[i] = 0;
		   mysql_free_result(result);
		   continue;
	   }
	   else
	   {
		   exist = 1;
		   realItemCnt[i] = atoi(row[1]);
		   sprintf(smsc_ip[i], "%s", row[0]);
		   mysql_free_result(result);
	   }
	   
	   sprintf(query, "SELECT system_name, smsc_ip, "
			   " IFNULL(SUM(req), 0), IFNULL(SUM(succ), 0), IFNULL(SUM(fail), 0), "
			   " IFNULL(SUM(smpp_err), 0), " 
			   " IFNULL(SUM(svr_err), 0), IFNULL(SUM(smsc_err), 0), " 
			   " IFNULL(SUM(etc_err), 0) "
			   " from %s "
			   " where system_name = '%s' AND (stat_date = '%s') "
			   " group by system_name, smsc_ip ",
			   table_type, SysName[i], get_period_select_time(time_type));

        if ( trcLogFlag == TRCLEVEL_SQL ) {
            sprintf(trcBuf, "query = %s\n", query);
            trclib_writeLog(FL, trcBuf);
        }
		if (stmd_mysql_query (query) < 0) {
            sprintf(trcBuf,">>> mysql_query fail; err=%s\n", mysql_error(conn));
            trclib_writeLogErr (FL,trcBuf);
            if(fp != NULL) fclose(fp);
            return -1;
        }

		logPrint(trcLogId, FL, "SMS Period query : %s\n", query);

        result = mysql_store_result(conn);

		select_cnt = 0;
        while((row = mysql_fetch_row(result)) != NULL) 
		{
            row_index = 2;
			if (select_cnt==0)
			{
				sprintf(tmpBuf, "%3s %8s %18s %12s %12s %12s\n",
						"", row[0], row[1], row[row_index],row[row_index+1],row[row_index+2]);
				strcat(condBuf, tmpBuf);
				sprintf(tmpBuf, "%3s %8s %18s %12s %12s %12s %12s\n",
						"", "", "", row[row_index+3],row[row_index+4],row[row_index+5],row[row_index+6]);
				strcat(condBuf, tmpBuf);
			} 
			else 
			{
				sprintf(tmpBuf, "%3s %8s %18s %12s %12s %12s\n",
						"", "", row[1], row[row_index],row[row_index+1],row[row_index+2]);
				strcat(condBuf, tmpBuf);
				sprintf(tmpBuf, "%3s %8s %18s %12s %12s %12s %12s\n",
						"", "", "", row[row_index+3], row[row_index+4],row[row_index+5],row[row_index+6] );
				strcat(condBuf, tmpBuf);
			}

    		sprintf(tmpBuf, "    ====================================================================================\n");
            strcat(condBuf, tmpBuf);

            select_cnt++;
        }
        mysql_free_result(result);

        if (select_cnt == 0) 
		{
			for( j = 0; j < realItemCnt[i]; j++ )
			{
				if (j==0)
				{
					sprintf(tmpBuf, "%3s %8s %18s %12s %12s %12s\n",
							"", SysName[i], smsc_ip[j], "0", "0", "0");
					strcat(condBuf, tmpBuf);
					sprintf(tmpBuf, "%3s %8s %18s %12s %12s %12s %12s\n",
							"", "", "", "0", "0", "0","0" );
					strcat(condBuf, tmpBuf);
				}
				else 
				{
					sprintf(tmpBuf, "%3s %8s %18s %12s %12s %12s\n",
							"", "", smsc_ip[j], "0", "0", "0");
					strcat(condBuf, tmpBuf);
					sprintf(tmpBuf, "%3s %8s %18s %12s %12s %12s %12s\n",
							"", "", "", "0", "0", "0","0" );
					strcat(condBuf, tmpBuf);
				}
			}
    		sprintf(tmpBuf, "    ====================================================================================\n");
            strcat(condBuf, tmpBuf);
        } 
    }

    sprintf(tmpBuf, "    COMPLETED\n\n\n");
    strcat(condBuf, tmpBuf);

    if(fp != NULL) 
	{
        fprintf (fp, "%s",condBuf);
        fclose(fp);
    }
    
    stmd_txMsg2Cond(condBuf, (sts_code - STSCODE_TO_MSGID_STATISTICS), 0, 1);
    
    return 1;
}
Beispiel #22
0
static int mysql_read (user_data_t *ud)
{
	mysql_database_t *db;
	MYSQL     *con;
	MYSQL_RES *res;
	MYSQL_ROW  row;
	char      *query;
	int        field_num;

	unsigned long long qcache_hits          = 0ULL;
	unsigned long long qcache_inserts       = 0ULL;
	unsigned long long qcache_not_cached    = 0ULL;
	unsigned long long qcache_lowmem_prunes = 0ULL;
	int qcache_queries_in_cache = -1;

	int threads_running   = -1;
	int threads_connected = -1;
	int threads_cached    = -1;
	unsigned long long threads_created = 0ULL;

	unsigned long long traffic_incoming = 0ULL;
	unsigned long long traffic_outgoing = 0ULL;

	if ((ud == NULL) || (ud->data == NULL))
	{
		ERROR ("mysql plugin: mysql_database_read: Invalid user data.");
		return (-1);
	}

	db = (mysql_database_t *) ud->data;

	/* An error message will have been printed in this case */
	if ((con = getconnection (db)) == NULL)
		return (-1);

	query = "SHOW STATUS";
	if (mysql_get_server_version (con) >= 50002)
		query = "SHOW GLOBAL STATUS";

	res = exec_query (con, query);
	if (res == NULL)
		return (-1);

	field_num = mysql_num_fields (res);
	while ((row = mysql_fetch_row (res)))
	{
		char *key;
		unsigned long long val;

		key = row[0];
		val = atoll (row[1]);

		if (strncmp (key, "Com_", 4) == 0)
		{
			if (val == 0ULL)
				continue;

			/* Ignore `prepared statements' */
			if (strncmp (key, "Com_stmt_", 9) != 0)
				counter_submit ("mysql_commands", key + 4, val, db);
		}
		else if (strncmp (key, "Handler_", 8) == 0)
		{
			if (val == 0ULL)
				continue;

			counter_submit ("mysql_handler", key + 8, val, db);
		}
		else if (strncmp (key, "Qcache_", 7) == 0)
		{
			if (strcmp (key, "Qcache_hits") == 0)
				qcache_hits = val;
			else if (strcmp (key, "Qcache_inserts") == 0)
				qcache_inserts = val;
			else if (strcmp (key, "Qcache_not_cached") == 0)
				qcache_not_cached = val;
			else if (strcmp (key, "Qcache_lowmem_prunes") == 0)
				qcache_lowmem_prunes = val;
			else if (strcmp (key, "Qcache_queries_in_cache") == 0)
				qcache_queries_in_cache = (int) val;
		}
		else if (strncmp (key, "Bytes_", 6) == 0)
		{
			if (strcmp (key, "Bytes_received") == 0)
				traffic_incoming += val;
			else if (strcmp (key, "Bytes_sent") == 0)
				traffic_outgoing += val;
		}
		else if (strncmp (key, "Threads_", 8) == 0)
		{
			if (strcmp (key, "Threads_running") == 0)
				threads_running = (int) val;
			else if (strcmp (key, "Threads_connected") == 0)
				threads_connected = (int) val;
			else if (strcmp (key, "Threads_cached") == 0)
				threads_cached = (int) val;
			else if (strcmp (key, "Threads_created") == 0)
				threads_created = val;
		}
	}
	mysql_free_result (res); res = NULL;

	if ((qcache_hits != 0ULL)
			|| (qcache_inserts != 0ULL)
			|| (qcache_not_cached != 0ULL)
			|| (qcache_lowmem_prunes != 0ULL))
		qcache_submit (qcache_hits, qcache_inserts, qcache_not_cached,
			       qcache_lowmem_prunes, qcache_queries_in_cache, db);

	if (threads_created != 0ULL)
		threads_submit (threads_running, threads_connected,
				threads_cached, threads_created, db);

	traffic_submit  (traffic_incoming, traffic_outgoing, db);

	if (db->master_stats)
		mysql_read_master_stats (db, con);

	if ((db->slave_stats) || (db->slave_notif))
		mysql_read_slave_stats (db, con);

	return (0);
} /* int mysql_read */
Beispiel #23
0
// When Server is ready
bool CCharServer::OnServerReady( )
{
    DB->QExecute( "DELETE FROM channels WHERE id=%u and type=%i", Config.ServerID, Config.ServerType );
    if(!DB->QExecute("INSERT INTO channels (id,type,name,host,port,lanip,lansubmask,connected,maxconnections,owner) VALUES (%i,%i,'%s','%s',%i,'%s','%s',0,%i,%i)",
                     Config.ServerID, Config.ServerType, Config.ServerName, Config.CharIP, Config.CharPort, Config.LanIP, Config.LanSubnet, Config.MaxConnections, Config.ParentID))
    {
        Log(MSG_WARNING, "Error accessing to database, the other server will not connect to CharServer" );
    }

    MYSQL_RES *result;
    MYSQL_ROW row;
    bool pflag = false;
    //Get IP and Port from Login
    result = DB->QStore( "SELECT host,port,lanip FROM channels WHERE id=%u and type=0", Config.ParentID );
    if(result==NULL) return false;
    if (mysql_num_rows( result ) == 1)
    {
        row = mysql_fetch_row( result );
        switch(Config.Connection)
        {
        case 0://wanip
            Config.LoginIP = row[0];
            break;
        case 1://lanip
            Config.LoginIP = row[2];
            break;
        default://localhost
            Config.LoginIP = (char*) "127.0.0.1";
            break;
        }
        Config.LoginPort =  atoi(row[1]);
        pflag = true;
    }
    DB->QFree( );
    if(pflag)
    {
        Log(  MSG_INFO, "Initialized loginserver connection" );
        // Connect To LoginServer
        lsock = socket( AF_INET, SOCK_STREAM, 0 );
        if (lsock == INVALID_SOCKET)
        {
            Log( MSG_WARNING, "Could not access login server" );
        }
        struct sockaddr_in ain;
        ain.sin_family		= AF_INET;
        ain.sin_addr.s_addr	= inet_addr( Config.LoginIP );
        ain.sin_port		= htons( Config.LoginPort );
        memset(&(ain.sin_zero), '\0', 8);
        if ( connect( lsock, (SOCKADDR*) &ain, sizeof(ain) ) == SOCKET_ERROR )
            Log( MSG_WARNING, "Could not access login server" );


        BEGINPACKET( pak, 0x500 );
        ADDDWORD   ( pak, Config.LoginPass );
        ADDDWORD   ( pak, Config.ServerID );
        ADDWORD    ( pak, Config.CharPort );
        cryptPacket( (char*)&pak, NULL );
        send( lsock, (char*)&pak, pak.Size, 0 );
    }
    // Load all our clans
    result = DB->QStore("SELECT id,logo,back,name,cp,grade,slogan,news,rankingpoints,siglogo FROM list_clan");
    if(result==NULL)  return false;
    while(row = mysql_fetch_row(result))
    {
        CClans* thisclan = new CClans;
        assert(thisclan);
        thisclan->id = atoi(row[0]);
        thisclan->logo = atoi(row[1]);
        thisclan->back = atoi(row[2]);
        strcpy(thisclan->name,row[3]);
        thisclan->cp = atoi(row[4]);
        thisclan->grade = atoi(row[5]);
        strcpy(thisclan->slogan,row[6]);
        strcpy(thisclan->news,row[7]);
        thisclan->rankingpoints=atoi(row[8]);
        thisclan->siglogo=atoi(row[9]);
        ClanList.push_back( thisclan );
    }
    DB->QFree( );
    // Load Clans
    for(UINT i=0; i<ClanList.size( ); i++)
    {
        CClans*	Clan = ClanList.at( i );
        result = DB->QStore("SELECT id,char_name,clan_rank FROM characters WHERE clanid=%i order by clan_rank",Clan->id);
        if(result==NULL) return false;
        while(row = mysql_fetch_row(result))
        {
            CClanMembers* newmember = new CClanMembers;
            assert(newmember);
            newmember->id = atoi(row[0]);
            strcpy(newmember->name,row[1]);
            newmember->clan_rank = atoi(row[2]);
            Clan->ClanMembers.push_back( newmember );
        }
        DB->QFree( );
    }

    result = DB->QStore("SELECT itemnum,itemtype,amount,slotnum,durability,sex,premium FROM items_newchar WHERE active='1'");
    if(result == NULL)return false;
    while(row = mysql_fetch_row(result))
    {
        CItemNewChar* tmp = new (nothrow) CItemNewChar();
        tmp->itemnum = atoi(row[0]);
        tmp->itemtype = atoi(row[1]);
        tmp->amount = atoi(row[2]);
        tmp->slotnum = atoi(row[3]);
        tmp->durability = atoi(row[4]);
        tmp->sex = atoi(row[5]);
        tmp->premium = atoi(row[6])?true:false;
        ItemNewChar.push_back(tmp);
    }
    DB->QFree( );

    Log( MSG_INFO, "Clans Information Loaded" );
    return true;
}
Beispiel #24
0
int main(int argc, char** argv) {
    MYSQL_RES *res_ptr;
    MYSQL_ROW sqlrow;

	int i = 0;
	int num_fields;
	
	//Default game time value
	gt.minute = 0;
	gt.hour = 0;
	gt.day = 1;
	gt.month = 1;
	gt.year = 1900;
    gt.weekdate = 1;
    gt.week_number = 1;


	//Init database
	db_main = mysql_init(NULL);
    db_rpy = mysql_init(NULL);
    db_rpjf = mysql_init(NULL);
    db_tip = mysql_init(NULL);
    
	if(mysql_real_connect(db_main, DB_IP, "server_main", DB_PASSWORD, DB_NAME, DB_PORT, NULL, 0)){
        mysql_real_connect(db_tip, DB_IP, "server_tip", DB_PASSWORD, DB_NAME, DB_PORT, NULL, 0);
        mysql_real_connect(db_rpjf, DB_IP, "server_rp_jf", DB_PASSWORD, DB_NAME, DB_PORT, NULL, 0);
        mysql_real_connect(db_rpy, DB_IP, "server_rp_y", DB_PASSWORD, DB_NAME, DB_PORT, NULL, 0);
        printf("[MySQL]Connection Success\n");
		res = mysql_query(db_main, "SELECT * from game_time WHERE id = 1");
		
		if(res){
			printf("[MySQL select error]\n");		
		}else{
			res_ptr = mysql_store_result(db_main);
			if(res_ptr){
				printf("Retrieved %lu Rows\n", (unsigned long)mysql_num_rows(res_ptr));	
				num_fields = mysql_num_fields(res_ptr);
				while((sqlrow = mysql_fetch_row(res_ptr))){
                                    gt.weekdate = atoi(sqlrow[1]);
                                    gt.year = atoi(sqlrow[2]);
                                    gt.month = atoi(sqlrow[3]);
                                    gt.day = atoi(sqlrow[4]);
                                    gt.hour = atoi(sqlrow[5]);
                                    gt.minute = atoi(sqlrow[6]);
                                    gt.week_number = atoi(sqlrow[7]);
				}
			}		
		}
        mysql_free_result(res_ptr);

		printf("Game time received : %2d-%2d-%2d %2d:%2d:0 [Week - %d]\n", gt.year, gt.month, gt.day, gt.hour, gt.minute, gt.week_number);
                
		i = pthread_create(&tt, NULL, timer_thread, NULL);
		pthread_join(tt, NULL);
	}else{
        printf("Could not connect to DB server\n");
        printf("MYSQL ERROR Number => %d", mysql_errno(db_main));
        return (1);
    }   
    return (EXIT_SUCCESS);
}
Beispiel #25
0
extern List setup_cluster_list_with_inx(mysql_conn_t *mysql_conn,
					slurmdb_job_cond_t *job_cond,
					void **curr_cluster)
{
	List local_cluster_list = NULL;
	time_t now = time(NULL);
	MYSQL_RES *result = NULL;
	MYSQL_ROW row;
	hostlist_t temp_hl = NULL;
	hostlist_iterator_t h_itr = NULL;
	char *query = NULL;
	int dims = 0;

	if (!job_cond || !job_cond->used_nodes)
		return NULL;

	if (!job_cond->cluster_list
	    || list_count(job_cond->cluster_list) != 1) {
		error("If you are doing a query against nodes "
		      "you must only have 1 cluster "
		      "you are asking for.");
		return NULL;
	}

	/* get the dimensions of this cluster so we know how to deal
	   with the hostlists */
	query = xstrdup_printf("select dimensions, flags from %s where "
			       "name='%s'",
			       cluster_table,
			       (char *)list_peek(job_cond->cluster_list));

	debug4("%d(%s:%d) query\n%s",
	       mysql_conn->conn, THIS_FILE, __LINE__, query);
	if (!(result = mysql_db_query_ret(mysql_conn, query, 0))) {
		xfree(query);
		return NULL;
	}
	xfree(query);

	if (!(row = mysql_fetch_row(result))) {
		error("Couldn't get the dimensions of cluster '%s'.",
		      (char *)list_peek(job_cond->cluster_list));
		return NULL;
	}

	/* On a Cray System when dealing with hostlists as we are here
	   this always needs to be 1.
	*/
	if (slurm_atoul(row[1]) & CLUSTER_FLAG_CRAYXT)
		dims = 1;
	else
		dims = atoi(row[0]);

	temp_hl = hostlist_create_dims(job_cond->used_nodes, dims);
	if (hostlist_count(temp_hl) <= 0) {
		error("we didn't get any real hosts to look for.");
		goto no_hosts;
	}
	h_itr = hostlist_iterator_create(temp_hl);

	query = xstrdup_printf("select cluster_nodes, time_start, "
			       "time_end from \"%s_%s\" where node_name='' "
			       "&& cluster_nodes !=''",
			       (char *)list_peek(job_cond->cluster_list),
			       event_table);

	if (job_cond->usage_start) {
		if (!job_cond->usage_end)
			job_cond->usage_end = now;

		xstrfmtcat(query,
			   " && ((time_start < %ld) "
			   "&& (time_end >= %ld || time_end = 0))",
			   job_cond->usage_end, job_cond->usage_start);
	}

	debug3("%d(%s:%d) query\n%s",
	       mysql_conn->conn, THIS_FILE, __LINE__, query);
	if (!(result = mysql_db_query_ret(mysql_conn, query, 0))) {
		xfree(query);
		goto no_hosts;
	}
	xfree(query);

	local_cluster_list = list_create(_destroy_local_cluster);
	while ((row = mysql_fetch_row(result))) {
		char *host = NULL;
		int loc = 0;
		local_cluster_t *local_cluster =
			xmalloc(sizeof(local_cluster_t));
		local_cluster->hl = hostlist_create_dims(row[0], dims);
		local_cluster->start = slurm_atoul(row[1]);
		local_cluster->end   = slurm_atoul(row[2]);
		local_cluster->asked_bitmap =
			bit_alloc(hostlist_count(local_cluster->hl));
		while ((host = hostlist_next_dims(h_itr, dims))) {
			if ((loc = hostlist_find(
				     local_cluster->hl, host)) != -1)
				bit_set(local_cluster->asked_bitmap, loc);
			free(host);
		}
		hostlist_iterator_reset(h_itr);
		if (bit_ffs(local_cluster->asked_bitmap) != -1) {
			list_append(local_cluster_list, local_cluster);
			if (local_cluster->end == 0) {
				local_cluster->end = now;
				(*curr_cluster) = local_cluster;
			}
		} else
			_destroy_local_cluster(local_cluster);
	}
	mysql_free_result(result);

	if (!list_count(local_cluster_list)) {
		list_destroy(local_cluster_list);
		local_cluster_list = NULL;
		goto no_hosts;
	}

no_hosts:

	hostlist_iterator_destroy(h_itr);
	hostlist_destroy(temp_hl);

	return local_cluster_list;
}
Beispiel #26
0
	// 序列化MySQL结果集
	bool Serialize(MYSQL_RES *result, ByteArray *out_bytes)
	{
		assert(result != nullptr && out_bytes != nullptr);
		if (result == nullptr || out_bytes == nullptr)
		{
			return false;
		}

		out_bytes->clear();
		size_t use_size = 0;
		std::array<char, (std::numeric_limits<uint16_t>::max)()> extrabuf;

		MYSQL_FIELD *fields = mysql_fetch_fields(result);
		const my_ulonglong num_rows = mysql_num_rows(result) + 1;
		const my_ulonglong num_fields = mysql_num_fields(result);
		use_size += snprintf(extrabuf.data(), extrabuf.size(), "%lld", num_rows) + 1;
		use_size += snprintf(extrabuf.data() + use_size, extrabuf.size() - use_size, "%lld", num_fields) + 1;

		// 首行存放字段名
		for (size_t i = 0; i < num_fields; ++i)
		{
			size_t field_size = strlen(fields[i].name) + 1;
			size_t new_use_size = use_size + field_size;
			if (new_use_size > extrabuf.size())
			{
				if (out_bytes->empty())
				{
					out_bytes->reserve(i == num_fields - 1 ? new_use_size : new_use_size * 2);
					out_bytes->resize(use_size);
					memcpy(out_bytes->data(), extrabuf.data(), use_size);
				}
				else
				{
					while (new_use_size > out_bytes->capacity())
					{
						out_bytes->reserve(new_use_size * 2);
					}
				}
				out_bytes->resize(new_use_size);
				memcpy(out_bytes->data() + use_size, fields[i].name, field_size);
			}
			else
			{
				memcpy(extrabuf.data() + use_size, fields[i].name, field_size);
			}
			use_size = new_use_size;
		}

		// 数据从第二行开始存放
		for (unsigned int row = 1; row < num_rows; ++row)
		{
			MYSQL_ROW row_data = mysql_fetch_row(result);
			assert(row_data != nullptr);
			for (unsigned int field = 0; field < num_fields; ++field)
			{
				bool is_null = row_data[field] == nullptr;
				size_t field_size = (is_null ? 0 : strlen(row_data[field])) + 1;
				size_t new_use_size = use_size + field_size;
				if (new_use_size > extrabuf.size())
				{
					if (out_bytes->empty())
					{
						out_bytes->reserve(row == num_rows - 1 && field == num_fields - 1 ? new_use_size : new_use_size * 2);
						out_bytes->resize(use_size);
						memcpy(out_bytes->data(), extrabuf.data(), use_size);
					}
					else
					{
						while (new_use_size > out_bytes->capacity())
						{
							out_bytes->reserve(new_use_size * 2);
						}
					}
					out_bytes->resize(new_use_size);
					if (is_null)
					{
						out_bytes->at(use_size) = '\0';
					}
					else
					{
						memcpy(out_bytes->data() + use_size, row_data[field], field_size);
					}
				}
				else
				{
					if (is_null)
					{
						extrabuf.data()[use_size] = '\0';
					}
					else
					{
						memcpy(extrabuf.data() + use_size, row_data[field], field_size);
					}
				}
				use_size = new_use_size;
			}
		}

		if (out_bytes->empty())
		{
			out_bytes->resize(use_size);
			memcpy(out_bytes->data(), extrabuf.data(), use_size);
		}

		return true;
	}
int analyze_bz2(char* f_name, struct stat filestats, int show_output) {

	long int bytes_read = 0; 		// total bytes read - (gigabytes read * bytes per gigabyte)
	char* tar_filename = f_name; 	// file to analyze
	char* real_filename;            // the filename without any directory info in front of it
	char* fullpath;             	// the absolute path to the file
	long int longtmp; 				// temporary variable for calculations
	long long int longlongtmp; 		// temporary variable for calculations
	int dberror = 0;                // indicate an error in analysis

	// End of archive check
	char archive_end_check[512];
	char archive_end[512];
	memset(archive_end, 0, sizeof(archive_end));

	// Information for BZ2 archive and member headers
	char membername[5000];				// name of member file
	long long int file_length;			// size of file in bytes (long int)
	char linkname[5000];				// name of linked file

	long int blocksize; // bz2 blocksize (inteval of 100 from 100kB to 900kB)
	int bzerror; // bz2 error checking
	int blocknumber = 0; // block number being read
	int numblocks = 1; // number of blocks data exists in
	int datafromarchivecheck = 0; //if archivecheck had to backtrack
	long int tmp_dataread;
	struct headerblock header;
	unsigned long long int archive_id; //id associated with the archive being analyzed

	//long name and link flags
	int the_name_is_long = 0;
	int the_link_is_long = 0;

	struct blockmap* block_offsets = (struct blockmap*) malloc(sizeof(struct blockmap));
	block_offsets->blocklocations = (struct blocklocation*) malloc(sizeof(struct blocklocation) * 200);
	block_offsets->maxsize = 200;

	int M_result = map_bzip2(tar_filename, block_offsets, show_output);
        if(M_result != 0) {
		printf("Error getting block sizes\n");
		free(block_offsets->blocklocations);
		free(block_offsets);
		return 1;
	}

	
	// get real filename
	real_filename = strrchr(tar_filename, '/');
	if (!real_filename) {
		real_filename = tar_filename;
	} 
	else {
		real_filename++;
	}
	fullpath = realpath(tar_filename, NULL);

	// connect to database, begin a transaction
	MYSQL *con = mysql_init(NULL);
	mysql_init(con);
	//read options from file
	mysql_options(con, MYSQL_READ_DEFAULT_FILE, SQLCONFILE); //SQLCONFILE defined in sqloptions.h
	mysql_options(con, MYSQL_READ_DEFAULT_GROUP, SQLGROUP);

	if(!mysql_real_connect(con, NULL, NULL, NULL, NULL, 0, NULL, 0)) {
		printf("Connection Failure: %s\n", mysql_error(con));
		//exit, no point
		mysql_close(con);
		free(block_offsets->blocklocations);
		free(block_offsets);
		return 1;
	}

	// begin transaction and check if this archive exists
	char insQuery[1000]; // insertion query buffer (we dont want current timestamp, we want the file's last modified timestamp)
	if(mysql_query(con, "START TRANSACTION")) {
		printf("Start Transaction error:\n%s\n", mysql_error(con));
		mysql_close(con);
		free(block_offsets->blocklocations);
		free(block_offsets);
		return 1;
	}

	//check if file already exists and ask for permission to overwrite and remove references
	sprintf(insQuery, "SELECT * from ArchiveList WHERE ArchiveName = '%s'", real_filename);
	if(mysql_query(con, insQuery)) {
		printf("Select error:\n%s\n", mysql_error(con));
		mysql_close(con);
		free(block_offsets->blocklocations);
		free(block_offsets);
		return 1;
	}
	MYSQL_RES* result = mysql_store_result(con);
	if(mysql_num_rows(result) == 0) {
		if(show_output) printf("File is not in database\n");
		//file foes not exist, do nothing
		mysql_free_result(result);
	}
	else {
		MYSQL_ROW row = mysql_fetch_row(result);
		mysql_free_result(result);
		char yes_no[20];
		sprintf(yes_no, "bad"); //prime with bad answer
		while(strcmp(yes_no, "y") && strcmp(yes_no, "Y") && strcmp(yes_no, "n") && strcmp(yes_no, "N")) {
			printf("File analysis already exists, overwrite[Y/N]: ");
			scanf("%s", yes_no);
		}
		// if N exit, if Y overwrite
		if(!strcmp(yes_no, "N") || !strcmp(yes_no, "n")) {
			if(mysql_query(con, "ROLLBACK")) {
				printf("Rollback error:\n%s\n", mysql_error(con));
			}
			mysql_close(con);
			free(block_offsets->blocklocations);
			free(block_offsets);
			return 1;
		}
		else {
			sprintf(insQuery, "DELETE FROM Bzip2_files WHERE ArchiveName = '%s'", real_filename);
			if(mysql_query(con, insQuery)) {
				if(show_output) printf("Delete error:\n%s\n", mysql_error(con));
				dberror = 1;
			}
			sprintf(insQuery, "DELETE FROM Bzip2_blocks WHERE ArchiveName = '%s'", real_filename);
			if(mysql_query(con, insQuery)) {
				if(show_output) printf("Delete error:\n%s\n", mysql_error(con));
				dberror = 1;
			}
			sprintf(insQuery, "DELETE FROM ArchiveList WHERE ArchiveName = '%s'", real_filename);
			if(mysql_query(con, insQuery)) {
				if(show_output) printf("Delete error:\n%s\n", mysql_error(con));
				dberror = 1;
			}
		}
	}
		
	// file is not in database or it has been cleared from database
	char* mod_time = ctime(&(filestats.st_mtime));
	sprintf(insQuery, "INSERT INTO ArchiveList VALUES (0, '%s', '%s', '%s')", real_filename, fullpath, mod_time);
	if(mysql_query(con, insQuery)) {
		if(show_output) printf("Insert error:\n%s\n", mysql_error(con));
		dberror = 1;
	}
	archive_id = mysql_insert_id(con);
	if(archive_id == 0) {
		if(show_output) printf("Archive Id error, was 0\n");
		dberror = 1;
	}

	// Get a block as a char pointer for easy byte incrementing
	blocknumber++;
	char* memblock = (char*) getblock_bzip(tar_filename, blocknumber, block_offsets);
	if(memblock == NULL) {
		mysql_close(con);
		free(block_offsets->blocklocations);
		free(block_offsets);
		printf("getting first block failed\n");
		return 1;
	}
	long int remainingdata = ((block_offsets->blocklocations)[blocknumber]).uncompressedSize;
	long int blockposition = 0;
	int firstrun = 1;

	while (1){
		// TAR HEADER SECTION - get tar header
		if(show_output) printf("BEGINNING FILE ANALYSIS\n");
		the_name_is_long = 0;
		the_link_is_long = 0;
		
		if(firstrun) {
			firstrun = 0;
			if(remainingdata >= 512){
				memcpy((void*) (&header), (memblock + blockposition), sizeof(header));
				remainingdata = remainingdata - sizeof(header);
				blockposition = blockposition + sizeof(header);
			}
			else {
				tmp_dataread = remainingdata;
				memcpy((void*) (&header), (memblock + blockposition), (sizeof(char) * remainingdata));
				free(memblock);

				blocknumber++;
				memblock = (char*) getblock_bzip(tar_filename, blocknumber, block_offsets);
				if(memblock == NULL) {
					mysql_close(con);
					free(block_offsets->blocklocations);
					free(block_offsets);
					return 1;
				}
				remainingdata = ((block_offsets->blocklocations)[blocknumber]).uncompressedSize;
				blockposition = 0;
	
				memcpy((void*)(((char*)&header) + tmp_dataread), (memblock + blockposition), (sizeof(char) * (512 - tmp_dataread)));
				remainingdata = remainingdata - (512 - tmp_dataread);
				blockposition = blockposition + (512 - tmp_dataread);
			}
		}

		// TAR HEADER SECTION - extract data from header

		// CHECK FOR ././@LongLink
		int tmp_longlink_position = 0;
		int position_incrementer = 0;
		while(strcmp(header.name, "././@LongLink") == 0) {
			if(show_output) printf("found a LongLink\n");

			//get length of name in bytes, adjust to be at end of block
			file_length = strtoll(header.size, NULL, 8);
			if((file_length % 512) != 0) {
				position_incrementer = file_length + (512 - (file_length % 512));
			}
			else {
				position_incrementer = file_length;
			}
			if(show_output) printf("LongLink's length (int): %lld\n", file_length);

			//copy longlink into proper area
			if(remainingdata >= position_incrementer){
				if(header.typeflag[0] == 'L') {
					memcpy((void*) membername, (memblock + blockposition), file_length);
					if(show_output) printf("READING INTO MEMBERNAME\n");
					the_name_is_long = 1;
				}
				else if(header.typeflag[0] == 'K') {
					memcpy((void*) linkname, (memblock + blockposition), file_length);
					if(show_output) printf("READING INTO LINKNAME\n");
					the_link_is_long = 1;
				}
				remainingdata = remainingdata - position_incrementer;
				blockposition = blockposition + position_incrementer;
			}
			else {
				tmp_dataread = remainingdata;
				if(header.typeflag[0] == 'L') {
					memcpy((void*) membername, (memblock + blockposition), (sizeof(char) * remainingdata));
					if(show_output) printf("READING INTO MEMBERNAME\n");
					the_name_is_long = 1;
				}
				else if(header.typeflag[0] == 'K') {
					memcpy((void*) linkname, (memblock + blockposition), (sizeof(char) * remainingdata));
					if(show_output) printf("READING INTO LINKNAME\n");
					the_link_is_long = 1;
				}
				free(memblock);

				blocknumber++;
				memblock = (char*) getblock_bzip(tar_filename, blocknumber, block_offsets);
				if(memblock == NULL) {
					mysql_close(con);
					free(block_offsets->blocklocations);
					free(block_offsets);
					return 1;
				}
				remainingdata = ((block_offsets->blocklocations)[blocknumber]).uncompressedSize;
				blockposition = 0;

				if(header.typeflag[0] == 'L') {
					memcpy((void*)(((char*)membername) + tmp_dataread), (memblock + blockposition), (sizeof(char) * (file_length - tmp_dataread)));
					if(show_output) printf("READING INTO MEMBERNAME\n");
					the_name_is_long = 1;
				}
				else if(header.typeflag[0] == 'K') {
					memcpy((void*)(((char*)linkname) + tmp_dataread), (memblock + blockposition), (sizeof(char) * (file_length - tmp_dataread)));
					if(show_output) printf("READING INTO LINKNAME\n");
					the_link_is_long = 1;
				}
				
				remainingdata = remainingdata - (position_incrementer - tmp_dataread);
				blockposition = blockposition + (position_incrementer - tmp_dataread);
			}

			// load in next header
			if(remainingdata >= 512){
				memcpy((void*) (&header), (memblock + blockposition), sizeof(header));
				remainingdata = remainingdata - sizeof(header);
				blockposition = blockposition + sizeof(header);
			}
			else {
				tmp_dataread = remainingdata;
				memcpy((void*) (&header), (memblock + blockposition), (sizeof(char) * remainingdata));
				free(memblock);

				blocknumber++;
				memblock = (char*) getblock_bzip(tar_filename, blocknumber, block_offsets);
				if(memblock == NULL) {
					mysql_close(con);
					free(block_offsets->blocklocations);
					free(block_offsets);
					return 1;
				}
				remainingdata = ((block_offsets->blocklocations)[blocknumber]).uncompressedSize;
				blockposition = 0;
	
				memcpy((void*)(((char*)&header) + tmp_dataread), (memblock + blockposition), (sizeof(char) * (512 - tmp_dataread)));
				remainingdata = remainingdata - (512 - tmp_dataread);
				blockposition = blockposition + (512 - tmp_dataread);
			}
		}

		//get filename
		if(!the_name_is_long) {
			strncpy(membername, header.name, 100);
		}
		if(show_output) printf("member name: %s\n", membername);

		//get length of file in bytes
		file_length = strtoll(header.size, NULL, 8);
		if(show_output) printf("file length (int): %lld\n", file_length);

		//get link flag (1 byte)
		if(show_output) printf("link flag: %c\n", header.typeflag[0]);

		//get linked filename (if flag set, otherwise this field is useless)
		if(!the_link_is_long) {
			strncpy(linkname, header.linkname, 100);
		}
		if(show_output) printf("link name: %s\n", linkname);


		// SKIP DATA SECTION - note the offset and skip the data
		//	-reminder: 	remainingdata: how much data is left in the block
		//			blockposition: essentially our position in the block

		int tmp_blocknumber = blocknumber; // temp to hold original blocknumber if data is in multiple blocks
		long int tmp_blockposition = blockposition; //temp to hold original block position if data is in multiple blocks
		numblocks = 1;

		// read longtmp = block adjusted file length
		if((file_length % 512) != 0) {
			longtmp = file_length + (512 - (file_length % 512));
		}
		else {
			longtmp = file_length;
		}

		if(show_output) printf("data begins in block %d, %ld bytes in\n", tmp_blocknumber, tmp_blockposition);
		if(file_length == 0) {
			// do nothing
		}
		else if(remainingdata >= longtmp) {
			remainingdata = remainingdata - longtmp;
			blockposition = blockposition + longtmp;
		}
		else {
			long long int file_data_remaining = longtmp;
			file_data_remaining = file_data_remaining - remainingdata;
			free(memblock);
			while(1) {
				blocknumber++;
				memblock = (char*) getblock_bzip(tar_filename, blocknumber, block_offsets);
				numblocks++;
				int sizeoftheblock = ((block_offsets->blocklocations)[blocknumber]).uncompressedSize;

				if(file_data_remaining == sizeoftheblock) {
					file_data_remaining = 0;
					remainingdata = 0;
					blockposition = 0;
					break;
				}
				else if(file_data_remaining < sizeoftheblock) {
					remainingdata = sizeoftheblock - file_data_remaining;
					blockposition = file_data_remaining;
					file_data_remaining = 0;
					break;
				}
				else {
					file_data_remaining = file_data_remaining - sizeoftheblock;
					free(memblock);
				}
			}
			
		}
		if(show_output) printf("file exists in %d blocks\n", numblocks);

		//convert to a name and directory path
		char membername_path[5000];
		char membername_file[5000];
		char* membername_ptr;

		//add beginning /
		sprintf(membername_path, "/%s", membername);

		//if last character is / kill it and set directory flag
		int slashes;
		char dirflag = 'N';
		if(membername_path[strlen(membername_path) - 1] == '/') {
			membername_path[strlen(membername_path) - 1] = '\0';
			slashes = 1;
			dirflag = 'Y';
		}
		else {
			slashes = 1;
		}

		//find breakpoint between filename and path
		membername_ptr = &(membername_path[strlen(membername_path) - 1]);
		while(1) {
			if(*membername_ptr == '/') slashes--;
			if(slashes == 0) break;
			membername_ptr--;
		}
		membername_ptr++; //now points to beginning of file name
		sprintf(membername_file, "%s", membername_ptr); //copy filename
		*membername_ptr = '\0'; // truncate path string

		if(show_output) {
			printf("MEMBERNAME PATH: %s\n", membername_path);
			printf("REAL MEMBERNAME: %s\n", membername_file);
		}

		// Build the query and submit it
		sprintf(insQuery, "INSERT INTO Bzip2_files VALUES (0, %llu, '%s', '%s', '%s', %d, %llu, %ld, %llu, '%c', '%c', %ld, %ld, %ld, '%s')", archive_id, real_filename, membername_file, membername_path, tmp_blocknumber, ((block_offsets->blocklocations)[tmp_blocknumber]).position, tmp_blockposition, strtoull(header.size, NULL, 8), header.typeflag[0], dirflag, strtol(header.mode, NULL, 8), strtol(header.uid, NULL, 8), strtol(header.gid, NULL, 8), linkname);
		if(mysql_query(con, insQuery)) {
			if(show_output) printf("Insert error:\n%s\n", mysql_error(con));
			dberror = 1;
		}
			
		//end printed info with newline
		if(show_output) printf("\n");

		// TEST ARCHIVE END SECTION - test for the end of the archive
		//	-reminder: 	remainingdata: how much data is left in the block
		//			blockposition: essentially our position in the block
		tmp_dataread = 0;
		if(remainingdata >= 512){
			memcpy((void*) archive_end_check, (memblock + blockposition), (sizeof(char) * 512));
			remainingdata = remainingdata - 512;
			blockposition = blockposition + 512;
		}
		else {
			tmp_dataread = remainingdata;
			memcpy((void*) archive_end_check, (memblock + blockposition), (sizeof(char) * remainingdata));
			free(memblock);

			blocknumber++;
			memblock = (char*) getblock_bzip(tar_filename, blocknumber, block_offsets);
			if(memblock == NULL) {
				mysql_close(con);
				free(block_offsets->blocklocations);
				free(block_offsets);
				return 1;
			}
			remainingdata = ((block_offsets->blocklocations)[blocknumber]).uncompressedSize;
			blockposition = 0;

			memcpy((void*)(((char*)archive_end_check) + tmp_dataread), (memblock + blockposition), (sizeof(char) * (512 - tmp_dataread)));
			remainingdata = remainingdata - (512 - tmp_dataread);
			blockposition = blockposition + (512 - tmp_dataread);
		}

		if(memcmp(archive_end_check, archive_end, sizeof(archive_end)) == 0) {
			//check subsequent block for zeros and error if not
			tmp_dataread = 0;
			if(remainingdata >= 512){
				memcpy((void*) archive_end_check, (memblock + blockposition), (sizeof(char) * 512));
				remainingdata = remainingdata - 512;
				blockposition = blockposition + 512;
			}
			else {
				tmp_dataread = remainingdata;
				memcpy((void*) archive_end_check, (memblock + blockposition), (sizeof(char) * remainingdata));
				free(memblock);

				blocknumber++;
				memblock = (char*) getblock_bzip(tar_filename, blocknumber, block_offsets);
				if(memblock == NULL) {
					mysql_close(con);
					free(block_offsets->blocklocations);
					free(block_offsets);
					return 1;
				}
				remainingdata = ((block_offsets->blocklocations)[blocknumber]).uncompressedSize;
				blockposition = 0;

				memcpy((void*)(((char*)archive_end_check) + tmp_dataread), (memblock + blockposition), (sizeof(char) * (512 - tmp_dataread)));
				remainingdata = remainingdata - (512 - tmp_dataread);
				blockposition = blockposition + (512 - tmp_dataread);
			}
			
			if(memcmp(archive_end_check, archive_end, sizeof(archive_end)) == 0) {
				break;
			}
			else {
				printf("improper end to tar file found stopping analysis\n");
				break;
			}
		}
		else {
			//put that 512 bytes as the next header
			memcpy((void*) (&header), (void*)archive_end_check, sizeof(header));
		}
	}

	free(memblock);

	//store the block map (blocknumber = the last block)
	int b_cur = 1;
	for(b_cur=1;b_cur<=blocknumber;b_cur++) {
		if(show_output) printf("storing block %d\n", b_cur);
		sprintf(insQuery, "INSERT INTO Bzip2_blocks VALUES (%llu, '%s', %d, %llu, %llu)", archive_id, real_filename, b_cur, ((block_offsets->blocklocations)[b_cur]).position, ((block_offsets->blocklocations)[b_cur]).uncompressedSize);
		if(mysql_query(con, insQuery)) {
			if(show_output) printf("Insert error:\n%s\n", mysql_error(con));
			dberror = 1;
		}
	}

	//the file has been read, commit the transation and close the connection
	if(dberror == 1) {
		if(mysql_query(con, "ROLLBACK")) {
			printf("Database error: Rollback error:\n%s\n", mysql_error(con));
		}
		else {
			printf("Database error: Entries rolled back\n");
		}
	}
	else {
		if(mysql_query(con, "COMMIT")) {
			printf("Commit error:\n%s\n", mysql_error(con));
		}
		else {
			if(show_output) printf("Entries committed\n");
		}
	}


	mysql_close(con);
	free(block_offsets->blocklocations);
	free(block_offsets);
	return 0;
}
Beispiel #28
0
void
get_run_config(char *mysql_database, char *session, int *run, char **config, char **conffile, char **datafile)
{
  MYSQL *connNum;
  MYSQL_RES *result;
  MYSQL_ROW row_out;
  char query[1024];

  *run=0;
  *config=NULL;
  *conffile=NULL;
  *datafile=NULL;

  /* connect to mysql database */
  connNum = dbConnect(getenv("MYSQL_HOST"), mysql_database);

  /* form mysql query, execute, then close mysql connection */
  sprintf(query,"SELECT runNumber,config FROM sessions WHERE name='%s'",session);
  if(mysql_query(connNum, query) != 0)
  {
    printf("get_run_config: ERROR in mysql_query 1\n");
    dbDisconnect(connNum);
    return;
  }

  if(!(result = mysql_store_result(connNum) ))
  {
    printf("get_run_config: ERROR in mysql_store_result 1\n");
    dbDisconnect(connNum);
    return;
  }

  /* get 'row_out' and check it for null */
  row_out = mysql_fetch_row(result);
  if(row_out==NULL)
  {
    mysql_free_result(result);
    dbDisconnect(connNum);
 
    return;
  }

  /* run number */ 
  if(row_out[0]==NULL)
  {
    *run=0;
  }
  else
  {
    *run=atoi(row_out[0]);
  }

  /* config */
#ifdef VXWORKS
  *config=mystrdup(row_out[1]);
#else
  *config=strdup(row_out[1]);
#endif
  mysql_free_result(result);








  /* get conffile */

  sprintf(query,"SELECT value FROM %s_option WHERE name='confFile'",(char *)(*config));
  if(mysql_query(connNum, query) != 0)
  {
    printf("get_run_config: ERROR in mysql_query 2\n");
    dbDisconnect(connNum);
    return;
  }
  if(!(result = mysql_store_result(connNum) ))
  {
    printf("get_run_config: ERROR in mysql_store_result 2\n");
    dbDisconnect(connNum);
    return;
  }
  row_out = mysql_fetch_row(result);
  if(row_out==NULL)
  {
    mysql_free_result(result);
    dbDisconnect(connNum); 
    return;
  }
#ifdef VXWORKS
  *conffile = mystrdup(row_out[0]);
#else
  *conffile = strdup(row_out[0]);
#endif
  mysql_free_result(result);







  /* get datafile */

  sprintf(query,"SELECT value FROM %s_option WHERE name='dataFile'",(char *)(*config));
  if(mysql_query(connNum, query) != 0)
  {
    printf("get_run_config: ERROR in mysql_query 3\n");
    dbDisconnect(connNum);
    return;
  }
  if(!(result = mysql_store_result(connNum) ))
  {
    printf("get_run_config: ERROR in mysql_store_result 3\n");
    dbDisconnect(connNum);
    return;
  }
  row_out = mysql_fetch_row(result);
  if(row_out==NULL)
  {
    mysql_free_result(result);
    dbDisconnect(connNum); 
    return;
  }
#ifdef VXWORKS
  *datafile = mystrdup(row_out[0]);
#else
  *datafile = strdup(row_out[0]);
#endif
  mysql_free_result(result);









  dbDisconnect(connNum);

  return;
}
Beispiel #29
0
int main(int argc, char** argv)
{

    /**
     * This test sets a session variable, creates tables in each of the shards
     * and inserts into them a single value while querying the session variable.
     * This will show if the value in the session variable in the shard is set and
     * if it is the same in all the shards.
     *
     * The test fails if any of the session variables is not set or differ from the original value.
     */
    
    const unsigned int ports[4] = {
        3000,
        3001,
        3002,
        3003
    };

    const char* srv_id[4] = {
        "3000",
        "3001",
        "3002",
        "3003"
    };

    const char* databases[4] = {
        "db0",
        "db1",
        "db2",
        "db3"
    };

	MYSQL* server;
    MYSQL_RES *result,*shdres;
    MYSQL_ROW row;
	char *host = NULL,*username = NULL, *password = NULL;
    char query[2048];
	unsigned int port,errnum,optval;
    unsigned long *lengths;
	int rval, i, j;

    if(argc < 5)
    {
        fprintf(stderr,"Usage: %s <host> <port> <username> <password>\n",argv[0]);
        return 1;
    }
    
	host = strdup(argv[1]);
	port = atoi(argv[2]);
	username = strdup(argv[3]);
    password = strdup(argv[4]);
	rval = 0;

    for(i = 0;i<4;i++)
    {

        if((server = mysql_init(NULL)) == NULL){
            fprintf(stderr,"Error : Initialization of MySQL client failed.\n");
            rval = 1;
            goto report;
        }
        optval = 1;
        mysql_options(server,MYSQL_OPT_CONNECT_TIMEOUT,&optval);

        if(mysql_real_connect(server,host,username,password,NULL,ports[i],NULL,0) == NULL){
            fprintf(stderr, "Failed to connect to server on port %d: %s\n",
                    ports[i],
                    mysql_error(server));
            rval = 1;
            goto report;
        }

        sprintf(query,"STOP SLAVE");
        if(mysql_real_query(server,query,strlen(query)))
        {
            fprintf(stderr, "Failed to stop slave in %d: %s.\n",
                    ports[i],
                    mysql_error(server));
        }


        for(j = 0;j<4;j++)
        {
            sprintf(query,"DROP DATABASE IF EXISTS %s",databases[j]);
            if(mysql_real_query(server,query,strlen(query)))
            {
                fprintf(stderr, "Failed to drop database in %d: %s.\n",
                        ports[i],
                        mysql_error(server));
            }
            
        }
        mysql_close(server);
    }

    for(i=0;i<4;i++)
    {
        if((server = mysql_init(NULL)) == NULL){
            fprintf(stderr,"Error : Initialization of MySQL client failed.\n");
            rval = 1;
            goto report;
        }
        
        mysql_options(server,MYSQL_OPT_CONNECT_TIMEOUT,&optval);
        
        if(mysql_real_connect(server,host,username,password,NULL,ports[i],NULL,0) == NULL){
            fprintf(stderr, "Failed to connect to server on port %d: %s\n",
                    ports[i],
                    mysql_error(server));
            rval = 1;
            goto report;
        }
        
        sprintf(query,"CREATE DATABASE %s",databases[i]);
        if(mysql_real_query(server,query,strlen(query)))
        {
            fprintf(stderr, "Failed to create database '%s' in %d: %s.\n",
                    databases[i],
                    ports[i],
                    mysql_error(server));
            rval = 1;
            goto report;
        }

        sprintf(query,"DROP TABLE IF EXISTS %s.t1",databases[i]);
        if(mysql_real_query(server,query,strlen(query)))
        {
            fprintf(stderr, "Failed to drop table '%s.t1' in %d: %s.\n",
                    databases[i],
                    ports[i],
                    mysql_error(server));
        }
        

        sprintf(query,"CREATE TABLE %s.t1 (id int)",databases[i]);
        if(mysql_real_query(server,query,strlen(query)))
        {
            fprintf(stderr, "Failed to create table '%s.t1' in %d: %s.\n",
                    databases[i],
                    ports[i],
                    mysql_error(server));
            rval = 1;
            goto report;
        }
        

        if(mysql_select_db(server,databases[i]))
        {
            fprintf(stderr, "Failed to use database %s in %d: %s.\n",
                    databases[i],
                    ports[i],
                    mysql_error(server));
            rval = 1;
            goto report;
        }

        sprintf(query,"INSERT INTO t1 values (%s)",srv_id[i]);
        if(mysql_real_query(server,query,strlen(query)))
        {
            fprintf(stderr, "Failed to insert values in %d: %s.\n",
                    ports[i],
                    mysql_error(server));
            rval = 1;
            goto report;
        }

        mysql_close(server);
    }

/** Test 1 - With default database  */

    printf("Testing with default database.\n");

    for(i = 0;i<4;i++)
    {

        printf("Testing database %s through MaxScale.\n",databases[i]);
        if((server = mysql_init(NULL)) == NULL){
            fprintf(stderr,"Error : Initialization of MySQL client failed.\n");
            rval = 1;
            goto report;
        }

        if(mysql_real_connect(server,host,username,password,databases[i],port,NULL,0) == NULL){
            fprintf(stderr, "Failed to connect to port %d using database %s: %s\n",
                    port,
                    databases[i],
                    mysql_error(server));
            rval = 1;
            goto report;
        }

        if(mysql_real_query(server,"SELECT id FROM t1",strlen("SELECT id FROM t1")))
        {
            fprintf(stderr, "Failed to execute query in %d: %s.\n",
                    ports[i],
                    mysql_error(server));
            rval = 1;
            goto report;
        }

        result = mysql_store_result(server);

        while((row = mysql_fetch_row(result)))
        {
            if(strcmp(row[0],srv_id[i]))
            {
                fprintf(stderr, "Test failed in %d: Was expecting %s but got %s instead.\n",
                        ports[i],srv_id[i],row[0]);
                rval = 1;
            
            }
        }

        mysql_free_result(result);
        
        mysql_close(server);

    }

    printf("Testing without default database and USE ... query.\n");

    for(i = 0;i<4;i++)
    {

        printf("Testing server on port %d through MaxScale.\n",ports[i]);
        if((server = mysql_init(NULL)) == NULL){
            fprintf(stderr,"Error : Initialization of MySQL client failed.\n");
            rval = 1;
            goto report;
        }

        if(mysql_real_connect(server,host,username,password,NULL,port,NULL,0) == NULL){
            fprintf(stderr, "Failed to connect to port %d using database %s: %s\n",
                    port,
                    databases[i],
                    mysql_error(server));
            rval = 1;
            goto report;
        }

        sprintf(query,"USE %s",databases[i]);
        if(mysql_select_db(server,databases[i]))
        {
            fprintf(stderr, "Failed to use database %s in %d: %s.\n",
                    databases[i],
                    ports[i],
                    mysql_error(server));
            rval = 1;
            goto report;
        }
    
        if(mysql_real_query(server,"SELECT id FROM t1",strlen("SELECT id FROM t1")))
        {
            fprintf(stderr, "Failed to execute query in %d: %s.\n",
                    ports[i],
                    mysql_error(server));
            rval = 1;
            goto report;
        }

        result = mysql_store_result(server);

        while((row = mysql_fetch_row(result)))
        {
            if(strcmp(row[0],srv_id[i]))
            {
                fprintf(stderr, "Test failed in %d: Was expecting %s but got %s instead.\n",
                        ports[i],srv_id[i],row[0]);
                rval = 1;
            
            }
        }

        mysql_free_result(result);
        
        mysql_close(server);
    }

/** Cleanup and START SLAVE */

    for(i = 0;i<4;i++)
    {
        
        if((server = mysql_init(NULL)) == NULL){
            fprintf(stderr,"Error : Initialization of MySQL client failed.\n");
            rval = 1;
            goto report;
        }

        if(mysql_real_connect(server,host,username,password,NULL,port,NULL,0) == NULL){
            fprintf(stderr, "Failed to connect to port %d using database %s: %s\n",
                    port,
                    databases[i],
                    mysql_error(server));
            rval = 1;
            goto report;
        }

        if(i > 0 && mysql_real_query(server,"START SLAVE",strlen("START SLAVE")))
        {
            fprintf(stderr, "Failed to start slave in %d: %s.\n",
                    ports[i],
                    mysql_error(server));
        }
        mysql_close(server);
    }

    report:

    if(rval){	
        printf("\nTest failed: Errors during test run.\n");
    }
    free(host);
    free(username);
    free(password);
    return rval;
}
Beispiel #30
0
OGRFeatureDefn *OGRMySQLTableLayer::ReadTableDefinition( const char *pszTable )

{
    MYSQL_RES    *hResult;
    CPLString     osCommand;

/* -------------------------------------------------------------------- */
/*      Fire off commands to get back the schema of the table.          */
/* -------------------------------------------------------------------- */
    osCommand.Printf("DESCRIBE `%s`", pszTable );
    pszGeomColumnTable = CPLStrdup(pszTable);
    if( mysql_query( poDS->GetConn(), osCommand ) )
    {
        poDS->ReportError( "DESCRIBE Failed" );
        return NULL;
    }

    hResult = mysql_store_result( poDS->GetConn() );
    if( hResult == NULL )
    {
        poDS->ReportError( "mysql_store_result() failed on DESCRIBE result." );
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Parse the returned table information.                           */
/* -------------------------------------------------------------------- */
    OGRFeatureDefn *poDefn = new OGRFeatureDefn( pszTable );
    char           **papszRow;
    OGRwkbGeometryType eForcedGeomType = wkbUnknown;
    int bGeomColumnNotNullable = FALSE;

    poDefn->Reference();

    while( (papszRow = mysql_fetch_row( hResult )) != NULL )
    {
        const char      *pszType;
        OGRFieldDefn    oField( papszRow[0], OFTString);
        int             nLenType;

        pszType = papszRow[1];

        if( pszType == NULL )
            continue;

        nLenType = (int)strlen(pszType);

        if( EQUAL(pszType,"varbinary")
            || (nLenType>=4 && EQUAL(pszType+nLenType-4,"blob")))
        {
            oField.SetType( OFTBinary );
        }
        else if( EQUAL(pszType,"varchar")
                 || (nLenType>=4 && EQUAL(pszType+nLenType-4,"enum"))
                 || (nLenType>=3 && EQUAL(pszType+nLenType-3,"set")) )
        {
            oField.SetType( OFTString );

        }
        else if( STARTS_WITH_CI(pszType, "char")  )
        {
            oField.SetType( OFTString );
            char ** papszTokens;

            papszTokens = CSLTokenizeString2(pszType,"(),",0);
            if (CSLCount(papszTokens) >= 2)
            {
                /* width is the second */
                oField.SetWidth(atoi(papszTokens[1]));
            }

            CSLDestroy( papszTokens );
            oField.SetType( OFTString );

        }

        if(nLenType>=4 && EQUAL(pszType+nLenType-4,"text"))
        {
            oField.SetType( OFTString );
        }
        else if( STARTS_WITH_CI(pszType,"varchar")  )
        {
            /*
               pszType is usually in the form "varchar(15)"
               so we'll split it up and get the width and precision
            */

            oField.SetType( OFTString );
            char ** papszTokens;

            papszTokens = CSLTokenizeString2(pszType,"(),",0);
            if (CSLCount(papszTokens) >= 2)
            {
                /* width is the second */
                oField.SetWidth(atoi(papszTokens[1]));
            }

            CSLDestroy( papszTokens );
            oField.SetType( OFTString );
        }
        else if( STARTS_WITH_CI(pszType, "int") )
        {
            oField.SetType( OFTInteger );
        }
        else if( STARTS_WITH_CI(pszType, "tinyint") )
        {
            oField.SetType( OFTInteger );
        }
        else if( STARTS_WITH_CI(pszType, "smallint") )
        {
            oField.SetType( OFTInteger );
        }
        else if( STARTS_WITH_CI(pszType, "mediumint") )
        {
            oField.SetType( OFTInteger );
        }
        else if( STARTS_WITH_CI(pszType, "bigint") )
        {
            oField.SetType( OFTInteger64 );
        }
        else if( STARTS_WITH_CI(pszType, "decimal") )
        {
            /*
               pszType is usually in the form "decimal(15,2)"
               so we'll split it up and get the width and precision
            */
            oField.SetType( OFTReal );
            char ** papszTokens;

            papszTokens = CSLTokenizeString2(pszType,"(),",0);
            if (CSLCount(papszTokens) >= 3)
            {
                /* width is the second and precision is the third */
                oField.SetWidth(atoi(papszTokens[1]));
                oField.SetPrecision(atoi(papszTokens[2]));
            }
            CSLDestroy( papszTokens );


        }
        else if( STARTS_WITH_CI(pszType, "float") )
        {
            oField.SetType( OFTReal );
        }
        else if( EQUAL(pszType,"double") )
        {
            oField.SetType( OFTReal );
        }
        else if( STARTS_WITH_CI(pszType, "double") )
        {
            // double can also be double(15,2)
            // so we'll handle this case here after
            // we check for just a regular double
            // without a width and precision specified

            char ** papszTokens=NULL;
            papszTokens = CSLTokenizeString2(pszType,"(),",0);
            if (CSLCount(papszTokens) >= 3)
            {
                /* width is the second and precision is the third */
                oField.SetWidth(atoi(papszTokens[1]));
                oField.SetPrecision(atoi(papszTokens[2]));
            }
            CSLDestroy( papszTokens );

            oField.SetType( OFTReal );
        }
        else if( EQUAL(pszType,"decimal") )
        {
            oField.SetType( OFTReal );
        }
        else if( EQUAL(pszType, "date") )
        {
            oField.SetType( OFTDate );
        }
        else if( EQUAL(pszType, "time") )
        {
            oField.SetType( OFTTime );
        }
        else if( EQUAL(pszType, "datetime")
                 || EQUAL(pszType, "timestamp") )
        {
            oField.SetType( OFTDateTime );
        }
        else if( EQUAL(pszType, "year") )
        {
            oField.SetType( OFTString );
            oField.SetWidth( 10 );
        }
        else if( EQUAL(pszType, "geometry") ||
                 OGRFromOGCGeomType(pszType) != wkbUnknown)
        {
            if (pszGeomColumn == NULL)
            {
                pszGeomColumn = CPLStrdup(papszRow[0]);
                eForcedGeomType = OGRFromOGCGeomType(pszType);
                bGeomColumnNotNullable = ( papszRow[2] != NULL && EQUAL(papszRow[2], "NO") );
            }
            else
            {
                CPLDebug("MYSQL",
                         "Ignoring %s as geometry column. Another one(%s) has already been found before",
                         papszRow[0], pszGeomColumn);
            }
            continue;
        }
        // Is this an integer primary key field?
        if( !bHasFid && papszRow[3] != NULL && EQUAL(papszRow[3],"PRI")
            && (oField.GetType() == OFTInteger || oField.GetType() == OFTInteger64) )
        {
            bHasFid = TRUE;
            pszFIDColumn = CPLStrdup(oField.GetNameRef());
            if( oField.GetType() == OFTInteger64 )
                SetMetadataItem(OLMD_FID64, "YES");
            continue;
        }

        // Is not nullable ?
        if( papszRow[2] != NULL && EQUAL(papszRow[2], "NO") )
            oField.SetNullable(FALSE);

        // Has default ?
        const char* pszDefault = papszRow[4];
        if( pszDefault != NULL )
        {
            if( !EQUAL(pszDefault, "NULL") &&
                !STARTS_WITH_CI(pszDefault, "CURRENT_") &&
                pszDefault[0] != '(' &&
                pszDefault[0] != '\'' &&
                CPLGetValueType(pszDefault) == CPL_VALUE_STRING )
            {
                int nYear, nMonth, nDay, nHour, nMinute;
                float fSecond;
                if( oField.GetType() == OFTDateTime &&
                    sscanf(pszDefault, "%d-%d-%d %d:%d:%f", &nYear, &nMonth, &nDay,
                                &nHour, &nMinute, &fSecond) == 6 )
                {
                    oField.SetDefault(CPLSPrintf("'%04d/%02d/%02d %02d:%02d:%02d'",
                                            nYear, nMonth, nDay, nHour, nMinute, (int)(fSecond+0.5)));
                }
                else
                {
                    CPLString osDefault("'");
                    char* pszTmp = CPLEscapeString(pszDefault, -1, CPLES_SQL);
                    osDefault += pszTmp;
                    CPLFree(pszTmp);
                    osDefault += "'";
                    oField.SetDefault(osDefault);
                }
            }
            else
            {
                oField.SetDefault(pszDefault);
            }
        }

        poDefn->AddFieldDefn( &oField );
    }

    // set to none for now... if we have a geometry column it will be set layer.
    poDefn->SetGeomType( wkbNone );

    if( hResult != NULL )
    {
        mysql_free_result( hResult );
        hResultSet = NULL;
    }

    if( bHasFid )
        CPLDebug( "MySQL", "table %s has FID column %s.",
                  pszTable, pszFIDColumn );
    else
        CPLDebug( "MySQL",
                  "table %s has no FID column, FIDs will not be reliable!",
                  pszTable );

    if (pszGeomColumn)
    {
        char*        pszType=NULL;

        // set to unknown first
        poDefn->SetGeomType( wkbUnknown );

        osCommand = "SELECT type, coord_dimension FROM geometry_columns WHERE f_table_name='";
        osCommand += pszTable;
        osCommand += "'";

        hResult = NULL;
        if( !mysql_query( poDS->GetConn(), osCommand ) )
            hResult = mysql_store_result( poDS->GetConn() );

        papszRow = NULL;
        if( hResult != NULL )
            papszRow = mysql_fetch_row( hResult );

        if( papszRow != NULL && papszRow[0] != NULL )
        {

            pszType = papszRow[0];

            OGRwkbGeometryType l_nGeomType = OGRFromOGCGeomType(pszType);

            if( papszRow[1] != NULL && atoi(papszRow[1]) == 3 )
                l_nGeomType = wkbSetZ(l_nGeomType);

            poDefn->SetGeomType( l_nGeomType );

        }
        else if (eForcedGeomType != wkbUnknown)
            poDefn->SetGeomType(eForcedGeomType);

        if( bGeomColumnNotNullable )
            poDefn->GetGeomFieldDefn(0)->SetNullable(FALSE);

        if( hResult != NULL )
            mysql_free_result( hResult );   //Free our query results for finding type.
			hResult = NULL;
    }

    // Fetch the SRID for this table now
    nSRSId = FetchSRSId();
    return poDefn;
}