MYSQL_STMT *_prepbind(struct subdbinfo *info,
		      struct stralloc *q,
		      unsigned int nparams,
		      struct stralloc *params)
{
  MYSQL_STMT *stmt;
  MYSQL_BIND bind[nparams];
  unsigned int i;

  if ((stmt = mysql_stmt_init((MYSQL*)info->conn)) == 0)
    die_sqlerror(info);
  if (mysql_stmt_prepare(stmt,q->s,q->len) != 0)
    die_sqlerror(info);
  byte_zero((char*)bind,sizeof bind);
  for (i = 0; i < nparams; ++i) {
    bind[i].buffer_type = MYSQL_TYPE_STRING;
    bind[i].buffer = params[i].s;
    bind[i].buffer_length = params[i].len;
  }
  if (mysql_stmt_bind_param(stmt,bind) != 0)
    die_sqlerror(info);
  return stmt;
}
bool SqlPreparedStatement::Prepare()
{
	auto sql = Sql();
	mSTMT = mysql_stmt_init(Sql());
	if (mSTMT == nullptr)
	{
		throw SqlException(sql, "Error in SqlPreparedStatement::mysql_stmt_init");
	}

	if (mysql_stmt_prepare(mSTMT, mStatement.c_str(), (ulong)mStatement.Length()) != 0)
	{
		SqlException e(mSTMT, "Error in SqlPreparedStatement::mysql_stmt_prepare");
		mysql_stmt_free_result(mSTMT);
		mysql_stmt_close(mSTMT);
		throw e;
	}

	mParamterCount = mysql_stmt_param_count(mSTMT);
	mResultCount = mysql_stmt_field_count(mSTMT);
	if (mResultCount!=0)
	{
		if ((mResultMetadata = mysql_stmt_result_metadata(mSTMT)) == NULL)
		{
			throw SqlException(mSTMT, "Error in SqlPreparedStatement::mysql_stmt_result_metadata");
		}

		MYSQL_FIELD* field = nullptr;
		while ((field = mysql_fetch_field(mResultMetadata)) != nullptr)
		{
			mResultFields.Add(field);
		}
	}

	
	
	return true;
}
Exemple #3
0
int gsc_mysql_stmt_prepare()
{
	int mysql_stmt;
	char *sql;
	int len;
	
	int helper = 0;
	helper += stackGetParamInt(1, &mysql_stmt);
	helper += stackGetParamString(2, &sql);
	helper += stackGetParamInt(3, &len);
	
	#if DEBUG_MYSQL
	printf_hide("gsc_mysql_stmt_prepare(mysql_stmt=%d, sql=%s)\n", mysql_stmt, sql);
	#endif
	
	if (helper != 3)
	{
		printf_hide("scriptengine> wrongs args for gsc_mysql_stmt_prepare(mysql_stmt);\n");
		return stackReturnInt(0);
	}

	int ret = mysql_stmt_prepare((MYSQL_STMT*)mysql_stmt, sql, len);
	return stackReturnInt(ret);
}
static MYSQL_STMT * prepare_and_execute_stmt_with_query(MYSQL *conn, char *query)
{
    MYSQL_STMT *stmt = mysql_stmt_init(conn);
    if (stmt == NULL) {
        rb_raise(rb_eRuntimeError, "Could not initialize prepared statement!");
    }

    int prepare_error = mysql_stmt_prepare(stmt, query, strlen(query));
    if (prepare_error) {
        rb_raise(rb_eRuntimeError, "Could not prepare statement! Error Code: %d", prepare_error);
    }

    long nr_params = mysql_stmt_param_count(stmt);
    if (nr_params) {
        rb_raise(rb_eRuntimeError, "Query contains %lu placeholders. 0 are allowed!", nr_params);
    }

    int exec_code = mysql_stmt_execute(stmt);
    if (exec_code) {
        rb_raise(rb_eRuntimeError, "Could not execute statement. MySQL error code: %d", exec_code);
    }

    return stmt;
}
Exemple #5
0
/*
 * success, err = stmt:prepare(query)
 */
static int
statement_prepare (lua_State * L) /* {{{ */
{
  statement_t *statement =
    (statement_t *) luaL_checkudata (L, 1, DBD_MYSQL_STATEMENT);
  const char *sql_query = luaL_checkstring (L, 2);
  unsigned long sql_len = strlen (sql_query);

  if (!statement->stmt)
    {
      luaL_error (L, DBI_ERR_INVALID_STATEMENT);
    }

  if (mysql_stmt_prepare (statement->stmt, sql_query, sql_len))
    {
      lua_pushnil (L);
      lua_pushfstring (L, DBI_ERR_PREP_STATEMENT,
		       mysql_stmt_error (statement->stmt));
      return 2;
    }

  lua_pushboolean (L, 1);
  return 1;
} /* }}} */
Exemple #6
0
/*
 * setup (initialize, prepare and bind) a prepared statement
 */
static int
netsnmp_mysql_bind(const char *text, size_t text_size, MYSQL_STMT **stmt,
                   MYSQL_BIND *bind)
{
    if ((NULL == text) || (NULL == stmt) || (NULL == bind)) {
        snmp_log(LOG_ERR,"invalid paramaters to netsnmp_mysql_bind()\n");
        return -1;
    }

    *stmt = mysql_stmt_init(_sql.conn);
    if (NULL == *stmt) {
        netsnmp_sql_error("could not initialize trap statement handler");
        return -1;
    }

    if (mysql_stmt_prepare(*stmt, text, text_size) != 0) {
        netsnmp_sql_stmt_error(*stmt, "Could not prepare INSERT");
        mysql_stmt_close(*stmt);
        *stmt = NULL;
        return -1;
    }

    return 0;
}
Exemple #7
0
void
handle_select_count(ETERM *msg)
{
  ETERM *query, *resp;
  MYSQL_STMT *handle;
  char *q;

  query = erl_element(2, msg);
  q = erl_iolist_to_string(query);
  erl_free_term(query);

  logmsg("INFO: Got select count for: %s", q);

  handle = mysql_stmt_init(&dbh);
  if (mysql_stmt_prepare(handle, q, strlen(q))) {
    resp = erl_format("{error, {mysql_error, ~i, ~s}}",
                      mysql_stmt_errno(handle), mysql_stmt_error(handle));
  } else if (mysql_stmt_execute(handle)) {
    resp = erl_format("{error, {mysql_error, ~i, ~s}}",
                      mysql_stmt_errno(handle), mysql_stmt_error(handle));
  } else {
    set_mysql_results(handle);
    if (results) {
      resp = erl_format("{ok, ~i}", mysql_stmt_affected_rows(handle));
    } else if (mysql_stmt_field_count(handle) == 0) {
      resp = erl_format("{ok, ~i}", mysql_stmt_affected_rows(handle));
    } else {
      resp = erl_format("{error, {mysql_error, ~i, ~s}}",
                        mysql_stmt_errno(handle), mysql_stmt_error(handle));
    }
  }
  erl_free(q);

  write_msg(resp);
  erl_free_term(resp);
}
Exemple #8
0
static int test_ps_client_errors(MYSQL *mysql)
{
  int rc;
  MYSQL_STMT *stmt;
  char *query= "DROP TABLE test_non_exists";

  rc= mysql_query(mysql, "DROP TABLE if exists test_non_exists");
  check_mysql_rc(rc, mysql);

  stmt= mysql_stmt_init(mysql);
  rc= mysql_stmt_prepare(stmt, query, strlen(query));
  FAIL_IF(rc, mysql_stmt_error(stmt));

  rc= mysql_stmt_execute(stmt);
  FAIL_IF(!rc, mysql_stmt_error(stmt));

  FAIL_IF(!mysql_stmt_errno(stmt), "Error expected");
  FAIL_IF(!strlen(mysql_stmt_error(stmt)), "Empty errormsg");
  FAIL_IF(strcmp(mysql_stmt_sqlstate(stmt), "00000") == 0, "Invalid SQLstate");

  mysql_stmt_close(stmt);

  return OK;
}
Exemple #9
0
int main (int argc, char *argv[]) {

    MYSQL mysql;
    MYSQL_RES *result;
    MYSQL_ROW row;
    my_bool reconnect = 0;
    mysql_init(&mysql);
    mysql_options(&mysql, MYSQL_OPT_RECONNECT, &reconnect);
 
    mysql_real_connect(&mysql, "127.0.0.1", "root", "root", "test", 3306, NULL, 0);

    MYSQL_STMT    *stmt;
    MYSQL_BIND    bind[3];
    my_ulonglong  affected_rows;
    int           param_count;
    short         small_data;
    int           int_data;
    char          str_data[STRING_SIZE];
    unsigned long str_length;
    my_bool       is_null;

    if (mysql_query(mysql, DROP_SAMPLE_TABLE))
    {
      fprintf(stderr, " DROP TABLE failed\n");
      fprintf(stderr, " %s\n", mysql_error(mysql));
      exit(0);
    }

    if (mysql_query(mysql, CREATE_SAMPLE_TABLE))
    {
      fprintf(stderr, " CREATE TABLE failed\n");
      fprintf(stderr, " %s\n", mysql_error(mysql));
      exit(0);
    }

    /* Prepare an INSERT query with 3 parameters */
    /* (the TIMESTAMP column is not named; the server */
    /*  sets it to the current date and time) */
    stmt = mysql_stmt_init(mysql);
    if (!stmt)
    {
      fprintf(stderr, " mysql_stmt_init(), out of memory\n");
      exit(0);
    }
    if (mysql_stmt_prepare(stmt, INSERT_SAMPLE, strlen(INSERT_SAMPLE)))
    {
      fprintf(stderr, " mysql_stmt_prepare(), INSERT failed\n");
      fprintf(stderr, " %s\n", mysql_stmt_error(stmt));
      exit(0);
    }
    fprintf(stdout, " prepare, INSERT successful\n");

    /* Get the parameter count from the statement */
    param_count= mysql_stmt_param_count(stmt);
    fprintf(stdout, " total parameters in INSERT: %d\n", param_count);

    if (param_count != 3) /* validate parameter count */
    {
      fprintf(stderr, " invalid parameter count returned by MySQL\n");
      exit(0);
    }

    /* Bind the data for all 3 parameters */

    memset(bind, 0, sizeof(bind));

    /* INTEGER PARAM */
    /* This is a number type, so there is no need to specify buffer_length */
    bind[0].buffer_type= MYSQL_TYPE_LONG;
    bind[0].buffer= (char *)&int_data;
    bind[0].is_null= 0;
    bind[0].length= 0;

    /* STRING PARAM */
    bind[1].buffer_type= MYSQL_TYPE_STRING;
    bind[1].buffer= (char *)str_data;
    bind[1].buffer_length= STRING_SIZE;
    bind[1].is_null= 0;
    bind[1].length= &str_length;

    /* SMALLINT PARAM */
    bind[2].buffer_type= MYSQL_TYPE_SHORT;
    bind[2].buffer= (char *)&small_data;
    bind[2].is_null= &is_null;
    bind[2].length= 0;

    /* Bind the buffers */
    if (mysql_stmt_bind_param(stmt, bind))
    {
      fprintf(stderr, " mysql_stmt_bind_param() failed\n");
      fprintf(stderr, " %s\n", mysql_stmt_error(stmt));
      exit(0);
    }

    /* Specify the data values for the first row */
    int_data= 10;             /* integer */
    strncpy(str_data, "MySQL", STRING_SIZE); /* string  */
    str_length= strlen(str_data);

    /* INSERT SMALLINT data as NULL */
    is_null= 1;

    /* Execute the INSERT statement - 1*/
    if (mysql_stmt_execute(stmt))
    {
      fprintf(stderr, " mysql_stmt_execute(), 1 failed\n");
      fprintf(stderr, " %s\n", mysql_stmt_error(stmt));
      exit(0);
    }

    /* Get the total number of affected rows */
    affected_rows= mysql_stmt_affected_rows(stmt);
    fprintf(stdout, " total affected rows(insert 1): %lu\n",
                    (unsigned long) affected_rows);

    if (affected_rows != 1) /* validate affected rows */
    {
      fprintf(stderr, " invalid affected rows by MySQL\n");
      exit(0);
    }

    /* Specify data values for second row, then re-execute the statement */
    int_data= 1000;
    strncpy(str_data, "The most popular Open Source database", STRING_SIZE);
    str_length= strlen(str_data);
    small_data= 1000;         /* smallint */
    is_null= 0;               /* reset */

    /* Execute the INSERT statement - 2*/
    if (mysql_stmt_execute(stmt))
    {
      fprintf(stderr, " mysql_stmt_execute, 2 failed\n");
      fprintf(stderr, " %s\n", mysql_stmt_error(stmt));
      exit(0);
    }

    /* Get the total rows affected */
    affected_rows= mysql_stmt_affected_rows(stmt);
    fprintf(stdout, " total affected rows(insert 2): %lu\n",
                    (unsigned long) affected_rows);

    if (affected_rows != 1) /* validate affected rows */
    {
      fprintf(stderr, " invalid affected rows by MySQL\n");
      exit(0);
    }

    /* Close the statement */
    if (mysql_stmt_close(stmt))
    {
      fprintf(stderr, " failed while closing the statement\n");
      fprintf(stderr, " %s\n", mysql_stmt_error(stmt));
      exit(0);
    }
}
Exemple #10
0
static int test_view_insert_fields(MYSQL *mysql)
{
  MYSQL_STMT    *stmt;
  char          parm[11][1000];
  ulong         l[11];
  int           rc, i;
  int           rowcount= 0;
  MYSQL_BIND    my_bind[11];
  const char    *query= "INSERT INTO `v1` ( `K1C4` ,`K2C4` ,`K3C4` ,`K4N4` ,`F1C4` ,`F2I4` ,`F3N5` ,`F7F8` ,`F6N4` ,`F5C8` ,`F9D8` ) VALUES( ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? )";

  rc= mysql_query(mysql, "DROP TABLE IF EXISTS t1, v1");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql, "DROP VIEW IF EXISTS t1, v1");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql,
                  "CREATE TABLE t1 (K1C4 varchar(4) NOT NULL,"
                  "K2C4 varchar(4) NOT NULL, K3C4 varchar(4) NOT NULL,"
                  "K4N4 varchar(4) NOT NULL default '0000',"
                  "F1C4 varchar(4) NOT NULL, F2I4 int(11) NOT NULL,"
                  "F3N5 varchar(5) NOT NULL default '00000',"
                  "F4I4 int(11) NOT NULL default '0', F5C8 varchar(8) NOT NULL,"
                  "F6N4 varchar(4) NOT NULL default '0000',"
                  "F7F8 double NOT NULL default '0',"
                  "F8F8 double NOT NULL default '0',"
                  "F9D8 decimal(8,2) NOT NULL default '0.00',"
                  "PRIMARY KEY (K1C4,K2C4,K3C4,K4N4)) "
                  "CHARSET=latin1 COLLATE latin1_bin");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql,
                  "CREATE VIEW v1 AS select sql_no_cache "
                  " K1C4 AS K1C4, K2C4 AS K2C4, K3C4 AS K3C4, K4N4 AS K4N4, "
                  " F1C4 AS F1C4, F2I4 AS F2I4, F3N5 AS F3N5,"
                  " F7F8 AS F7F8, F6N4 AS F6N4, F5C8 AS F5C8, F9D8 AS F9D8"
                  " from t1 T0001");

  memset(my_bind, '\0', sizeof(my_bind));
  for (i= 0; i < 11; i++)
  {
    l[i]= 20;
    my_bind[i].buffer_type= MYSQL_TYPE_STRING;
    my_bind[i].is_null= 0;
    my_bind[i].buffer= (char *)&parm[i];

    strcpy(parm[i], "1");
    my_bind[i].buffer_length= 2;
    my_bind[i].length= &l[i];
  }
  stmt= mysql_stmt_init(mysql);
  rc= mysql_stmt_prepare(stmt, query, strlen(query));
  check_stmt_rc(rc, stmt);
  rc= mysql_stmt_bind_param(stmt, my_bind);
  check_stmt_rc(rc, stmt);

  rc= mysql_stmt_execute(stmt);
  check_stmt_rc(rc, stmt);
  mysql_stmt_close(stmt);

  query= "select * from t1";
  stmt= mysql_stmt_init(mysql);
  rc= mysql_stmt_prepare(stmt, query, strlen(query));
  check_stmt_rc(rc, stmt);
  rc= mysql_stmt_execute(stmt);
  check_stmt_rc(rc, stmt);
  while (mysql_stmt_fetch(stmt) != MYSQL_NO_DATA)
    rowcount++;
  FAIL_UNLESS(1 == rowcount, "Expected 1 row");

  mysql_stmt_close(stmt);
  rc= mysql_query(mysql, "DROP VIEW v1");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql, "DROP TABLE t1");
  check_mysql_rc(rc, mysql);

  return OK;
}
Exemple #11
0
static DWORD GroupSyncIncrChanges(DB_CONTEXT *db, SYNC_CONTEXT *sync)
{
    CHAR        *query;
    BYTE        syncEvent;
    CHAR        syncInfo[255];
    CHAR        groupName[_MAX_NAME + 1];
    DWORD       error;
    GROUPFILE   groupFile;
    INT         result;
    MYSQL_BIND  bindInput[2];
    MYSQL_BIND  bindOutput[3];
    MYSQL_RES   *metadata;
    MYSQL_STMT  *stmt;

    ASSERT(db != NULL);
    ASSERT(sync != NULL);

    //
    // Prepare statement and bind parameters
    //

    stmt = db->stmt[7];

    query = "SELECT name, type, info FROM io_group_changes"
            "  WHERE time BETWEEN ? AND ?"
            "  ORDER BY id ASC";

    result = mysql_stmt_prepare(stmt, query, strlen(query));
    if (result != 0) {
        TRACE("Unable to prepare statement: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    DB_CHECK_PARAMS(bindInput, stmt);
    ZeroMemory(&bindInput, sizeof(bindInput));

    bindInput[0].buffer_type = MYSQL_TYPE_LONG;
    bindInput[0].buffer      = &sync->prevUpdate;
    bindInput[0].is_unsigned = TRUE;

    bindInput[1].buffer_type = MYSQL_TYPE_LONG;
    bindInput[1].buffer      = &sync->currUpdate;
    bindInput[1].is_unsigned = TRUE;

    result = mysql_stmt_bind_param(stmt, bindInput);
    if (result != 0) {
        TRACE("Unable to bind parameters: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    metadata = mysql_stmt_result_metadata(stmt);
    if (metadata == NULL) {
        TRACE("Unable to prepare statement: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    //
    // Execute prepared statement
    //

    result = mysql_stmt_execute(stmt);
    if (result != 0) {
        LOG_ERROR("Unable to execute statement: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    //
    // Bind and fetch results
    //

    DB_CHECK_RESULTS(bindOutput, metadata);
    ZeroMemory(&bindOutput, sizeof(bindOutput));

    bindOutput[0].buffer_type   = MYSQL_TYPE_STRING;
    bindOutput[0].buffer        = groupName;
    bindOutput[0].buffer_length = sizeof(groupName);

    bindOutput[1].buffer_type   = MYSQL_TYPE_TINY;
    bindOutput[1].buffer        = &syncEvent;
    bindOutput[1].is_unsigned   = TRUE;

    bindOutput[2].buffer_type   = MYSQL_TYPE_STRING;
    bindOutput[2].buffer        = syncInfo;
    bindOutput[2].buffer_length = sizeof(syncInfo);

    result = mysql_stmt_bind_result(stmt, bindOutput);
    if (result != 0) {
        TRACE("Unable to bind results: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    result = mysql_stmt_store_result(stmt);
    if (result != 0) {
        TRACE("Unable to buffer results: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    //
    // Process result set
    //

    for (;;) {
        if (mysql_stmt_fetch(stmt) != 0) {
            break;
        }

        switch ((SYNC_EVENT)syncEvent) {
            case SYNC_EVENT_CREATE:
                TRACE("GroupSyncIncr: Create(%s)", groupName);

                // Read group file from database
                ZeroMemory(&groupFile, sizeof(GROUPFILE));
                error = DbGroupRead(db, groupName, &groupFile);
                if (error != ERROR_SUCCESS) {
                    LOG_WARN("Unable to read group \"%s\" (error %lu).", groupName, error);
                } else {

                    // Create local user
                    error = GroupEventCreate(groupName, &groupFile);
                    if (error != ERROR_SUCCESS) {
                        LOG_WARN("Unable to create group \"%s\" (error %lu).", groupName, error);
                    }
                }
                break;

            case SYNC_EVENT_RENAME:
                TRACE("GroupSyncIncr: Rename(%s,%s)", groupName, syncInfo);

                error = GroupEventRename(groupName, syncInfo);
                if (error != ERROR_SUCCESS) {
                    LOG_WARN("Unable to rename group \"%s\" to \"%s\" (error %lu).", groupName, syncInfo, error);
                }
                break;

            case SYNC_EVENT_DELETE:
                TRACE("GroupSyncIncr: Delete(%s)", groupName);

                error = GroupEventDelete(groupName);
                if (error != ERROR_SUCCESS) {
                    LOG_WARN("Unable to delete group \"%s\" (error %lu).", groupName, error);
                }
                break;

            default:
                LOG_ERROR("Unknown sync event %d.", syncEvent);
                break;
        }
    }

    mysql_free_result(metadata);

    return ERROR_SUCCESS;
}
Exemple #12
0
int main(int argc, char **argv)
{
	MYSQL_STMT *stmt;
	  MYSQL_BIND param[4];
	  char *sql = "insert into Measurements VALUES(?,?,?,?)";

	  int value, value_type, time_ms, sensor_id;
	  size_t data_length = sizeof(value);
	  int affected_rows;
	  
  MYSQL *con = mysql_init(NULL);
  
  if (con == NULL) 
  {
      fprintf(stderr, "%s\n", mysql_error(con));
      exit(1);
  }  

  if (mysql_real_connect(con, "localhost", "till", NULL, 
          "till", 0, NULL, 0) == NULL) 
  {
      finish_with_error(con);
  }    
  
  if (mysql_query(con, "DROP TABLE IF EXISTS Measurements")) {
      finish_with_error(con);
  }
  
  if (mysql_query(con, "CREATE TABLE Measurements(value INT, time INT, valuetype INT, sensor_id INT) engine=myisam")) {      
      finish_with_error(con);
  }
  
  if (mysql_query(con, "INSERT INTO Measurements VALUES(1,1,1,1)")) {
      finish_with_error(con);
  }
  
  stmt = mysql_stmt_init(con);
  
    if (!stmt) {
      fprintf(stderr, " mysql_stmt_init(), out of memory\n");
      exit(EXIT_FAILURE);
    }

    if (mysql_stmt_prepare(stmt, sql, strlen(sql))) {
      fprintf(stderr, " mysql_stmt_prepare(), INSERT failed\n");
      fprintf(stderr, " %s\n", mysql_stmt_error(stmt));
      exit(EXIT_FAILURE);
    }
    
    memset(param, 0, sizeof(param));
    param[0].buffer_type = MYSQL_TYPE_LONG;
    param[0].buffer = (char *)&value;
    param[0].buffer_length = sizeof(value);
    param[0].is_null = 0;
    param[0].length = &data_length;
	
    param[1].buffer_type = MYSQL_TYPE_LONG;
    param[1].buffer = (char *)&value_type;
    param[1].buffer_length = sizeof(value);
    param[1].is_null = 0;
    param[1].length = &data_length;
	
    param[2].buffer_type = MYSQL_TYPE_LONG;
    param[2].buffer = (char *)&time_ms;
    param[2].buffer_length = sizeof(value);
    param[2].is_null = 0;
    param[2].length = &data_length;
	
    param[3].buffer_type = MYSQL_TYPE_LONG;
    param[3].buffer = (char *)&sensor_id;
    param[3].buffer_length = sizeof(value);
    param[3].is_null = 0;
    param[3].length = &data_length;

	if (mysql_stmt_bind_param(stmt, param)) {
	    fprintf(stderr, " mysql_stmt_bind_param() failed\n");
	    fprintf(stderr, " %s\n", mysql_stmt_error(stmt));
	    exit(EXIT_FAILURE);
	}	
	
	int iValues = 10000;
	int iSensors = 10;
	int i,j;
	intmax_t t;
	
	//printf("%ld\n", get_current_time_in_ms());
  	for(i=0;i<iValues;i++) {
  		t = get_current_time_in_ms();
		for(j=0;j<iSensors;j++) {
			value = i+j;
			value_type = VALUE_TYPE_TEMP_CENTIGRADE;
			time_ms = t;
			sensor_id = j;
			if (mysql_stmt_execute(stmt))
			{
				fprintf(stderr, " mysql_stmt_execute(), 1 failed\n");
				fprintf(stderr, " %s\n", mysql_stmt_error(stmt));
				exit(EXIT_FAILURE);
			}
		}
  	}
	
 
  mysql_close(con);
  exit(0);
}
Exemple #13
0
void DBManager::update_completed_type134(const int& job_id, const std::string& result, const int& type) {
	char *stmt_str;
	if (type == 1)
		stmt_str = "UPDATE wkdd_ldp_jobs SET top_cui = ?, status = 'complete', end_time = ? WHERE id = ?";
	else if (type == 3)
		stmt_str = "UPDATE wkdd_ldp_jobs SET start_cui_option = ?, status = 'complete', end_time = ? WHERE id = ?";
	else if (type == 4)
		stmt_str = "UPDATE wkdd_ldp_jobs SET end_cui_option = ?, status = 'complete', end_time = ? WHERE id = ?";
		
	MYSQL_BIND param[3];
	int my_job_id;
	char my_cui[result.length()];
	unsigned long my_cui_length;
	MYSQL_TIME my_datetime;
	time_t clock;
	struct tm *cur_time;
	
	if (mysql_stmt_prepare(m_stmt, stmt_str, strlen(stmt_str)) != 0) {
		print_stmt_error("could not prepare update statement");
		return;
	}
	
	// zero the parameter structures, and then perform all parameter initialization that is constant and does not change for each row
	memset((void *)param, 0, sizeof(param));
	
	// set up my_cui parameter
	param[0].buffer_type = MYSQL_TYPE_STRING;
	param[0].buffer = (void *) &my_cui;
	param[0].buffer_length = sizeof(my_cui);
	param[0].length = &my_cui_length;
	param[0].is_null = 0;
	
	// set up my_datetime
	param[1].buffer_type = MYSQL_TYPE_DATETIME;
	param[1].buffer = (void *) &my_datetime;
	param[1].is_null = 0;
	
	// set up my_id parameter
	param[2].buffer_type = MYSQL_TYPE_LONG;
	param[2].buffer = (void *) &my_job_id;
	param[2].is_unsigned = 0;
	param[2].is_null = 0;
	
	if (mysql_stmt_bind_param(m_stmt, param) != 0) {
		print_stmt_error("could not bind parameters for update");
		return;
	}
	
	// get current time
	(void)time (&clock);
	
	// set variables
	my_job_id = job_id;
	(void) strcpy(my_cui, result.c_str());
	my_cui_length = strlen(my_cui);
	cur_time = localtime(&clock);
	my_datetime.year = cur_time->tm_year + 1900;
	my_datetime.month = cur_time->tm_mon + 1;
	my_datetime.day = cur_time->tm_mday;
	my_datetime.hour = cur_time->tm_hour;
	my_datetime.minute = cur_time->tm_min;
	my_datetime.second = cur_time->tm_sec;
	my_datetime.second_part = 0;
	my_datetime.neg = 0;
	
	if (mysql_stmt_execute(m_stmt) != 0) {
		print_stmt_error("could not execute statement");
		return;
	}
}
unsigned int GetMultiStatements(MADB_Stmt *Stmt, char *StmtStr, size_t Length)
{
  char *p, *last, *prev= NULL;
  unsigned int statements= 1;
  int quote[2]= {0,0}, comment= 0;
  char *end;
  MYSQL_STMT *stmt;
  p= last= StmtStr;

  stmt= mysql_stmt_init(Stmt->Connection->mariadb);

  /* if the entire stmt string passes, we don't have multistatement */
  if (stmt && !mysql_stmt_prepare(stmt, StmtStr, Length))
  {
    mysql_stmt_close(stmt);
    return 1;
  }
  mysql_stmt_close(stmt);
  /* make sure we don't have trailing whitespace or semicolon */
  if (Length)
  {
    end= StmtStr + Length - 1;
    while (end > StmtStr && (isspace(*end) || *end == ';'))
      end--;
    Length= end - StmtStr;
  }

  while (p < StmtStr + Length)
  {
    switch (*p) {
    case ';':
      if (!quote[0] && !quote[1] && !comment)
      {
        statements++;
        last= p + 1;
        *p= 0;
      }
      break;
    case '/':
      if (!comment && (p < StmtStr + Length + 1) && (char)*(p+1) ==  '*')
        comment= 1;
      else if (comment && (p > StmtStr) && (char)*(p-1) == '*')
        comment= 0;
      break;
    case '\"':
      if (prev && *prev != '\\')
        quote[0] = !quote[0];
      break;
    case 39:
      if (prev && *prev != '\\')
        quote[1] = !quote[1];
      break;
    default:
      break;
    }
    prev= p;
    p++;
  }

  if (statements > 1)
  {
    int i=0;
    unsigned int MaxParams= 0;

    p= StmtStr;
    Stmt->MultiStmtCount= 0;
    Stmt->MultiStmtNr= 0;
    Stmt->MultiStmts= (MYSQL_STMT **)MADB_CALLOC(sizeof(MYSQL_STMT) * statements);

    while (p < StmtStr + Length)
    {
      Stmt->MultiStmts[i]= mysql_stmt_init(Stmt->Connection->mariadb);
      if (mysql_stmt_prepare(Stmt->MultiStmts[i], p, strlen(p)))
      {
        MADB_SetNativeError(&Stmt->Error, SQL_HANDLE_STMT, Stmt->MultiStmts[i]);
        CloseMultiStatements(Stmt);
        return 0;
      }
      if (mysql_stmt_param_count(Stmt->MultiStmts[i]) > MaxParams)
        MaxParams= mysql_stmt_param_count(Stmt->MultiStmts[i]);
      p+= strlen(p) + 1;
      ++i;
      ++Stmt->MultiStmtCount;
    }
    if (MaxParams)
      Stmt->params= (MYSQL_BIND *)MADB_CALLOC(sizeof(MYSQL_BIND) * MaxParams);
  }

  return statements;
}
Exemple #15
0
static DWORD UserSyncFull(DB_CONTEXT *db)
{
    BOOL        removed;
    CHAR        *query;
    CHAR        userName[_MAX_NAME + 1];
    DWORD       error;
    DWORD       i;
    USERFILE    userFile;
    INT         result;
    NAME_ENTRY  *entry;
    NAME_LIST   list;
    MYSQL_BIND  bind[17];
    MYSQL_RES   *metadata;
    MYSQL_STMT  *stmt;

    ASSERT(db != NULL);
    TRACE("db=%p", db);

    //
    // Build list of user IDs
    //

    error = NameListCreateUsers(&list);
    if (error != ERROR_SUCCESS) {
        LOG_ERROR("Unable to create user ID list (error %lu).", error);
        return error;
    }

    //
    // Prepare and execute statement
    //

    stmt = db->stmt[7];

    query = "SELECT name,description,flags,home,limits,password,vfsfile,credits,"
            "       ratio,alldn,allup,daydn,dayup,monthdn,monthup,wkdn,wkup"
            "  FROM io_user";

    result = mysql_stmt_prepare(stmt, query, strlen(query));
    if (result != 0) {
        LOG_WARN("Unable to prepare statement: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    metadata = mysql_stmt_result_metadata(stmt);
    if (metadata == NULL) {
        LOG_WARN("Unable to retrieve result metadata: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    result = mysql_stmt_execute(stmt);
    if (result != 0) {
        LOG_ERROR("Unable to execute statement: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    //
    // Bind and fetch results
    //

    DB_CHECK_RESULTS(bind, metadata);
    ZeroMemory(&bind, sizeof(bind));

    bind[0].buffer_type   = MYSQL_TYPE_STRING;
    bind[0].buffer        = userName;
    bind[0].buffer_length = sizeof(userName);

    bind[1].buffer_type   = MYSQL_TYPE_STRING;
    bind[1].buffer        = userFile.Tagline;
    bind[1].buffer_length = sizeof(userFile.Tagline);

    bind[2].buffer_type   = MYSQL_TYPE_STRING;
    bind[2].buffer        = userFile.Flags;
    bind[2].buffer_length = sizeof(userFile.Flags);

    bind[3].buffer_type   = MYSQL_TYPE_STRING;
    bind[3].buffer        = userFile.Home;
    bind[3].buffer_length = sizeof(userFile.Home);

    bind[4].buffer_type   = MYSQL_TYPE_BLOB;
    bind[4].buffer        = &userFile.Limits;
    bind[4].buffer_length = sizeof(userFile.Limits);

    bind[5].buffer_type   = MYSQL_TYPE_BLOB;
    bind[5].buffer        = &userFile.Password;
    bind[5].buffer_length = sizeof(userFile.Password);

    bind[6].buffer_type   = MYSQL_TYPE_STRING;
    bind[6].buffer        = userFile.MountFile;
    bind[6].buffer_length = sizeof(userFile.MountFile);

    bind[7].buffer_type   = MYSQL_TYPE_BLOB;
    bind[7].buffer        = &userFile.Ratio;
    bind[7].buffer_length = sizeof(userFile.Ratio);

    bind[8].buffer_type   = MYSQL_TYPE_BLOB;
    bind[8].buffer        = &userFile.Credits;
    bind[8].buffer_length = sizeof(userFile.Credits);

    bind[9].buffer_type   = MYSQL_TYPE_BLOB;
    bind[9].buffer        = &userFile.DayUp;
    bind[9].buffer_length = sizeof(userFile.DayUp);

    bind[10].buffer_type   = MYSQL_TYPE_BLOB;
    bind[10].buffer        = &userFile.DayDn;
    bind[10].buffer_length = sizeof(userFile.DayDn);

    bind[11].buffer_type   = MYSQL_TYPE_BLOB;
    bind[11].buffer        = &userFile.WkUp;
    bind[11].buffer_length = sizeof(userFile.WkUp);

    bind[12].buffer_type   = MYSQL_TYPE_BLOB;
    bind[12].buffer        = &userFile.WkDn;
    bind[12].buffer_length = sizeof(userFile.WkDn);

    bind[13].buffer_type   = MYSQL_TYPE_BLOB;
    bind[13].buffer        = &userFile.MonthUp;
    bind[13].buffer_length = sizeof(userFile.MonthUp);

    bind[14].buffer_type   = MYSQL_TYPE_BLOB;
    bind[14].buffer        = &userFile.MonthDn;
    bind[14].buffer_length = sizeof(userFile.MonthDn);

    bind[15].buffer_type   = MYSQL_TYPE_BLOB;
    bind[15].buffer        = &userFile.AllUp;
    bind[15].buffer_length = sizeof(userFile.AllUp);

    bind[16].buffer_type   = MYSQL_TYPE_BLOB;
    bind[16].buffer        = &userFile.AllDn;
    bind[16].buffer_length = sizeof(userFile.AllDn);

    result = mysql_stmt_bind_result(stmt, bind);
    if (result != 0) {
        LOG_WARN("Unable to bind results: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    result = mysql_stmt_store_result(stmt);
    if (result != 0) {
        LOG_WARN("Unable to buffer results: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    //
    // Process result set
    //

    for (;;) {
        ZeroMemory(&userFile, sizeof(USERFILE));
        if (mysql_stmt_fetch(stmt) != 0) {
            break;
        }

        // Remove user from the list beforehand in case DbUserReadExtra() fails
        removed = NameListRemove(&list, userName);

        // Read the user's admin-groups, groups, and hosts
        error = DbUserReadExtra(db, userName, &userFile);
        if (error != ERROR_SUCCESS) {
            LOG_WARN("Unable to read user \"%s\" (error %lu).", userName, error);
            continue;
        }

        //
        // If ioFTPD fails to open a user at start-up, the user will still
        // have an entry in the UserIdTable file but ioFTPD considers them
        // gone. The call to UserExists() is done to check for this.
        //
        if (!removed || !UserExists(userName)) {
            TRACE("UserSyncFull: Create(%s)", userName);

            // User does not exist locally, create it.
            error = UserEventCreate(userName, &userFile);
            if (error != ERROR_SUCCESS) {
                LOG_WARN("Unable to create user \"%s\" (error %lu).", userName, error);
            }
        } else {
            TRACE("UserSyncFull: Update(%s)", userName);

            // User already exists locally, update it.
            error = UserEventUpdate(userName, &userFile);
            if (error != ERROR_SUCCESS) {
                LOG_WARN("Unable to update user \"%s\" (error %lu).", userName, error);
            }
        }
    }

    mysql_free_result(metadata);

    //
    // Delete remaining users
    //

    for (i = 0; i < list.count; i++) {
        entry = list.array[i];
        TRACE("UserSyncFull: Delete(%s,%d)", entry->name, entry->id);

        // User does not exist on database, delete it.
        error = UserEventDeleteEx(entry->name, entry->id);
        if (error != ERROR_SUCCESS) {
            LOG_WARN("Unable to delete user \"%s\" (error %lu).", entry->name, error);
        }
    }

    NameListDestroy(&list);

    return ERROR_SUCCESS;
}
Exemple #16
0
void fun()
{
    const uint32_t STRING_SIZE = 50;
    const std::string SELECT_SAMPLE = "SELECT fid, fipbegin, fipend, flocation FROM tiptable";

    MYSQL_BIND bind[4];
    MYSQL_RES *prepare_meta_result;

    MYSQL_TIME ts;
    (void)ts;
    int param_count;

    MYSQL* mysql = init();
    if (!mysql) {
        printf("error\n");
        return;
    }

    /* Prepare a SELECT query to fetch data from test_table */
    MYSQL_STMT* stmt = mysql_stmt_init(mysql);
    if (!stmt) {
        fprintf(stderr, " mysql_stmt_init(), out of memory\n");
        exit(0);
    }
    if (mysql_stmt_prepare(stmt, SELECT_SAMPLE.c_str(), SELECT_SAMPLE.size())) {
        fprintf(stderr, " mysql_stmt_prepare(), SELECT failed\n");
        fprintf(stderr, " %s\n", mysql_stmt_error(stmt));
        exit(0);
    }

    fprintf(stdout, " prepare, SELECT successful\n");

    /* Get the parameter count from the statement */
    param_count = (int)mysql_stmt_param_count(stmt);

    fprintf(stdout, " total parameters in SELECT: %d\n", param_count);
    if (param_count != 0) {
        fprintf(stderr, " invalid parameter count returned by MySQL\n");
        exit(0);
    }

    /* Fetch result set meta information */
    prepare_meta_result = mysql_stmt_result_metadata(stmt);
    if (!prepare_meta_result) {
        fprintf(stderr, " mysql_stmt_result_metadata(),  returned no meta information\n");
        fprintf(stderr, " %s\n", mysql_stmt_error(stmt));
        exit(0);
    }

    /* Get total columns in the query */
    int column_count = mysql_num_fields(prepare_meta_result);
    fprintf(stdout, " total columns in SELECT statement: %d\n", column_count);
    if (column_count != 4) {
        fprintf(stderr, " invalid column count returned by MySQL\n");
        exit(0);
    }

    /* Execute the SELECT query */
    if (mysql_stmt_execute(stmt)) {
        fprintf(stderr, " mysql_stmt_execute(), failed\n");
        fprintf(stderr, " %s\n", mysql_stmt_error(stmt));
        exit(0);
    }
    /* Bind the result buffers for all 4 columns before fetching them */

    unsigned long length[4];
    my_bool is_null[4];
    my_bool error[4];
    short small_data;
    (void)small_data;
    int int_data[4];
    char str_data[4][STRING_SIZE];

    std::memset(bind, 0, sizeof(bind));
    /* INTEGER COLUMN */
    bind[0].buffer_type = MYSQL_TYPE_LONG;
    bind[0].buffer = (char *)&int_data[0];
    bind[0].is_null = &is_null[0];
    bind[0].length = &length[0];
    bind[0].error = &error[0];

    bind[1].buffer_type = MYSQL_TYPE_LONG;
    bind[1].buffer = (char *)&int_data[1];
    bind[1].is_null = &is_null[1];
    bind[1].length = &length[1];
    bind[1].error = &error[1];

    bind[2].buffer_type = MYSQL_TYPE_LONG;
    bind[2].buffer = (char *)&int_data[2];
    bind[2].is_null = &is_null[2];
    bind[2].length = &length[2];
    bind[2].error = &error[2];

    bind[3].buffer_type = MYSQL_TYPE_STRING;
    bind[3].buffer = (char *)&str_data[3];
    bind[3].buffer_length = STRING_SIZE;
    bind[3].is_null = &is_null[3];
    bind[3].length = &length[3];
    bind[3].error = &error[3];


    /* TIMESTAMP COLUMN */
    /*
    bind[3].buffer_type = MYSQL_TYPE_TIMESTAMP;
    bind[3].buffer = (char *)&ts;
    bind[3].is_null = &is_null[3];
    bind[3].length = &length[3];
    bind[3].error = &error[3];
    */

    /* Bind the result buffers */
    if (mysql_stmt_bind_result(stmt, bind)) {
        fprintf(stderr, " mysql_stmt_bind_result() failed\n");
        fprintf(stderr, " %s\n", mysql_stmt_error(stmt));
        exit(0);
    }

    /* Now buffer all results to client (optional step) */

    auto tbegin = std::chrono::system_clock::now();
    if (mysql_stmt_store_result(stmt)) {
        fprintf(stderr, " mysql_stmt_store_result() failed\n");
        fprintf(stderr, " %s\n", mysql_stmt_error(stmt));
        exit(0);
    }
    auto tend = std::chrono::system_clock::now();
    fprintf(stderr, "mysql_stmt_store_result use %d\n", (int)std::chrono::duration_cast<std::chrono::seconds>(tend-tbegin).count());

    fprintf(stderr, "total rows:%d\n",(int)::mysql_stmt_num_rows(stmt));

    /* Fetch all rows */
    int row_count = 0;
    fprintf(stdout, "Fetching results ...\n");
    while (!mysql_stmt_fetch(stmt)) {
        row_count++;
        fprintf(stdout, " row %d\n", row_count);

        /* column 1 */
        fprintf(stdout, " column1: ");
        if (is_null[0])
            fprintf(stdout, " NULL\t");
        else
            fprintf(stdout, " %d(%ld)\t", int_data[0], length[0]);

        /* column 2 */
        fprintf(stdout, " column2: ");
        if (is_null[1])
            fprintf(stdout, " NULL\t");
        else
            fprintf(stdout, " %d(%ld)\t", int_data[1], length[1]);

        /* column 3 */
        fprintf(stdout, " column3: ");
        if (is_null[2])
            fprintf(stdout, " NULL\t");
        else
            fprintf(stdout, " %d(%ld)\t", int_data[2], length[2]);

        fprintf(stdout, " column4: ");
        if (is_null[3])
            fprintf(stdout, " NULL\t");
        else
            fprintf(stdout, " %s(%ld)\t", str_data[3], length[3]);

        /* column 4 */
        /*
        fprintf(stdout, " column4 (timestamp): ");
        if (is_null[3])
            fprintf(stdout, " NULL\n");
        else
            fprintf(stdout, " %04d-%02d-%02d %02d:%02d:%02d (%ld)\n",
                ts.year, ts.month, ts.day,
                ts.hour, ts.minute, ts.second,
                length[3]);
                */
        fprintf(stdout, "\n");
        if (row_count > 10)
            break;
    }

    /* Validate rows fetched */
    fprintf(stdout, " total rows fetched: %d\n", row_count);

    /* Free the prepared result metadata */
    mysql_free_result(prepare_meta_result);

    /* Close the statement */
    if (mysql_stmt_close(stmt)) {
        fprintf(stderr, " failed while closing the statement\n");
        fprintf(stderr, " %s\n", mysql_stmt_error(stmt));
        exit(0);
    }
}
int recorder::init(OBJECT *parent)
{
	// check the connection
	if ( get_connection()!=NULL )
		db = (database*)(get_connection()+1);
	if ( db==NULL )
		exception("no database connection available or specified");
	if ( !db->isa("database") )
		exception("connection is not a mysql database");
	gl_verbose("connection to mysql server '%s', schema '%s' ok", db->get_hostname(), db->get_schema());

	// check mode
	if ( strlen(mode)>0 )
	{
		options = 0xffffffff;
		struct {
			char *str;
			set bits;
		} modes[] = {
			{"r",	0xffff},
			{"r+",	0xffff},
			{"w",	MO_DROPTABLES},
			{"w+",	MO_DROPTABLES},
			{"a",	0x0000},
			{"a+",	0x0000},
		};
		int n;
		for ( n=0 ; n<sizeof(modes)/sizeof(modes[0]) ; n++ )
		{
			if ( strcmp(mode,modes[n].str)==0 )
			{
				options = modes[n].bits;
				break;
			}
		}
		if ( options==0xffffffff )
			exception("mode '%s' is not recognized",(const char*)mode);
		else if ( options==0xffff )
			exception("mode '%s' is not valid for a recorder", (const char*)mode);
	}

	// connect the target property
	if ( get_parent()==NULL )
		exception("parent is not set");
	target.set_object(get_parent());

	printf("****************************************before switch*********************************************************\n");

	char propname[64]="", propunit[64]="";
	switch ( sscanf(get_property(),"%[^[][%[^]]",propname,propunit) ) {
	case 2:
		printf("****************************************case 2*********************************************************\n");
		if ( !unit.set_unit(propunit) )
			exception("property '%s' has an invalid unit", get_property());
		// drop through
	case 1:
		printf("****************************************case 1*********************************************************\n");
		printf("propname : %s \n", propname);
		printf("propunit : %s \n", propunit);
		printf("field    : %s \n", field);
		strncpy(field, propname, sizeof(field) - 1);
		printf("****************************************before set property*********************************************************\n");
		target.set_property(propname);
		printf("****************************************after set property*********************************************************\n");
		
		scale = 1.0;
		if ( unit.is_valid() && target.get_unit()!=NULL )
		{
			target.get_unit()->convert(unit,scale);
			sprintf(field,"%s[%s]",propname,propunit);
		}
		else if ( propunit[0]=='\0' && options&MO_USEUNITS && target.get_unit() )
			sprintf(field,"%s[%s]",propname,target.get_unit()->get_name());
		break;
	default:
		printf("****************************************not valid*********************************************************\n");
		exception("property '%s' is not valid", get_property());
		break;
	}
	printf("****************************************after switch*********************************************************\n");

	// check for table existence and create if not found
	if ( target.is_valid() )
	{
		// drop table if exists and drop specified
		if ( db->table_exists(get_table()) )
		{
			if ( get_options()&MO_DROPTABLES && !db->query("DROP TABLE IF EXISTS `%s`", get_table()) )
				exception("unable to drop table '%s'", get_table());
		}
		
		// create table if not exists
		if ( !db->table_exists(get_table()) )
		{
			if ( !(options&MO_NOCREATE) )
			{
				if ( !db->query("CREATE TABLE IF NOT EXISTS `%s` ("
					"id INT AUTO_INCREMENT PRIMARY KEY, "
					"t TIMESTAMP, "
					"`%s` %s, "
					"INDEX i_t (t) "
					")", 
					get_table(), (const char*)field, db->get_sqltype(target)) )
					exception("unable to create table '%s' in schema '%s'", get_table(), db->get_schema());
				else
					gl_verbose("table %s created ok", get_table());
			}
			else
				exception("NOCREATE option prevents creation of table '%s'", get_table());
		}

		// check row count
		else 
		{
			if ( db->select("SELECT count(*) FROM `%s`", get_table())==NULL )
				exception("unable to get row count of table '%s'", get_table());

			gl_verbose("table '%s' ok", get_table());
		}
	}
	else
	{
		exception("property '%s' is not valid", get_property());
		return 0;
	}

	// set heartbeat
	if ( interval>0 )
	{
		set_heartbeat((TIMESTAMP)interval);
		enabled = true;
	}

	// arm trigger, if any
	if ( enabled && trigger[0]!='\0' )
	{
		// read trigger condition
		if ( sscanf(trigger,"%[<>=!]%s",compare_op,compare_val)==2 )
		{
			// rescale comparison value if necessary
			if ( scale!=1.0 )
				sprintf(compare_val,"%g",atof(compare_val)/scale);

			// enable trigger and suspend data collection
			trigger_on=true;
			enabled=false;
		}
	}

	// prepare insert statement
	char statement[1024];
	int len = sprintf(statement,"INSERT INTO `%s` (`%s`) VALUES ('?')", get_table(), (const char*)field);
	gl_verbose("preparing statement '%s'", statement);
	printf("****************************************preparing statement*********************************************************\n");
	printf("preparing statement '%s' \n", statement);
	insert = mysql_stmt_init(db->get_handle());
	if ( !db->get_sqlbind(value,target,&stmt_error) )
	{
		gl_warning("unable to bind target '%s'", target.get_name());
		mysql_stmt_close(insert);
		insert = NULL;
	}
	else if ( mysql_stmt_prepare(insert,statement,len)!=0 )
	{
		gl_warning("insert statement '%s' prepare failed (error='%s'), using slowing 'INSERT' method", statement, mysql_stmt_error(insert));
		mysql_stmt_close(insert);
		insert = NULL;
	}
	else if ( mysql_stmt_bind_param(insert,&value)!=0 )
	{
		gl_warning("insert statement '%s' bind failed (error='%s'), using slowing 'INSERT' method", statement, mysql_stmt_error(insert));
		mysql_stmt_close(insert);
		insert = NULL;
	}

	return 1;
}
Exemple #18
0
void mysql_search_logg(MYSQL *demo_db, struct QueryDataForamt *QueryData, 
	struct SiderHederFormat *FinalSiderHeder, int totlaAds, 
	struct queryNodeHederFormat *queryNodeHeder, int nrOfServers, struct SiderFormat *Sider, 
	int nrOfPiServers) {
	/********************************************************************************************/
	//mysql logging
	/********************************************************************************************/

#ifndef MYSQL_VERSION_ID

	#error "MYSQL_VERSION_ID fra mysql_version.h er ikke definert"

#elif MYSQL_VERSION_ID==50045


	MYSQL_STMT *logstmt, *pilogstmt;
	char query [2048];
	MYSQL_BIND bind[12];
	unsigned long len[12];
	memset(bind, 0, sizeof(bind));
	logstmt = mysql_stmt_init(demo_db);
	pilogstmt = mysql_stmt_init(demo_db);

	if ((logstmt==NULL) || (pilogstmt==NULL)) {
		fprintf(stderr, "out of memory. Cant Create logstmt or pilogstmt");
	}

	sprintf(query,"INSERT DELAYED INTO search_logg (tid,query,search_bruker,treff,search_tid,ip_adresse,betaler_keywords_treff,HTTP_ACCEPT_LANGUAGE,HTTP_USER_AGENT,HTTP_REFERER,GeoIPLang,side) VALUES(NOW(),?,?,?,?,?,?,?,?,?,?,?)");

	if (mysql_stmt_prepare(logstmt, query, strlen(query)) != 0) {
		fprintf(stderr, " mysql_stmt_prepare(), INSERT INTO search_logg failed\n");
		fprintf(stderr, " Error: \"%s\"\n", mysql_stmt_error(logstmt));			
		return;
	}

	bind[0].buffer_type = MYSQL_TYPE_STRING; // query
	bind[0].buffer = QueryData->query;	// Ax: Max lengde i databasen er 30 tegn. Lage en nice-write?
	len[0] = strlen(QueryData->query);
	bind[0].length = &len[0];

	bind[1].buffer_type = MYSQL_TYPE_STRING; // user
	bind[1].buffer = QueryData->search_user;
	len[1] = strlen(QueryData->search_user);
	bind[1].length = &len[1];

	if (FinalSiderHeder==NULL) {

		bind[2].buffer_type = MYSQL_TYPE_NULL; // treff
		bind[2].buffer = NULL;

		bind[3].buffer_type = MYSQL_TYPE_NULL; // sÃketid
		bind[3].buffer = NULL;
	}
	else {
		bind[2].buffer_type = MYSQL_TYPE_LONG; // treff
		bind[2].buffer = &FinalSiderHeder->TotaltTreff;

		bind[3].buffer_type = MYSQL_TYPE_DOUBLE; // sÃketid
		bind[3].buffer = &FinalSiderHeder->total_usecs;
	}
	bind[4].buffer_type = MYSQL_TYPE_STRING; // ip
	bind[4].buffer = QueryData->userip;
	len[4] = strlen(QueryData->userip);
	bind[4].length = &len[4];

	bind[5].buffer_type = MYSQL_TYPE_LONG; // betaler
	bind[5].buffer = &totlaAds;
		
	bind[6].buffer_type = MYSQL_TYPE_STRING; // http lang
	bind[6].buffer = QueryData->HTTP_ACCEPT_LANGUAGE;
	len[6] = strlen(QueryData->HTTP_ACCEPT_LANGUAGE);
	bind[6].length = &len[6];

	bind[7].buffer_type = MYSQL_TYPE_STRING; // http user agent
	bind[7].buffer = QueryData->HTTP_USER_AGENT;
	len[7] = strlen(QueryData->HTTP_USER_AGENT);
	bind[7].length = &len[7];

	bind[8].buffer_type = MYSQL_TYPE_STRING; // http referer
	bind[8].buffer = QueryData->HTTP_REFERER;
	len[8] = strlen(QueryData->HTTP_REFERER);
	bind[8].length = &len[8];

	bind[9].buffer_type = MYSQL_TYPE_STRING; // geoip
	bind[9].buffer = QueryData->GeoIPcontry;
	len[9] = strlen(QueryData->GeoIPcontry);
	bind[9].length = &len[9];

	bind[10].buffer_type = MYSQL_TYPE_LONG; // side
	bind[10].buffer = &QueryData->start;


	mysql_stmt_bind_param(logstmt, bind);

	mysql_stmt_execute(logstmt);
	mysql_stmt_close(logstmt);


	/************************************************************************************************
	Logging av Paid Inclusion til sql db.
	************************************************************************************************/
	#ifndef BLACK_BOX
		if (Sider != NULL) {
			sprintf(query,"insert into pi_search_logg (tid,query,treff,search_tid,ip_adresse,spot,piDocID ) \
				select NOW(),?,?,?,?,?,id from pi_sider where WWWDocID=? ");


			if (mysql_stmt_prepare(pilogstmt, query, strlen(query)) != 0) {
				fprintf(stderr, " mysql_stmt_prepare(), INSERT into pi_search_logg failed\n");
				fprintf(stderr, " %s\n", mysql_stmt_error(pilogstmt));
				return;
			}

			i = QueryData->MaxsHits * (QueryData->start -1);
			x = i;

			while ((x<(QueryData->MaxsHits * QueryData->start)) && (x<FinalSiderHeder->showabal) && (i < (queryNodeHeder->MaxsHits * (nrOfServers + nrOfPiServers)))) {

				if (!Sider[i].deletet) {
					dprintf("pi analyse. Subname \"%s\", pi \"%i\"\n",Sider[i].subname.subname, (int)Sider[i].subname.config.isPaidInclusion);

					if (Sider[i].subname.config.isPaidInclusion) {
						unsigned int spot;

						spot = x + 1;		

						memset(bind, 0, sizeof(bind));
						memset(len, 0, sizeof(len)); // må vi ha denne?

						bind[0].buffer_type = MYSQL_TYPE_STRING; // query
						bind[0].buffer = QueryData->query;
						len[0] = strlen(QueryData->query);
						bind[0].length = &len[0];
						
						bind[1].buffer_type = MYSQL_TYPE_LONG; // treff
						bind[1].buffer = &FinalSiderHeder->TotaltTreff;
						
						bind[2].buffer_type = MYSQL_TYPE_DOUBLE; // sÃketid
						bind[2].buffer = &FinalSiderHeder->total_usecs;
						
						bind[3].buffer_type = MYSQL_TYPE_STRING; // ip
						bind[3].buffer = QueryData->userip;
						len[3] = strlen(QueryData->userip);
						bind[3].length = &len[3];

						bind[4].buffer_type = MYSQL_TYPE_LONG ; // spot 
						bind[4].buffer = &spot;
						bind[4].is_unsigned = 1; 
		
						bind[5].buffer_type = MYSQL_TYPE_LONG; // piDocID
						bind[5].buffer = &Sider[i].iindex.DocID;
						bind[5].is_unsigned = 1; 


						if (mysql_stmt_bind_param(pilogstmt, bind) != 0) {
							fprintf(stderr, " mysql_stmt_bind_param() failed\n");
							fprintf(stderr, " %s\n", mysql_stmt_error(pilogstmt));
						}

						if (mysql_stmt_execute(pilogstmt) != 0) {
							fprintf(stderr, " mysql_stmt_execute(), 1 failed\n");
							fprintf(stderr, " %s\n", mysql_stmt_error(pilogstmt));
						}

						/* Get the total number of affected rows */
						affected_rows= mysql_stmt_affected_rows(pilogstmt);

						if (affected_rows != 1) /* validate affected rows */
						{
							fprintf(stderr, " invalid affected rows by MySQL\n");
							fprintf(stderr, " total affected rows(insert 1): %lu\n", (unsigned long) affected_rows);
							break;
						}
					}
					else {
						//dprintf("is NOT pi! :(\n");
					}
				}
				//teller bare normale sider (hva med Paid Inclusion ?)
				// Denne skal vel vaere innenfor !deletet?
				if (Sider[i].type == siderType_normal) {
					++x;
				}

				++i;
			}

			mysql_stmt_close(pilogstmt);
		}
Exemple #19
0
void stmt_fetch_init(Stmt_fetch *fetch, unsigned stmt_no_arg,
const char *query_arg)
{
 unsigned long type= CURSOR_TYPE_READ_ONLY;
 int rc;
 unsigned i;
 MYSQL_RES *metadata;
 DBUG_ENTER("stmt_fetch_init");

 /* Save query and statement number for error messages */
 fetch->stmt_no= stmt_no_arg;
 fetch->query= query_arg;

 fetch->handle= mysql_stmt_init(mysql);

 rc= mysql_stmt_prepare(fetch->handle, fetch->query, (ulong)strlen(fetch->query));
 check_execute(fetch->handle, rc);

 /*
 The attribute is sent to server on execute and asks to open read-only
 for result set
 */
 mysql_stmt_attr_set(fetch->handle, STMT_ATTR_CURSOR_TYPE,
 (const void*) &type);

 rc= mysql_stmt_execute(fetch->handle);
 check_execute(fetch->handle, rc);

 /* Find out total number of columns in result set */
 metadata= mysql_stmt_result_metadata(fetch->handle);
 fetch->column_count= mysql_num_fields(metadata);
 mysql_free_result(metadata);

 /*
 Now allocate bind handles and buffers for output data:
 calloc memory to reduce number of MYSQL_BIND members we need to
 set up.
 */

 fetch->bind_array= (MYSQL_BIND *) calloc(1, sizeof(MYSQL_BIND) *
 fetch->column_count);
 fetch->out_data= (char**) calloc(1, sizeof(char*) * fetch->column_count);
 fetch->out_data_length= (ulong*) calloc(1, sizeof(ulong) *
                                         fetch->column_count);
 for (i= 0; i < fetch->column_count; ++i)
 {
   fetch->out_data[i]= (char*) calloc(1, MAX_COLUMN_LENGTH);
   fetch->bind_array[i].buffer_type= MYSQL_TYPE_STRING;
   fetch->bind_array[i].buffer= fetch->out_data[i];
   fetch->bind_array[i].buffer_length= MAX_COLUMN_LENGTH;
   fetch->bind_array[i].length= fetch->out_data_length + i;
 }

 mysql_stmt_bind_result(fetch->handle, fetch->bind_array);

 fetch->row_count= 0;
 fetch->is_open= TRUE;

 /* Ready for reading rows */
 DBUG_VOID_RETURN;
}
Exemple #20
0
void Event::updateNotes( const StringSetMap &newNoteSetMap )
{
    bool update = false;

    //Info( "Checking notes, %d <> %d", noteSetMap.size(), newNoteSetMap.size() );
    if ( newNoteSetMap.size() > 0 )
    {
        if ( noteSetMap.size() == 0 )
        {
            noteSetMap = newNoteSetMap;
            update = true;
        }
        else
        {
            for ( StringSetMap::const_iterator newNoteSetMapIter = newNoteSetMap.begin(); newNoteSetMapIter != newNoteSetMap.end(); newNoteSetMapIter++ )
            {
                const std::string &newNoteGroup = newNoteSetMapIter->first;
                const StringSet &newNoteSet = newNoteSetMapIter->second;
                //Info( "Got %d new strings", newNoteSet.size() );
                if ( newNoteSet.size() > 0 )
                {
                    StringSetMap::iterator noteSetMapIter = noteSetMap.find( newNoteGroup );
                    if ( noteSetMapIter == noteSetMap.end() )
                    {
                        //Info( "Can't find note group %s, copying %d strings", newNoteGroup.c_str(), newNoteSet.size() );
                        noteSetMap.insert( StringSetMap::value_type( newNoteGroup, newNoteSet ) );
                        update = true;
                    }
                    else
                    {
                        StringSet &noteSet = noteSetMapIter->second;
                        //Info( "Found note group %s, got %d strings", newNoteGroup.c_str(), newNoteSet.size() );
                        for ( StringSet::const_iterator newNoteSetIter = newNoteSet.begin(); newNoteSetIter != newNoteSet.end(); newNoteSetIter++ )
                        {
                            const std::string &newNote = *newNoteSetIter;
                            StringSet::iterator noteSetIter = noteSet.find( newNote );
                            if ( noteSetIter == noteSet.end() )
                            {
                                noteSet.insert( newNote );
                                update = true;
                            }
                        }
                    }
                }
            }
        }
    }

    if ( update )
    {
        std::string notes;
        createNotes( notes );

        Debug( 2, "Updating notes for event %d, '%s'", id, notes.c_str() );
        static char sql[ZM_SQL_MED_BUFSIZ];
#if USE_PREPARED_SQL
        static MYSQL_STMT *stmt = 0;

        char notesStr[ZM_SQL_MED_BUFSIZ] = "";
        unsigned long notesLen = 0;

        if ( !stmt )
        {
            const char *sql = "update Events set Notes = ? where Id = ?";

            stmt = mysql_stmt_init( &dbconn );
            if ( mysql_stmt_prepare( stmt, sql, strlen(sql) ) )
            {
                Fatal( "Unable to prepare sql '%s': %s", sql, mysql_stmt_error(stmt) );
            }

            /* Get the parameter count from the statement */
            if ( mysql_stmt_param_count( stmt ) != 2 )
            {
                Fatal( "Unexpected parameter count %ld in sql '%s'", mysql_stmt_param_count( stmt ), sql );
            }

            MYSQL_BIND  bind[2];
            memset(bind, 0, sizeof(bind));

            /* STRING PARAM */
            bind[0].buffer_type = MYSQL_TYPE_STRING;
            bind[0].buffer = (char *)notesStr;
            bind[0].buffer_length = sizeof(notesStr);
            bind[0].is_null = 0;
            bind[0].length = &notesLen;

            bind[1].buffer_type= MYSQL_TYPE_LONG;
            bind[1].buffer= (char *)&id;
            bind[1].is_null= 0;
            bind[1].length= 0;

            /* Bind the buffers */
            if ( mysql_stmt_bind_param( stmt, bind ) )
            {
                Fatal( "Unable to bind sql '%s': %s", sql, mysql_stmt_error(stmt) );
            }
        }

        strncpy( notesStr, notes.c_str(), sizeof(notesStr) );
        notesLen = notes.length();

        if ( mysql_stmt_execute( stmt ) )
        {
            Fatal( "Unable to execute sql '%s': %s", sql, mysql_stmt_error(stmt) );
        }
#else
        static char escapedNotes[ZM_SQL_MED_BUFSIZ];

        mysql_real_escape_string( &dbconn, escapedNotes, notes.c_str(), notes.length() );

        snprintf( sql, sizeof(sql), "update Events set Notes = '%s' where Id = %d", escapedNotes, id );
        if ( mysql_query( &dbconn, sql ) )
        {
            Error( "Can't insert event: %s", mysql_error( &dbconn ) );
        }
#endif
    }
}
Exemple #21
0
static DWORD UserSyncIncrUpdates(DB_CONTEXT *db, SYNC_CONTEXT *sync)
{
    CHAR        *query;
    CHAR        userName[_MAX_NAME + 1];
    DWORD       error;
    INT         result;
    USERFILE    userFile;
    MYSQL_BIND  bindInput[2];
    MYSQL_BIND  bindOutput[17];
    MYSQL_RES   *metadata;
    MYSQL_STMT  *stmt;

    ASSERT(db != NULL);
    ASSERT(sync != NULL);

    //
    // Prepare statement and bind parameters
    //

    stmt = db->stmt[7];

    query = "SELECT name,description,flags,home,limits,password,vfsfile,credits,"
            "       ratio,alldn,allup,daydn,dayup,monthdn,monthup,wkdn,wkup"
            "  FROM io_user"
            "  WHERE updated BETWEEN ? AND ?";

    result = mysql_stmt_prepare(stmt, query, strlen(query));
    if (result != 0) {
        LOG_WARN("Unable to prepare statement: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    DB_CHECK_PARAMS(bindInput, stmt);
    ZeroMemory(&bindInput, sizeof(bindInput));

    bindInput[0].buffer_type = MYSQL_TYPE_LONG;
    bindInput[0].buffer      = &sync->prevUpdate;
    bindInput[0].is_unsigned = TRUE;

    bindInput[1].buffer_type = MYSQL_TYPE_LONG;
    bindInput[1].buffer      = &sync->currUpdate;
    bindInput[1].is_unsigned = TRUE;

    result = mysql_stmt_bind_param(stmt, bindInput);
    if (result != 0) {
        LOG_WARN("Unable to bind parameters: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    metadata = mysql_stmt_result_metadata(stmt);
    if (metadata == NULL) {
        LOG_WARN("Unable to retrieve result metadata: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    //
    // Execute prepared statement
    //

    result = mysql_stmt_execute(stmt);
    if (result != 0) {
        LOG_ERROR("Unable to execute statement: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    //
    // Bind and fetch results
    //

    DB_CHECK_RESULTS(bindOutput, metadata);
    ZeroMemory(&bindOutput, sizeof(bindOutput));

    bindOutput[0].buffer_type   = MYSQL_TYPE_STRING;
    bindOutput[0].buffer        = userName;
    bindOutput[0].buffer_length = sizeof(userName);

    bindOutput[1].buffer_type   = MYSQL_TYPE_STRING;
    bindOutput[1].buffer        = userFile.Tagline;
    bindOutput[1].buffer_length = sizeof(userFile.Tagline);

    bindOutput[2].buffer_type   = MYSQL_TYPE_STRING;
    bindOutput[2].buffer        = userFile.Flags;
    bindOutput[2].buffer_length = sizeof(userFile.Flags);

    bindOutput[3].buffer_type   = MYSQL_TYPE_STRING;
    bindOutput[3].buffer        = userFile.Home;
    bindOutput[3].buffer_length = sizeof(userFile.Home);

    bindOutput[4].buffer_type   = MYSQL_TYPE_BLOB;
    bindOutput[4].buffer        = &userFile.Limits;
    bindOutput[4].buffer_length = sizeof(userFile.Limits);

    bindOutput[5].buffer_type   = MYSQL_TYPE_BLOB;
    bindOutput[5].buffer        = &userFile.Password;
    bindOutput[5].buffer_length = sizeof(userFile.Password);

    bindOutput[6].buffer_type   = MYSQL_TYPE_STRING;
    bindOutput[6].buffer        = userFile.MountFile;
    bindOutput[6].buffer_length = sizeof(userFile.MountFile);

    bindOutput[7].buffer_type   = MYSQL_TYPE_BLOB;
    bindOutput[7].buffer        = &userFile.Ratio;
    bindOutput[7].buffer_length = sizeof(userFile.Ratio);

    bindOutput[8].buffer_type   = MYSQL_TYPE_BLOB;
    bindOutput[8].buffer        = &userFile.Credits;
    bindOutput[8].buffer_length = sizeof(userFile.Credits);

    bindOutput[9].buffer_type   = MYSQL_TYPE_BLOB;
    bindOutput[9].buffer        = &userFile.DayUp;
    bindOutput[9].buffer_length = sizeof(userFile.DayUp);

    bindOutput[10].buffer_type   = MYSQL_TYPE_BLOB;
    bindOutput[10].buffer        = &userFile.DayDn;
    bindOutput[10].buffer_length = sizeof(userFile.DayDn);

    bindOutput[11].buffer_type   = MYSQL_TYPE_BLOB;
    bindOutput[11].buffer        = &userFile.WkUp;
    bindOutput[11].buffer_length = sizeof(userFile.WkUp);

    bindOutput[12].buffer_type   = MYSQL_TYPE_BLOB;
    bindOutput[12].buffer        = &userFile.WkDn;
    bindOutput[12].buffer_length = sizeof(userFile.WkDn);

    bindOutput[13].buffer_type   = MYSQL_TYPE_BLOB;
    bindOutput[13].buffer        = &userFile.MonthUp;
    bindOutput[13].buffer_length = sizeof(userFile.MonthUp);

    bindOutput[14].buffer_type   = MYSQL_TYPE_BLOB;
    bindOutput[14].buffer        = &userFile.MonthDn;
    bindOutput[14].buffer_length = sizeof(userFile.MonthDn);

    bindOutput[15].buffer_type   = MYSQL_TYPE_BLOB;
    bindOutput[15].buffer        = &userFile.AllUp;
    bindOutput[15].buffer_length = sizeof(userFile.AllUp);

    bindOutput[16].buffer_type   = MYSQL_TYPE_BLOB;
    bindOutput[16].buffer        = &userFile.AllDn;
    bindOutput[16].buffer_length = sizeof(userFile.AllDn);

    result = mysql_stmt_bind_result(stmt, bindOutput);
    if (result != 0) {
        LOG_WARN("Unable to bind results: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    result = mysql_stmt_store_result(stmt);
    if (result != 0) {
        LOG_WARN("Unable to buffer results: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    //
    // Process result set
    //

    for (;;) {
        ZeroMemory(&userFile, sizeof(USERFILE));
        if (mysql_stmt_fetch(stmt) != 0) {
            break;
        }
        TRACE("UserSyncIncr: Update(%s)", userName);

        // Read the user's admin-groups, groups, and hosts
        error = DbUserReadExtra(db, userName, &userFile);
        if (error != ERROR_SUCCESS) {
            LOG_WARN("Unable to read user \"%s\" (error %lu).", userName, error);
        } else {

            // Update user file
            error = UserEventUpdate(userName, &userFile);
            if (error != ERROR_SUCCESS) {
                LOG_WARN("Unable to update user \"%s\" (error %lu).", userName, error);
            }
        }
    }

    mysql_free_result(metadata);

    return ERROR_SUCCESS;
}
bool AutopatcherMySQLRepository::UpdateApplicationFiles(const char *applicationName, const char *applicationDirectory, const char *userName, FileListProgress *cb)
{
	MYSQL_STMT    *stmt;
	MYSQL_BIND    bind[3];
	char query[512];
	FileList filesOnHarddrive;
	filesOnHarddrive.SetCallback(cb);
	int prepareResult;
	my_bool falseVar=false;
	RakNet::RakString escapedApplicationName = GetEscapedString(applicationName);
	filesOnHarddrive.AddFilesFromDirectory(applicationDirectory,"", true, true, true, FileListNodeContext(0,0));
	if (filesOnHarddrive.fileList.Size()==0)
	{
		sprintf(lastError,"ERROR: Can't find files at %s in UpdateApplicationFiles\n",applicationDirectory);
		return false;
	}

	sprintf(query, "SELECT applicationID FROM Applications WHERE applicationName='%s';", escapedApplicationName.C_String());
	int applicationID;

	if (!ExecuteQueryReadInt(query, &applicationID))
	{
		sprintf(lastError,"ERROR: %s not found in UpdateApplicationFiles\n",escapedApplicationName.C_String());
		return false;
	}

	if (!ExecuteBlockingCommand("BEGIN;"))
	{
		return false;
	}
	sprintf(query, "UPDATE Applications SET changeSetId = changeSetId + 1 where applicationID=%i;", applicationID);
	if (!ExecuteBlockingCommand(query))
	{
		Rollback ();
		return false;
	}
	int changeSetId = 0;
	sprintf(query, "SELECT changeSetId FROM Applications WHERE applicationID=%i;", applicationID);
	if (!ExecuteQueryReadInt(query, &changeSetId))
	{
		Rollback ();
		return false;
	}

	// +1 was added in the update
	changeSetId--;

	// Gets all newest files
	sprintf(query, "SELECT filename, contentHash, createFile FROM FileVersionHistory "
	               "JOIN (SELECT max(fileId) maxId FROM FileVersionHistory WHERE applicationId=%i GROUP BY fileName) MaxId "
	               "ON FileVersionHistory.fileId = MaxId.maxId "
	               "ORDER BY filename DESC;", applicationID);

	MYSQL_RES *result = 0;
	if (!ExecuteBlockingCommand(query, &result))
	{
		Rollback();
		return false;
	}
	DataStructures::List <FileInfo> newestFiles;
	MYSQL_ROW row;
	while ((row = mysql_fetch_row (result)) != 0)
	{
	    FileInfo fi;
		fi.filename = row [0];
		fi.createFile = (atoi (row [2]) != 0);
		if (fi.createFile)
		{
			RakAssert(mysql_fetch_lengths (result) [1] == HASH_LENGTH);  // check the data is sensible
			memcpy (fi.contentHash, row [1], HASH_LENGTH);
		}
	    newestFiles.Insert (fi);
	}    
	mysql_free_result(result);


	FileList newFiles;
	// Loop through files on filesOnHarddrive
	// If the file in filesOnHarddrive does not exist in the query result, or if it does but the hash is different or non-existent, add this file to the create list
	for (unsigned fileListIndex=0; fileListIndex < filesOnHarddrive.fileList.Size(); fileListIndex++)
	{
		bool addFile=true;
		if (fileListIndex%10==0)
			printf("Hashing files %i/%i\n", fileListIndex+1, filesOnHarddrive.fileList.Size());

		const char * hardDriveFilename=filesOnHarddrive.fileList[fileListIndex].filename;
		const char * hardDriveHash=filesOnHarddrive.fileList[fileListIndex].data;

		for (unsigned i = 0; i != newestFiles.Size (); ++i)
		{
			const FileInfo & fi = newestFiles [i];
                        
			if (_stricmp(hardDriveFilename, fi.filename)==0)
			{
				if (fi.createFile && memcmp(fi.contentHash, hardDriveHash, HASH_LENGTH)==0)
				{
					// File exists in database and is the same
					addFile=false;
				}

				break;
			}
		}

		// Unless set to false, file does not exist in query result or is different.
		if (addFile)
		{
			newFiles.AddFile(hardDriveFilename,hardDriveFilename, filesOnHarddrive.fileList[fileListIndex].data, filesOnHarddrive.fileList[fileListIndex].dataLengthBytes, filesOnHarddrive.fileList[fileListIndex].fileLengthBytes, FileListNodeContext(0,0), false);
		}
	}
	
	// Go through query results that are marked as create
	// If a file that is currently in the database is not on the harddrive, add it to the delete list
	FileList deletedFiles;
	for (unsigned i = 0; i != newestFiles.Size (); ++i)
	{
		const FileInfo & fi = newestFiles [i];
		if (!fi.createFile)
			continue; // If already false don't mark false again.

		bool fileOnHarddrive=false;
		for (unsigned fileListIndex=0; fileListIndex < filesOnHarddrive.fileList.Size(); fileListIndex++)
		{
			const char * hardDriveFilename=filesOnHarddrive.fileList[fileListIndex].filename;
			//hardDriveHash=filesOnHarddrive.fileList[fileListIndex].data;

			if (_stricmp(hardDriveFilename, fi.filename)==0)
			{
				fileOnHarddrive=true;
				break;
			}
		}

		if (!fileOnHarddrive)
			deletedFiles.AddFile(fi.filename,fi.filename,0,0,0,FileListNodeContext(0,0), false);
	}

	// files on harddrive no longer needed.  Free this memory since generating all the patches is memory intensive.
	filesOnHarddrive.Clear();

	// For each file in the delete list add a row indicating file deletion
	for (unsigned fileListIndex=0; fileListIndex < deletedFiles.fileList.Size(); fileListIndex++)
	{
		if (fileListIndex%10==0)
			printf("Tagging deleted files %i/%i\n", fileListIndex+1, deletedFiles.fileList.Size());

		sprintf(query, "INSERT INTO FileVersionHistory(applicationID, filename, createFile, changeSetID, userName) VALUES (%i, '%s', FALSE,%i,'%s');", 
			applicationID, GetEscapedString(deletedFiles.fileList[fileListIndex].filename).C_String(), changeSetId, GetEscapedString(userName).C_String());
		
		if (!ExecuteBlockingCommand (query))
		{
			Rollback();
			deletedFiles.Clear();
			newFiles.Clear();
			return false;
		}
	}
	
	// Clear the delete list as it is no longer needed.
	deletedFiles.Clear();

	// For each file in the create list
	for (unsigned fileListIndex=0; fileListIndex < newFiles.fileList.Size(); fileListIndex++)
	{
		if (fileListIndex%10==0)
			printf("Adding file %i/%i\n", fileListIndex+1, newFiles.fileList.Size());
		const char * hardDriveFilename=newFiles.fileList[fileListIndex].filename;
		const char * hardDriveData=newFiles.fileList[fileListIndex].data+HASH_LENGTH;
		const char * hardDriveHash=newFiles.fileList[fileListIndex].data;
		unsigned     hardDriveDataLength=newFiles.fileList[fileListIndex].fileLengthBytes;

		sprintf( query, "SELECT fileID from FileVersionHistory WHERE applicationID=%i AND filename='%s' AND createFile=TRUE;", applicationID, GetEscapedString(hardDriveFilename).C_String() );

		MYSQL_RES * res = 0;
		if (!ExecuteBlockingCommand (query, &res))
		{
			Rollback();
			newFiles.Clear();
			return false;
		}
		
		// Create new patches for every create version
		MYSQL_ROW row;

		while ((row = mysql_fetch_row (res)) != 0)
		{
			const char * fileID = row [0];
			
			// The last query handled all the relevant comparisons
			sprintf(query, "SELECT content from FileVersionHistory WHERE fileID=%s", fileID );
			MYSQL_RES * queryResult = 0;
			if (!ExecuteBlockingCommand (query, &queryResult))
			{
				Rollback();
				newFiles.Clear();
				mysql_free_result(res);
				return false;
			}
		
			MYSQL_ROW queryRow = mysql_fetch_row (queryResult);

			const unsigned contentLength=mysql_fetch_lengths (queryResult) [0];
			const char * content=queryRow [0];

			char *patch;
			unsigned patchLength;	
			if (!CreatePatch(content, contentLength, (char *) hardDriveData, hardDriveDataLength, &patch, &patchLength))
			{
				strcpy(lastError,"CreatePatch failed.");
				Rollback();

				newFiles.Clear();
				mysql_free_result(res);
				mysql_free_result(queryResult);
				return false;
			}
			
			char buf[512];
			stmt = mysql_stmt_init(mySqlConnection);
			sprintf (buf, "UPDATE FileVersionHistory SET patch=? where fileID=%s;", fileID);
			if ((prepareResult=mysql_stmt_prepare(stmt, buf, (unsigned long) strlen(buf)))!=0)
			{
				strcpy (lastError, mysql_stmt_error (stmt));
				mysql_stmt_close(stmt);
				Rollback();
				return false;
			}
			memset(bind, 0, sizeof(bind));

			unsigned long l1;
			l1=patchLength;
			bind[0].buffer_type= MYSQL_TYPE_LONG_BLOB;
			bind[0].buffer= patch;
			bind[0].buffer_length= patchLength;
			bind[0].is_null= &falseVar;
			bind[0].length=&l1;

			if (mysql_stmt_bind_param(stmt, bind))
			{
				strcpy (lastError, mysql_stmt_error (stmt));
				mysql_stmt_close(stmt);
				Rollback();
				return false;
			}

			if (mysql_stmt_execute(stmt))
			{
				strcpy (lastError, mysql_stmt_error (stmt));
				mysql_stmt_close(stmt);
				Rollback();
				newFiles.Clear();
				mysql_free_result(res);
				mysql_free_result(queryResult);
				delete [] patch;
				return false;
			}

			mysql_stmt_close(stmt);
			delete [] patch;

			mysql_free_result(queryResult);
		}
         mysql_free_result(res);

		 stmt = mysql_stmt_init(mySqlConnection);
		 sprintf(query, "INSERT INTO FileVersionHistory (applicationID, filename, fileLength, content, contentHash, createFile, changeSetID, userName) "
			 "VALUES (%i, ?, %i,?,?, TRUE, %i, '%s' );", 
			 applicationID, hardDriveDataLength, changeSetId, GetEscapedString(userName).C_String());

		 if ((prepareResult=mysql_stmt_prepare(stmt, query, (unsigned long) strlen(query)))!=0)
		 {
			 strcpy (lastError, mysql_stmt_error (stmt));
			 mysql_stmt_close(stmt);
			 Rollback();
			 return false;
		 }
		 memset(bind, 0, sizeof(bind));

		 unsigned long l2,l3,l4;
		 l2=(unsigned long) strlen(hardDriveFilename);
		 l3=hardDriveDataLength;
		 l4=HASH_LENGTH;
		 bind[0].buffer_type= MYSQL_TYPE_STRING;
		 bind[0].buffer= (void*) hardDriveFilename;
		 bind[0].buffer_length= (unsigned long) strlen(hardDriveFilename);
		 bind[0].is_null= &falseVar;
		 bind[0].length=&l2;

		 bind[1].buffer_type= MYSQL_TYPE_LONG_BLOB;
		 bind[1].buffer= (void*) hardDriveData;
		 bind[1].buffer_length= hardDriveDataLength;
		 bind[1].is_null= &falseVar;
		 bind[1].length=&l3;

		 bind[2].buffer_type= MYSQL_TYPE_TINY_BLOB;
		 bind[2].buffer= (void*) hardDriveHash;
		 bind[2].buffer_length= HASH_LENGTH;
		 bind[2].is_null= &falseVar;
		 bind[2].length=&l4;

		 if (mysql_stmt_bind_param(stmt, bind))
		 {
			 strcpy (lastError, mysql_stmt_error (stmt));
			 mysql_stmt_close(stmt);
			 Rollback();
			 return false;
		 }

		 if (mysql_stmt_execute(stmt))
		 {
			 strcpy (lastError, mysql_stmt_error (stmt));
			 mysql_stmt_close(stmt);
			 Rollback();
			 return false;
		 }

		 mysql_stmt_close(stmt);
	}

	if (!ExecuteBlockingCommand("COMMIT;"))
	{
        Rollback ();
		return false;
	}

	return true;
}
int main(int argc, char* argv[])
{
    MYSQL *mysql,*sock;
    MYSQL_ROW row;
    MYSQL_RES *result;

    mysql = mysql_init(NULL);
    if (!(sock = CONN(0))) {
        fprintf(stderr, "Couldn't connect to engine!\n%s\n\n", mysql_error(mysql));
        perror("");
        exit(1);
    }

    // simple 
    char sql[100] = {};

    sprintf(sql, "INSERT INTO blob_test(a, b) VALUE (1, 2)");

    mysql_query(sock, sql);

    mysql_query(sock, "select * from blob_test");
    
    result = mysql_store_result(mysql);
    mysql_free_result(result);

    #define INSERT_QUERY "INSERT INTO blob_test(a, b) VALUES(?,?)"

    MYSQL_STMT    *stmt;
    MYSQL_BIND bind[2];
    long       length;
    int         int_data = 10;
    char        str[100];
    int         ret;

    stmt = mysql_stmt_init(mysql);

    mysql_stmt_prepare(stmt, INSERT_QUERY, strlen(INSERT_QUERY));

    memset(bind, 0, sizeof(bind));
    bind[0].buffer_type= MYSQL_TYPE_LONG;
    bind[0].buffer= (char *)&int_data;
    bind[0].is_null= 0;
    bind[1].buffer_type= MYSQL_TYPE_BLOB;
    bind[1].buffer = (char*)&str;
    bind[1].is_null= 0;
    mysql_stmt_bind_param(stmt, bind);

    ret = mysql_stmt_send_long_data(stmt,1,"fails",5);

    ret = mysql_stmt_send_long_data(stmt,1," - The most popular Open Source database",40);

    mysql_stmt_execute(stmt);

    mysql_stmt_close(stmt);

    stmt = mysql_stmt_init(mysql);

    mysql_stmt_prepare(stmt, INSERT_QUERY, strlen(INSERT_QUERY));

    size_t s = sizeof(str);

    memset(bind, 0, sizeof(bind));
    bind[0].buffer_type= MYSQL_TYPE_LONG;
    bind[0].buffer= (char *)&int_data;
    bind[0].is_null= 0;
    bind[1].buffer_type= MYSQL_TYPE_BLOB;
    bind[1].buffer = (char*)&str;
    bind[1].is_null= 0;
    bind[1].length= (char*)&s;
    mysql_stmt_bind_param(stmt, bind);

    snprintf(str, sizeof(str), "%s", "this success");

    mysql_stmt_execute(stmt);

    mysql_stmt_close(stmt);

    return 0;
}
Exemple #24
0
/*
 * Executes the given SQL query after binding the parameters as indicated
 * by 'params'. The results are bound to the provided pointers with order
 * and types described by 'fields'. Number of var args should match the
 * combined length of 'params' and 'fields'. The number of 'params' must
 * be exactly the same as the number of ?s in the query.
 *
 * Valid format specifies:
 *    d:  MYSQL_TYPE_LONG (signed)
 *    D:  MYSQL_TYPE_LONG (unsigned)
 *    f:  MYSQL_TYPE_DOUBLE
 *    s:  MYSQL_TYPE_STRING
 *    S:  MYSQL_TYPE_STRING, buffer size followed by pointer to the data
 *
 *    note that strings are (char *) for input parameters and (char **) for output parameters
 *
 * Examples:
 *     int id;
 *     char *name, *new_name, *status;
 *
 *     SSTR(query, "SELECT name FROM table WHERE id = ?");
 *     mysql_helper_stmt(&mh, query, SSTRLEN(query), "d", "s", &id, &name);
 *
 *     SSTR(query, "UPDATE table SET name = ? WHERE id = ?");
 *     mysql_helper_stmt(&mh, query, SSTRLEN(query), "sd", "", new_name, &id);
 *
 *     SSTR(query, "INSERT INTO table (status, name) VALUES (?, ?)");
 *     mysql_helper_stmt(&mh, query, SSTRLEN(query), "ss", "", status, name);
 */
int mysql_helper_stmt(struct mysql_helper *mysql_helper,
                      const char *query,
                      size_t query_len,
                      const char *params,
                      const char *fields,
                      ...)
{
    /*
     * 0. Cleanup from previous call
     */
    if (mysql_helper->stmt) {
        mysql_stmt_close(mysql_helper->stmt);
        mysql_helper->stmt = NULL;
        vmbuf_reset(&mysql_helper->buf);
    }
    /*
     * 1. Prepare statement
     */
    mysql_helper->stmt = mysql_stmt_init(&mysql_helper->mysql);
    if (!mysql_helper->stmt)
        return report_error(mysql_helper);

    if (0 != mysql_stmt_prepare(mysql_helper->stmt, query, query_len))
        return report_stmt_error(mysql_helper);
    /*
     * 2. Bind parameters if there are any
     */
    uint32_t nparams = strlen(params);
    uint32_t n = mysql_stmt_param_count(mysql_helper->stmt);
    if (nparams != n) {
        LOGGER_ERROR("num params != num ?s in query (%u != %u)", nparams, n);
        return -1;
    }
    const char *p;
    uint32_t i;
    va_list ap;
    va_start(ap, fields);
    /* TODO: move to internal vmbuf (mysql_helper), so
       mysql_stmt_execute can be called multiple times when inserting
       data */
    unsigned long plengths[nparams];
    int ptypes[nparams];
    my_bool pnulls[nparams];
    MYSQL_BIND pbind[nparams];

    if (nparams > 0) {
        memset(pbind, 0, sizeof(pbind));
        MYSQL_BIND *pbind_ptr = pbind;
        for (i = 0, p = params; *p; ++p, ++pbind_ptr, ++i) {
            char c = *p;
            char *str;
            switch(tolower(c)) {
            case 'd':
                ptypes[i] = MYSQL_TYPE_LONG;
                pbind_ptr->buffer = va_arg(ap, int *);
                pnulls[i] = (pbind_ptr->buffer == NULL);
                pbind_ptr->is_unsigned = isupper(c) ? 1 : 0;
                break;
            case 'f':
                ptypes[i] = MYSQL_TYPE_DOUBLE;
                pbind_ptr->buffer = va_arg(ap, double *);
                pnulls[i] = (pbind_ptr->buffer == NULL);
                break;
            case 's':
                ptypes[i] = MYSQL_TYPE_STRING;
                if (isupper(c)) {
                    plengths[i] = va_arg(ap, size_t);
                    str = va_arg(ap, char *);
                } else {
                    str = va_arg(ap, char *);
                    plengths[i] = strlen(str);
                }
                pnulls[i] = (str == NULL);
                pbind_ptr->buffer = str;
                pbind_ptr->buffer_length = plengths[i];
                pbind_ptr->length = &plengths[i];
                break;
            }
            pbind_ptr->buffer_type = ptypes[i];
            pbind_ptr->is_null = &pnulls[i];
        }
Exemple #25
0
DBJob DBManager::get_job(const int& id) {
	DBJob data;

	char *stmt_str = "SELECT term, type FROM wkdd_ldp_jobs WHERE id = ?";
	MYSQL_BIND param[1];
	MYSQL_BIND result[2];
	int my_job_id;
	int my_type;
	char my_term[2000];
	unsigned long my_term_length;

	if (mysql_stmt_prepare(m_stmt, stmt_str, strlen(stmt_str)) != 0) {
		print_stmt_error("could not prepare select statement");
		return data;
	}
	
	if (mysql_stmt_field_count(m_stmt) != 2) {
		print_stmt_error("unexpected column count from select");
		return data;
	}
	
	// initialize result column structures
	memset((void *)param, 0, sizeof(param));
	memset((void *)result, 0, sizeof(result)); // zero the structures
	
	// set up my_id parameter
	param[0].buffer_type = MYSQL_TYPE_LONG;
	param[0].buffer = (void *) &my_job_id;
	param[0].is_unsigned = 0;
	param[0].is_null = 0;
	
	// set up my_term parameter
	result[0].buffer_type = MYSQL_TYPE_STRING;
	result[0].buffer = (void *) &my_term;
	result[0].buffer_length = sizeof(my_term);
	result[0].length = &my_term_length;
	result[0].is_null = 0;
	
	// set up my_type parameter
	result[1].buffer_type = MYSQL_TYPE_LONG;
	result[1].buffer = (void *) &my_type;
	result[1].is_unsigned = 0;
	result[1].is_null = 0;
	
	if (mysql_stmt_bind_param(m_stmt, param) != 0) {
		print_stmt_error("could not bind parameters for select");
		return data;
	}
	
	if (mysql_stmt_bind_result(m_stmt, result) != 0) {
		print_stmt_error("could not bind parameters for select");
		return data;
	}
	
	// set variable
	my_job_id = id;
	
	if (mysql_stmt_execute(m_stmt) != 0) {
		print_stmt_error("could not execute select");
		return data;
	}
	
	// fetch result set into client memory; this is optional, but it allows mysql_stmt_num_rows() to be called to determine the number of rows in the result set
	if (mysql_stmt_store_result(m_stmt) != 0) {
		print_stmt_error("could not buffer result set");
		return data;
	}
	
	mysql_stmt_fetch(m_stmt);  // fetch the single result
	data = DBJob(my_term, my_type);
	
	// deallocate result set
	mysql_stmt_free_result(m_stmt);
	
	return data;
}
Exemple #26
0
static int test_view_2where(MYSQL *mysql)
{
  MYSQL_STMT *stmt;
  int rc, i;
  MYSQL_BIND      my_bind[8];
  char            parms[8][100];
  ulong           length[8];
  const char *query=
    "select relid, report, handle, log_group, username, variant, type, "
    "version, erfdat, erftime, erfname, aedat, aetime, aename, dependvars, "
    "inactive from V_LTDX where mandt = ? and relid = ? and report = ? and "
    "handle = ? and log_group = ? and username in ( ? , ? ) and type = ?";

  rc= mysql_query(mysql, "DROP TABLE IF EXISTS LTDX");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql, "DROP VIEW IF EXISTS V_LTDX");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql,
                  "CREATE TABLE LTDX (MANDT char(3) NOT NULL default '000', "
                  " RELID char(2) NOT NULL, REPORT varchar(40) NOT NULL,"
                  " HANDLE varchar(4) NOT NULL, LOG_GROUP varchar(4) NOT NULL,"
                  " USERNAME varchar(12) NOT NULL,"
                  " VARIANT varchar(12) NOT NULL,"
                  " TYPE char(1) NOT NULL, SRTF2 int(11) NOT NULL,"
                  " VERSION varchar(6) NOT NULL default '000000',"
                  " ERFDAT varchar(8) NOT NULL default '00000000',"
                  " ERFTIME varchar(6) NOT NULL default '000000',"
                  " ERFNAME varchar(12) NOT NULL,"
                  " AEDAT varchar(8) NOT NULL default '00000000',"
                  " AETIME varchar(6) NOT NULL default '000000',"
                  " AENAME varchar(12) NOT NULL,"
                  " DEPENDVARS varchar(10) NOT NULL,"
                  " INACTIVE char(1) NOT NULL, CLUSTR smallint(6) NOT NULL,"
                  " CLUSTD blob,"
                  " PRIMARY KEY (MANDT, RELID, REPORT, HANDLE, LOG_GROUP, "
                                "USERNAME, VARIANT, TYPE, SRTF2))"
                 " CHARSET=latin1 COLLATE latin1_bin");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql,
                  "CREATE VIEW V_LTDX AS select T0001.MANDT AS "
                  " MANDT,T0001.RELID AS RELID,T0001.REPORT AS "
                  " REPORT,T0001.HANDLE AS HANDLE,T0001.LOG_GROUP AS "
                  " LOG_GROUP,T0001.USERNAME AS USERNAME,T0001.VARIANT AS "
                  " VARIANT,T0001.TYPE AS TYPE,T0001.VERSION AS "
                  " VERSION,T0001.ERFDAT AS ERFDAT,T0001.ERFTIME AS "
                  " ERFTIME,T0001.ERFNAME AS ERFNAME,T0001.AEDAT AS "
                  " AEDAT,T0001.AETIME AS AETIME,T0001.AENAME AS "
                  " AENAME,T0001.DEPENDVARS AS DEPENDVARS,T0001.INACTIVE AS "
                  " INACTIVE from LTDX T0001 where (T0001.SRTF2 = 0)");
  check_mysql_rc(rc, mysql);
  memset(my_bind, '\0', sizeof(MYSQL_BIND));
  for (i=0; i < 8; i++) {
    strcpy(parms[i], "1");
    my_bind[i].buffer_type = MYSQL_TYPE_VAR_STRING;
    my_bind[i].buffer = (char *)&parms[i];
    my_bind[i].buffer_length = 100;
    my_bind[i].is_null = 0;
    my_bind[i].length = &length[i];
    length[i] = 1;
  }
  stmt= mysql_stmt_init(mysql);
  rc= mysql_stmt_prepare(stmt, query, strlen(query));
  check_stmt_rc(rc, stmt);

  rc= mysql_stmt_bind_param(stmt, my_bind);
  check_stmt_rc(rc, stmt);

  rc= mysql_stmt_execute(stmt);
  check_stmt_rc(rc, stmt);

  rc= mysql_stmt_fetch(stmt);
  FAIL_UNLESS(MYSQL_NO_DATA == rc, "Expected 0 rows");

  mysql_stmt_close(stmt);

  rc= mysql_query(mysql, "DROP VIEW V_LTDX");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql, "DROP TABLE LTDX");
  check_mysql_rc(rc, mysql);

  return OK;
}
Exemple #27
0
static DWORD GroupSyncFull(DB_CONTEXT *db)
{
    CHAR        *query;
    CHAR        groupName[_MAX_NAME + 1];
    DWORD       error;
    DWORD       i;
    GROUPFILE   groupFile;
    INT         result;
    NAME_ENTRY  *entry;
    NAME_LIST   list;
    MYSQL_BIND  bind[5];
    MYSQL_RES   *metadata;
    MYSQL_STMT  *stmt;

    ASSERT(db != NULL);
    TRACE("db=%p", db);

    //
    // Build list of group IDs
    //

    error = NameListCreateGroups(&list);
    if (error != ERROR_SUCCESS) {
        LOG_ERROR("Unable to create group ID list (error %lu).", error);
        return error;
    }

    //
    // Prepare and execute statement
    //

    stmt = db->stmt[7];

    query = "SELECT name, description, slots, users, vfsfile"
            "  FROM io_group";

    result = mysql_stmt_prepare(stmt, query, strlen(query));
    if (result != 0) {
        TRACE("Unable to prepare statement: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    metadata = mysql_stmt_result_metadata(stmt);
    if (metadata == NULL) {
        TRACE("Unable to prepare statement: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    result = mysql_stmt_execute(stmt);
    if (result != 0) {
        LOG_ERROR("Unable to execute statement: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    //
    // Bind and fetch results
    //

    DB_CHECK_RESULTS(bind, metadata);
    ZeroMemory(&bind, sizeof(bind));

    bind[0].buffer_type   = MYSQL_TYPE_STRING;
    bind[0].buffer        = groupName;
    bind[0].buffer_length = sizeof(groupName);

    bind[1].buffer_type   = MYSQL_TYPE_STRING;
    bind[1].buffer        = groupFile.szDescription;
    bind[1].buffer_length = sizeof(groupFile.szDescription);

    bind[2].buffer_type   = MYSQL_TYPE_BLOB;
    bind[2].buffer        = groupFile.Slots;
    bind[2].buffer_length = sizeof(groupFile.Slots);

    bind[3].buffer_type   = MYSQL_TYPE_LONG;
    bind[3].buffer        = &groupFile.Users;

    bind[4].buffer_type   = MYSQL_TYPE_STRING;
    bind[4].buffer        = groupFile.szVfsFile;
    bind[4].buffer_length = sizeof(groupFile.szVfsFile);

    result = mysql_stmt_bind_result(stmt, bind);
    if (result != 0) {
        TRACE("Unable to bind results: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    result = mysql_stmt_store_result(stmt);
    if (result != 0) {
        TRACE("Unable to buffer results: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    //
    // Process result set
    //

    for (;;) {
        ZeroMemory(&groupFile, sizeof(GROUPFILE));
        if (mysql_stmt_fetch(stmt) != 0) {
            break;
        }

        //
        // If ioFTPD fails to open a group at start-up, the group will still
        // have an entry in the GroupIdTable file but ioFTPD considers them
        // gone. The call to GroupExists() is done to check for this.
        //
        if (!NameListRemove(&list, groupName) || !GroupExists(groupName)) {
            TRACE("GroupSyncFull: Create(%s)", groupName);

            // Group does not exist locally, create it.
            error = GroupEventCreate(groupName, &groupFile);
            if (error != ERROR_SUCCESS) {
                LOG_WARN("Unable to create group \"%s\" (error %lu).", groupName, error);
            }
        } else {
            TRACE("GroupSyncFull: Update(%s)", groupName);

            // Group already exists locally, update it.
            error = GroupEventUpdate(groupName, &groupFile);
            if (error != ERROR_SUCCESS) {
                LOG_WARN("Unable to update group \"%s\" (error %lu).", groupName, error);
            }
        }
    }

    mysql_free_result(metadata);

    //
    // Delete remaining groups
    //

    for (i = 0; i < list.count; i++) {
        entry = list.array[i];
        TRACE("GroupSyncFull: Delete(%s,%d)", entry->name, entry->id);

        // Group does not exist on database, delete it.
        error = GroupEventDeleteEx(entry->name, entry->id);
        if (error != ERROR_SUCCESS) {
            LOG_WARN("Unable to delete group \"%s\" (error %lu).", entry->name, error);
        }
    }

    NameListDestroy(&list);

    return ERROR_SUCCESS;
}
Exemple #28
0
static int test_view(MYSQL *mysql)
{
  MYSQL_STMT *stmt;
  int rc, i;
  MYSQL_BIND      my_bind[1];
  char            str_data[50];
  ulong           length = 0L;
  long            is_null = 0L;
  const char *query=
    "SELECT COUNT(*) FROM v1 WHERE SERVERNAME=?";

  rc = mysql_query(mysql, "DROP TABLE IF EXISTS t1,t2,t3,v1");
  check_mysql_rc(rc, mysql);

  rc = mysql_query(mysql, "DROP VIEW IF EXISTS v1,t1,t2,t3");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql,"CREATE TABLE t1 ("
                        " SERVERGRP varchar(20) NOT NULL default '', "
                        " DBINSTANCE varchar(20) NOT NULL default '', "
                        " PRIMARY KEY  (SERVERGRP)) "
                        " CHARSET=latin1 collate=latin1_bin");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql,"CREATE TABLE t2 ("
                        " SERVERNAME varchar(20) NOT NULL, "
                        " SERVERGRP varchar(20) NOT NULL, "
                        " PRIMARY KEY (SERVERNAME)) "
                        " CHARSET=latin1 COLLATE latin1_bin");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql,
                  "CREATE TABLE t3 ("
                  " SERVERGRP varchar(20) BINARY NOT NULL, "
                  " TABNAME varchar(30) NOT NULL, MAPSTATE char(1) NOT NULL, "
                  " ACTSTATE char(1) NOT NULL , "
                  " LOCAL_NAME varchar(30) NOT NULL, "
                  " CHG_DATE varchar(8) NOT NULL default '00000000', "
                  " CHG_TIME varchar(6) NOT NULL default '000000', "
                  " MXUSER varchar(12) NOT NULL default '', "
                  " PRIMARY KEY (SERVERGRP, TABNAME, MAPSTATE, ACTSTATE, "
                  " LOCAL_NAME)) CHARSET=latin1 COLLATE latin1_bin");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql,"CREATE VIEW v1 AS select sql_no_cache"
                  " T0001.SERVERNAME AS SERVERNAME, T0003.TABNAME AS"
                  " TABNAME,T0003.LOCAL_NAME AS LOCAL_NAME,T0002.DBINSTANCE AS"
                  " DBINSTANCE from t2 T0001 join t1 T0002 join t3 T0003 where"
                  " ((T0002.SERVERGRP = T0001.SERVERGRP) and"
                  " (T0002.SERVERGRP = T0003.SERVERGRP)"
                  " and (T0003.MAPSTATE = _latin1'A') and"
                  " (T0003.ACTSTATE = _latin1' '))");
  check_mysql_rc(rc, mysql);

  stmt= mysql_stmt_init(mysql);
  rc= mysql_stmt_prepare(stmt, query, strlen(query));
  check_stmt_rc(rc, stmt);

  strcpy(str_data, "TEST");
  memset(my_bind, '\0', sizeof(MYSQL_BIND));
  my_bind[0].buffer_type= MYSQL_TYPE_STRING;
  my_bind[0].buffer= (char *)&str_data;
  my_bind[0].buffer_length= 50;
  my_bind[0].length= &length;
  length= 4;
  my_bind[0].is_null= (char*)&is_null;
  rc= mysql_stmt_bind_param(stmt, my_bind);
  check_stmt_rc(rc, stmt);

  for (i= 0; i < 3; i++)
  {
    int rowcount= 0;

    rc= mysql_stmt_execute(stmt);
    check_stmt_rc(rc, stmt);

    while (mysql_stmt_fetch(stmt) != MYSQL_NO_DATA)
      rowcount++; 
    FAIL_IF(rowcount != 1, "Expected 1 row");
  }
  mysql_stmt_close(stmt);

  rc= mysql_query(mysql, "DROP TABLE t1,t2,t3");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql, "DROP VIEW v1");
  check_mysql_rc(rc, mysql);

  return OK;
}
Exemple #29
0
static DWORD GroupSyncIncrUpdates(DB_CONTEXT *db, SYNC_CONTEXT *sync)
{
    CHAR        *query;
    CHAR        groupName[_MAX_NAME + 1];
    DWORD       error;
    GROUPFILE   groupFile;
    INT         result;
    MYSQL_BIND  bindInput[2];
    MYSQL_BIND  bindOutput[5];
    MYSQL_RES   *metadata;
    MYSQL_STMT  *stmt;

    ASSERT(db != NULL);
    ASSERT(sync != NULL);

    //
    // Prepare statement and bind parameters
    //

    stmt = db->stmt[7];

    query = "SELECT name, description, slots, users, vfsfile"
            "  FROM io_group"
            "  WHERE updated BETWEEN ? AND ?";

    result = mysql_stmt_prepare(stmt, query, strlen(query));
    if (result != 0) {
        TRACE("Unable to prepare statement: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    DB_CHECK_PARAMS(bindInput, stmt);
    ZeroMemory(&bindInput, sizeof(bindInput));

    bindInput[0].buffer_type = MYSQL_TYPE_LONG;
    bindInput[0].buffer      = &sync->prevUpdate;
    bindInput[0].is_unsigned = TRUE;

    bindInput[1].buffer_type = MYSQL_TYPE_LONG;
    bindInput[1].buffer      = &sync->currUpdate;
    bindInput[1].is_unsigned = TRUE;

    result = mysql_stmt_bind_param(stmt, bindInput);
    if (result != 0) {
        TRACE("Unable to bind parameters: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    metadata = mysql_stmt_result_metadata(stmt);
    if (metadata == NULL) {
        TRACE("Unable to prepare statement: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    //
    // Execute prepared statement
    //

    result = mysql_stmt_execute(stmt);
    if (result != 0) {
        LOG_ERROR("Unable to execute statement: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    //
    // Bind and fetch results
    //

    DB_CHECK_RESULTS(bindOutput, metadata);
    ZeroMemory(&bindOutput, sizeof(bindOutput));

    bindOutput[0].buffer_type   = MYSQL_TYPE_STRING;
    bindOutput[0].buffer        = groupName;
    bindOutput[0].buffer_length = sizeof(groupName);

    bindOutput[1].buffer_type   = MYSQL_TYPE_STRING;
    bindOutput[1].buffer        = groupFile.szDescription;
    bindOutput[1].buffer_length = sizeof(groupFile.szDescription);

    bindOutput[2].buffer_type   = MYSQL_TYPE_BLOB;
    bindOutput[2].buffer        = groupFile.Slots;
    bindOutput[2].buffer_length = sizeof(groupFile.Slots);

    bindOutput[3].buffer_type   = MYSQL_TYPE_LONG;
    bindOutput[3].buffer        = &groupFile.Users;

    bindOutput[4].buffer_type   = MYSQL_TYPE_STRING;
    bindOutput[4].buffer        = groupFile.szVfsFile;
    bindOutput[4].buffer_length = sizeof(groupFile.szVfsFile);

    result = mysql_stmt_bind_result(stmt, bindOutput);
    if (result != 0) {
        TRACE("Unable to bind results: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    result = mysql_stmt_store_result(stmt);
    if (result != 0) {
        TRACE("Unable to buffer results: %s", mysql_stmt_error(stmt));
        return DbMapErrorFromStmt(stmt);
    }

    //
    // Process result set
    //

    for (;;) {
        ZeroMemory(&groupFile, sizeof(GROUPFILE));
        if (mysql_stmt_fetch(stmt) != 0) {
            break;
        }
        TRACE("GroupSyncIncr: Update(%s)", groupName);

        error = GroupEventUpdate(groupName, &groupFile);
        if (error != ERROR_SUCCESS) {
            LOG_WARN("Unable to update group \"%s\" (error %lu).", groupName, error);
        }
    }

    mysql_free_result(metadata);

    return ERROR_SUCCESS;
}
Exemple #30
0
static int test_view_insert(MYSQL *mysql)
{
  MYSQL_STMT *insert_stmt, *select_stmt;
  int rc, i;
  MYSQL_BIND      my_bind[1];
  int             my_val = 0;
  ulong           my_length = 0L;
  long            my_null = 0L;
  const char *query=
    "insert into v1 values (?)";

  rc = mysql_query(mysql, "DROP TABLE IF EXISTS t1,v1");
  check_mysql_rc(rc, mysql);
  rc = mysql_query(mysql, "DROP VIEW IF EXISTS t1,v1");
  check_mysql_rc(rc, mysql);

  rc= mysql_query(mysql,"create table t1 (a int, primary key (a))");
  check_mysql_rc(rc, mysql);

  rc= mysql_query(mysql, "create view v1 as select a from t1 where a>=1");
  check_mysql_rc(rc, mysql);

  insert_stmt= mysql_stmt_init(mysql);
  rc= mysql_stmt_prepare(insert_stmt, query, strlen(query));
  check_stmt_rc(rc, insert_stmt);
  query= "select * from t1";
  select_stmt= mysql_stmt_init(mysql);
  rc= mysql_stmt_prepare(select_stmt, query, strlen(query));
  check_stmt_rc(rc, select_stmt);

  memset(my_bind, '\0', sizeof(MYSQL_BIND));
  my_bind[0].buffer_type = MYSQL_TYPE_LONG;
  my_bind[0].buffer = (char *)&my_val;
  my_bind[0].length = &my_length;
  my_bind[0].is_null = (char*)&my_null;
  rc= mysql_stmt_bind_param(insert_stmt, my_bind);
  check_stmt_rc(rc, select_stmt);

  for (i= 0; i < 3; i++)
  {
    int rowcount= 0;
    my_val= i;

    rc= mysql_stmt_execute(insert_stmt);
    check_stmt_rc(rc, insert_stmt);;

    rc= mysql_stmt_execute(select_stmt);
    check_stmt_rc(rc, select_stmt);;
    while (mysql_stmt_fetch(select_stmt) != MYSQL_NO_DATA)
      rowcount++;
    FAIL_UNLESS((i+1) == rowcount, "rowcount != i+1");
  }
  mysql_stmt_close(insert_stmt);
  mysql_stmt_close(select_stmt);

  rc= mysql_query(mysql, "DROP VIEW v1");
  check_mysql_rc(rc, mysql);
  rc= mysql_query(mysql, "DROP TABLE t1");
  check_mysql_rc(rc, mysql);

  return OK;
}