void CNetworkStringTable::TriggerCallbacks( int tick_ack )
{
	if ( m_changeFunc == NULL )
		return;

	COM_TimestampedLog( "Change(%s):Start", GetTableName() );

	int count = m_pItems->Count();

	for ( int i = 0; i < count; i++ )
	{
		CNetworkStringTableItem *pItem = &m_pItems->Element( i );

		// mirror is up to date
		if ( pItem->GetTickChanged() <= tick_ack )
			continue;

		int userDataSize;
		const void *pUserData = pItem->GetUserData( &userDataSize );

		// fire the callback function
		( *m_changeFunc )( m_pObject, this, i, GetString( i ), pUserData );
	}

	COM_TimestampedLog( "Change(%s):End", GetTableName() );
}
static void s_ResetConnection(void)
{
    s_Conn->Connect();
    CQuery query(s_Conn->NewQuery());

    // Create a test table ...
    string sql;

    sql  = " CREATE TABLE " + GetTableName() + "( \n";
    sql += "    id NUMERIC(18, 0) IDENTITY NOT NULL, \n";
    sql += "    int_field INT NULL, \n";
    sql += "    vc1000_field VARCHAR(1000) NULL, \n";
    sql += "    text_field TEXT NULL, \n";
    sql += "    image_field IMAGE NULL \n";
    sql += " )";

    // Create the table
    query.SetSql(sql);
    query.Execute();
    query.RequireRowCount(0);
    query.VerifyDone(CQuery::eAllResultSets);

    sql  = " CREATE UNIQUE INDEX #ind01 ON " + GetTableName() + "( id ) \n";

    // Create an index
    query.SetSql(sql);
    query.Execute();
    query.RequireRowCount(0);
    query.VerifyDone(CQuery::eAllResultSets);

    sql  = " CREATE TABLE #dbapi_bcp_table2 ( \n";
    sql += "    id INT NULL, \n";
    // Identity won't work with bulk insert ...
    // sql += "    id NUMERIC(18, 0) IDENTITY NOT NULL, \n";
    sql += "    int_field INT NULL, \n";
    sql += "    vc1000_field VARCHAR(1000) NULL, \n";
    sql += "    text_field TEXT NULL \n";
    sql += " )";

    query.SetSql(sql);
    query.Execute();
    query.RequireRowCount(0);
    query.VerifyDone(CQuery::eAllResultSets);

    sql  = " CREATE TABLE #test_unicode_table ( \n";
    sql += "    id NUMERIC(18, 0) IDENTITY NOT NULL, \n";
    sql += "    nvc255_field NVARCHAR(255) NULL \n";
//        sql += "    nvc255_field VARCHAR(255) NULL \n";
    sql += " )";

    // Create table
    query.SetSql(sql);
    query.Execute();
    query.RequireRowCount(0);
    query.VerifyDone(CQuery::eAllResultSets);
}
TCHAR * OdbcRecordset::Read(bool bAllowEmptyTable /*= false*/)
{
	static TCHAR szError[128] = {0};

	// Build statement
	tstring szSQL = _T("SELECT ");
	tstring szWhereClause = GetWhereClause();

	szSQL += GetColumns();
	szSQL += _T(" FROM ");
	szSQL += GetTableName();

	// Do we have a where clause? Include it.
	if (!szWhereClause.empty())
	{
		szSQL += _T(" WHERE ");
		szSQL += szWhereClause;
	}

	// Attempt to execute the statement.
	if (!_dbCommand->Execute(szSQL))
		return _dbCommand->GetError();

	// Does the table have any rows?
	// Make sure we allow for tables that can be empty.
	if (!_dbCommand->hasData())
	{
		if (bAllowEmptyTable)
			return nullptr;

		_stprintf(szError, _T("%s la tabla esta vacia."), GetTableName().c_str());
		return szError;
	}

	do
	{
		// This extra result/check potentially slows things down. 
		// It's also not very informative, so this could really use a bit of a rewrite
		// to better allow for this scenario.
		if (!Fetch())
		{
			_stprintf(szError, _T("No se han podido selecionar columnas en la tabla %s."), GetTableName().c_str());
			return szError;
		}
	} while (_dbCommand->MoveNext());

	return nullptr;
}
Esempio n. 4
0
void SimpleDBStorage::Load(void)
{
    MSqlQuery query(MSqlQuery::InitCon());
    MSqlBindings bindings;
    query.prepare(
        "SELECT CAST(" + GetColumnName() + " AS CHAR)"
        " FROM " + GetTableName() +
        " WHERE " + GetWhereClause(bindings));
    query.bindValues(bindings);

    if (!query.exec() || !query.isActive())
    {
        MythDB::DBError("SimpleDBStorage::Load()", query);
    }
    else if (query.next())
    {
        QString result = query.value(0).toString();
        // a 'NULL' QVariant does not get converted to a 'NULL' QString
        if (!query.value(0).isNull())
        {
            initval = result;
            user->SetDBValue(result);
        }
    }
}
Esempio n. 5
0
const std::string InsertStatement::GetInfo(int num_indent) const {
  std::ostringstream os;
  os << StringUtil::Indent(num_indent) << "InsertStatement\n";
  os << StringUtil::Indent(num_indent + 1) << GetTableName() << std::endl;
  if (!columns.empty()) {
    os << StringUtil::Indent(num_indent + 1) << "-> Columns\n";
    for (auto &col_name : columns) {
      os << StringUtil::Indent(num_indent + 2) << col_name << std::endl;
    }
  }
  switch (type) {
    case InsertType::VALUES:
      os << StringUtil::Indent(num_indent + 1) << "-> Values\n";
      for (auto &value_item : insert_values) {
        // TODO this is a debugging method which is currently unused.
        for (auto &expr : value_item) {
          os << expr.get()->GetInfo(num_indent + 2) << std::endl;
        }
      }
      break;
    case InsertType::SELECT:
      os << select.get()->GetInfo(num_indent + 1);
      break;
    default:
      break;
  }
  std::string info = os.str();
  StringUtil::RTrim(info);
  return info;
}
Esempio n. 6
0
int UPnpCDSExtension::GetCount( const QString &sColumn, const QString &sKey )
{
    int nCount = 0;

    MSqlQuery query(MSqlQuery::InitCon());

    if (query.isConnected())
    {
        QString sSQL = QString("SELECT count( %1 ) FROM %2")
                       .arg( sColumn ).arg( GetTableName( sColumn ) );

        if ( sKey.length() )
            sSQL += " WHERE " + sColumn + " = :KEY";

        query.prepare( sSQL );
        if ( sKey.length() )
            query.bindValue( ":KEY", sKey );

        if (query.exec() && query.next())
        {
            nCount = query.value(0).toInt();
        }
        VERBOSE(VB_UPNP+VB_EXTRA, "UPnpCDSExtension::GetCount() - " +
                                  sSQL + " = " + QString::number(nCount));
    }

    return( nCount );
}
Esempio n. 7
0
		VirtualDBFVirtualTable::VirtualDBFVirtualTable(
			const boost::filesystem::path& path,
			const std::string& codePage
		):	SQLiteVirtualTable(
			GetTableName(path),
			"VirtualDBF(\"" + replace_all_copy(path.file_string(), "\\", "\\\\") + "\"," + codePage + ")"
		)
		{}
		VirtualShapeVirtualTable::VirtualShapeVirtualTable(
			const boost::filesystem::path& path,
			const std::string& codePage,
			CoordinatesSystem::SRID srid
		):	SQLiteVirtualTable(
			GetTableName(path),
			"VirtualShape(\"" + replace_all_copy(change_extension(path, string()).file_string(), "\\", "\\\\") + "\"," + codePage + "," + lexical_cast<string>(srid) + ")"
		)
		{}
Esempio n. 9
0
// FIXME: Should remove when the simple_optimizer tears down
//  Initializes the update plan without adding any child nodes and
//  retrieves column ids for the child scan plan.
void UpdatePlan::BuildInitialUpdatePlan(
    const parser::UpdateStatement *parse_tree, std::vector<oid_t> &column_ids) {
  LOG_TRACE("Creating an Update Plan");
  auto t_ref = parse_tree->table;
  auto table_name = std::string(t_ref->GetTableName());
  auto database_name = t_ref->GetDatabaseName();
  LOG_TRACE("Update database %s table %s", database_name, table_name.c_str());
  target_table_ = catalog::Catalog::GetInstance()->GetTableWithName(
      database_name, table_name);
  PL_ASSERT(target_table_ != nullptr);

  for (auto update_clause : *parse_tree->updates) {
    updates_.push_back(update_clause->Copy());
  }
  TargetList tlist;
  DirectMapList dmlist;
  oid_t col_id;
  auto schema = target_table_->GetSchema();

  for (auto update : updates_) {
    // get oid_t of the column and push it to the vector;
    col_id = schema->GetColumnID(std::string(update->column));
    column_ids.push_back(col_id);
    auto *update_expr = update->value->Copy();
    expression::ExpressionUtil::TransformExpression(target_table_->GetSchema(),
                                                    update_expr);

    planner::DerivedAttribute attribute{update_expr};
    attribute.attribute_info.name = update->column;
    tlist.emplace_back(col_id, attribute);
  }

  auto &schema_columns = schema->GetColumns();
  for (uint i = 0; i < schema_columns.size(); i++) {
    bool is_in_target_list = false;
    for (auto col_id : column_ids) {
      if (schema_columns[i].column_name == schema_columns[col_id].column_name) {
        is_in_target_list = true;
        break;
      }
    }
    if (is_in_target_list == false)
      dmlist.emplace_back(i, std::pair<oid_t, oid_t>(0, i));
  }

  std::unique_ptr<const planner::ProjectInfo> project_info(
      new planner::ProjectInfo(std::move(tlist), std::move(dmlist)));
  project_info_ = std::move(project_info);

  if (parse_tree->where != nullptr)
    where_ = parse_tree->where->Copy();
  else
    where_ = nullptr;
  expression::ExpressionUtil::TransformExpression(target_table_->GetSchema(),
                                                  where_);
}
Esempio n. 10
0
int UPnpCDSExtension::GetDistinctCount( UPnpCDSRootInfo *pInfo )
{
    int nCount = 0;

    if ((pInfo == NULL) || (pInfo->column == NULL))
        return 0;

    MSqlQuery query(MSqlQuery::InitCon());

    if (query.isConnected())
    {
        // Note: Tried to use Bind, however it would not allow me to use it
        //       for column & table names

        QString sSQL;

        if (strncmp( pInfo->column, "*", 1) == 0)
        {
            sSQL = QString( "SELECT count( %1 ) FROM %2" )
                      .arg( pInfo->column )
                      .arg( GetTableName( pInfo->column ));
        }
        else
        {
            sSQL = QString( "SELECT count( DISTINCT %1 ) FROM %2" )
                      .arg( pInfo->column )
                      .arg( GetTableName( pInfo->column ) );
        }

        query.prepare( sSQL );
        query.exec();

        if (query.size() > 0)
        {
            query.next();

            nCount = query.value(0).toInt();
        }
    }

    return( nCount );
}
//---------------------------------------------------------------------------
int TServerModeDemoDataDM::GetRecordsCount()
{
  ADQuery->Active = false;
  String ASQL = "IF DB_ID(N\'%s\') IS NOT NULL AND OBJECT_ID(N\'%0:s.dbo.%1:s\') IS NOT NULL SELECT COUNT(*) FROM %0:s.dbo.%1:s; ELSE SELECT 0;";
  TVarRec args[2] = {GetDatabaseName(), GetTableName()};
  ADQuery->Open(Format(ASQL, args, 2));
  if (!ADQuery->Eof)
	return ADQuery->Fields->Fields[0]->AsInteger;
  else
	return 0;
}
Esempio n. 12
0
void kGUIDbTableDefWindowObj::WindowEvent(kGUIEvent *event)
{
    switch(event->GetEvent())
    {
    case EVENT_CLOSE:
        m_table.DeleteChildren();
        delete this;
        break;
    case EVENT_ADDROW:
    {
        unsigned int i;
        kGUIDbTableDefRowObj *row;
        bool exists;
        int index;
        kGUIString name;

        index=0;
        do
        {
            exists=false;
            if(!index)
                name.SetString("field");
            else
                name.Sprintf("field%d",index);
            ++index;

            /* check to see if this field name already exists */
            for(i=0; i<m_table.GetNumChildren(); ++i)
            {
                row=static_cast<kGUIDbTableDefRowObj *>(m_table.GetChild(i));
                if(!stricmp(row->GetName(),name.GetString()))
                {
                    exists=true;
                    break;
                }
            }
        } while(exists);

        //add field
        kGUIDbCommand *q;

        //ALTER TABLE t1 CHANGE oldname newname newtype;
        q=new kGUIDbCommand(GetDB(),"ALTER TABLE %s ADD COLUMN %s %s;",GetTableName(),name.GetString(),sqltypes[row->GetSqlTypeIndex(MYSQL_TYPE_LONG)].name);
        delete q;

        row=new kGUIDbTableDefRowObj(this,name.GetString(),row->GetSqlTypeIndex(MYSQL_TYPE_LONG),4,4,false,false);
        m_table.AddRow(row);
    }
    break;
    }
}
//---------------------------------------------------------------------------
bool TServerModeDemoDataDM::TableExists()
{
  String ASQL;
  ASQL = "IF DB_ID(N'" + GetDatabaseName() + "') IS NOT NULL AND OBJECT_ID(N'" + GetDatabaseName() +
	".dbo." + GetTableName() + "') IS NOT NULL" + sLineBreak +
	"  SELECT 1;" + sLineBreak +
	"ELSE" + sLineBreak +
	"  SELECT -1;";
  ADQuery->Active = False;
  ADQuery->Open(ASQL);
  if ((!ADQuery->Eof)&&(ADQuery->Fields->Fields[0]->AsInteger == 1))
	return true;
  else
	return false;
}
//---------------------------------------------------------------------------
void TServerModeDemoDataDM::CreateTable()
{
  String ASQL;
  ASQL = "IF OBJECT_ID(N\'" + GetDatabaseName() + ".dbo." + GetTableName() + "\') IS NULL" + sLineBreak +
	"CREATE TABLE \"dbo\".\"" + GetTableName() + "\"(" +
	" \"OID\" int IDENTITY(1,1) NOT NULL, \"Subject\" nvarchar(100) NULL," +
	"\"From\" nvarchar(100) NULL," +
	" \"Sent\" datetime NULL," +
	" \"Size\" bigint NULL," +
	" \"HasAttachment\" bit NULL," +
	" \"Priority\" int NULL," +
	" CONSTRAINT \"PK_' + ATableName + '\" PRIMARY KEY CLUSTERED" +
	"(" +
	" \"OID\" ASC" +
	")WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON \"PRIMARY\"" +
	") ON \"PRIMARY\";";
  ExecSQL(ASQL);
  ExecSQL("CREATE NONCLUSTERED INDEX iSubject_ServerModeGridTableDemo ON \"ServerModeGridTableDemo\" (\"Subject\");");
  ExecSQL("CREATE NONCLUSTERED INDEX iFrom_ServerModeGridTableDemo ON \"ServerModeGridTableDemo\" (\"From\");");
  ExecSQL("CREATE NONCLUSTERED INDEX iSent_ServerModeGridTableDemo ON \"ServerModeGridTableDemo\" (\"Sent\");");
  ExecSQL("CREATE NONCLUSTERED INDEX iSize_ServerModeGridTableDemo ON \"ServerModeGridTableDemo\" (\"Size\");");
  ExecSQL("CREATE NONCLUSTERED INDEX iHasAttachment_ServerModeGridTableDemo ON \"ServerModeGridTableDemo\" (\"HasAttachment\");");
  ExecSQL("CREATE NONCLUSTERED INDEX iPriority_ServerModeGridTableDemo ON \"ServerModeGridTableDemo\" (\"Priority\");");
}
Esempio n. 15
0
int UPnpCDSExtension::GetCount( const QString &sColumn, const QString &sKey )
{
    int nCount = 0;

    MSqlQuery query(MSqlQuery::InitCon());

    if (query.isConnected())
    {
        // Note: Tried to use Bind, however it would not allow me to use it
        //       for column & table names

        QString sSQL;

        if (sColumn == "*")
            sSQL = QString( "SELECT count( * ) FROM %1" ).arg( GetTableName( sColumn ) );
        else
            sSQL = QString( "SELECT count( %1 ) FROM %2 WHERE %3=:KEY" )
                      .arg( sColumn )
                      .arg( GetTableName( sColumn ) )
                      .arg( sColumn );

        query.prepare( sSQL );
        query.bindValue( ":KEY", sKey );
        query.exec();

        if (query.size() > 0)
        {
            query.next();

            nCount = query.value(0).toInt();
        }

    }

    return( nCount );
}
//---------------------------------------------------------------------------
String TServerModeDemoDataDM::GetInsertSQL(){
  String Users[] = { //17
	"Peter Dolan",
	"Ryan Fischer",
	"Richard Fisher",
	"Tom Hamlett",
	"Mark Hamilton",
	"Steve Lee",
	"Jimmy Lewis",
	"Jeffrey W McClain",
	"Andrew Miller",
	"Dave Murrel",
	"Bert Parkins",
	"Mike Roller",
	"Ray Shipman",
	"Paul Bailey",
	"Brad Barnes",
	"Carl Lucas",
	"Jerry Campbell"
  };
  String Subjects[] = { //21
	"Integrating Developer Express MasterView control into an Accounting System.",
    "Web Edition: Data Entry Page. There is an issue with date validation.",
	"Payables Due Calculator is ready for testing.",
	"Web Edition: Search Page is ready for testing.",
	"Main Menu: Duplicate Items. Somebody has to review all menu items in the system.",
	"Receivables Calculator. Where can I find the complete specs?",
	"Ledger: Inconsistency. Please fix it.",
	"Receivables Printing module is ready for testing.",
	"Screen Redraw. Somebody has to look at it.",
	"Email System. What library are we going to use?",
	"Cannot add new vendor. This module doesn""""t work!",
	"History. Will we track sales history in our system?",
	"Main Menu: Add a File menu. File menu item is missing.",
	"Currency Mask. The current currency mask in completely unusable.",
	"Drag & Drop operations are not available in the scheduler module.",
	"Data Import. What database types will we support?",
	"Reports. The list of incomplete reports.",
	"Data Archiving. We still don""""t have this features in our application.",
	"Email Attachments. Is it possible to add multiple attachments? I haven""""t found a way to do this.",
	"Check Register. We are using different paths for different modules.",
	"Data Export. Our customers asked us for export to Microsoft Excel"
  };
  String S = FormatDateTime("yyyymmdd hh:mm:ss", IncSecond(Now(), -Random(315360000)));
  return "INSERT INTO \"" + GetTableName() + "\" (\"Subject\", \"From\", \"Sent\", \"Size\", \"HasAttachment\", \"Priority\")" +
	"VALUES (\'" + Subjects[Random(21)] + "\',\'" + Users[Random(17)] + "\',\'" + S + "\'," +
	IntToStr(Random(100000)) + "," + IntToStr(Random(2)) + "," + IntToStr(Random(3)) + ");";
}
Esempio n. 17
0
/* @brief   evict table catalog object from cache
 * @param   table_oid
 * @return  true if table_oid is found and evicted; false if not found
 */
bool DatabaseCatalogObject::EvictTableObject(oid_t table_oid) {
  // find table name from table name cache
  auto it = table_objects_cache.find(table_oid);
  if (it == table_objects_cache.end()) {
    return false;  // table oid not found in cache
  }

  auto table_object = it->second;
  PELOTON_ASSERT(table_object);
  table_objects_cache.erase(it);
  // erase from table name cache
  std::string key =
      table_object->GetSchemaName() + "." + table_object->GetTableName();
  table_name_cache.erase(key);
  return true;
}
bool CNetworkStringTable::WriteBaselines( SVC_CreateStringTable &msg, char *msg_buffer, int msg_buffer_size )
{
	msg.m_DataOut.StartWriting( msg_buffer, msg_buffer_size );

	msg.m_bIsFilenames          = m_bIsFilenames;
	msg.m_szTableName			= GetTableName();
	msg.m_nMaxEntries			= GetMaxStrings();
	msg.m_nNumEntries			= GetNumStrings();
	msg.m_bUserDataFixedSize	= IsUserDataFixedSize();
	msg.m_nUserDataSize			= GetUserDataSize();
	msg.m_nUserDataSizeBits		= GetUserDataSizeBits();

	// tick = -1 ensures that all entries are updated = baseline
	int entries = WriteUpdate( NULL, msg.m_DataOut, -1 );

	return entries == msg.m_nNumEntries;
}
//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CNetworkStringTable::Dump( void )
{
	ConMsg( "Table %s\n", GetTableName() );
	ConMsg( "  %i/%i items\n", GetNumStrings(), GetMaxStrings() );
	for ( int i = 0; i < GetNumStrings() ; i++ )
	{
		ConMsg( "  %i : %s\n", i, GetString( i ) );
	}
	if ( m_pItemsClientSide )
	{
		for ( int i = 0; i < (int)m_pItemsClientSide->Count() ; i++ )
		{
			ConMsg( "  %i : %s\n", i, m_pItemsClientSide->String( i ) );
		}
	}
	ConMsg( "\n" );
}
Esempio n. 20
0
 TEST(SelectTests, BasicStatementTest) {
     auto statement = SQLParser::Instance().ParseStatement("select * from my_table;");
     auto select_statement = dynamic_cast<SelectStatement*>(statement.get());
     ASSERT_EQ(select_statement->GetTableName(), "my_table");
 }
Esempio n. 21
0
const char* FeatureClass::GetName ()
{
	return GetTableName();
}
Esempio n. 22
0
void SimpleDBStorage::Save(void)
{
    Save(GetTableName());
}
//-----------------------------------------------------------------------------
// Purpose: 
// Input  : *value - 
// Output : int
//-----------------------------------------------------------------------------
int CNetworkStringTable::AddString( bool bIsServer, const char *string, int length /*= -1*/, const void *userdata /*= NULL*/ )
{
	bool bHasChanged;
	CNetworkStringTableItem *item;
	
	if ( !string )
	{
		Assert( string );
		ConMsg( "Warning:  Can't add NULL string to table %s\n", GetTableName() );
		return INVALID_STRING_INDEX;
	}

#ifdef _DEBUG
	if ( m_bLocked )
	{
		DevMsg("Warning! CNetworkStringTable::AddString: adding '%s' while locked.\n", string );
	}
#endif

	int i = m_pItems->Find( string );
	if ( !bIsServer )
	{
		if ( m_pItems->IsValidIndex( i ) && !m_pItemsClientSide )
		{
			bIsServer = true;
		}
	}

	if ( !bIsServer && m_pItemsClientSide )
	{
		i = m_pItemsClientSide->Find( string );

		if ( !m_pItemsClientSide->IsValidIndex( i ) )
		{
			// not in list yet, create it now
			if ( m_pItemsClientSide->Count() >= (unsigned int)GetMaxStrings() )
			{
				// Too many strings, FIXME: Print warning message
				ConMsg( "Warning:  Table %s is full, can't add %s\n", GetTableName(), string );
				return INVALID_STRING_INDEX;
			}

			// create new item
			{
			MEM_ALLOC_CREDIT();
			i = m_pItemsClientSide->Insert( string );
			}

			item = &m_pItemsClientSide->Element( i );

			// set changed ticks

			item->m_nTickChanged = m_nTickCount;

	#ifndef	SHARED_NET_STRING_TABLES
			item->m_nTickCreated = m_nTickCount;

			if ( m_bChangeHistoryEnabled )
			{
				item->EnableChangeHistory();
			}
	#endif

			bHasChanged = true;
		}
		else
		{
			item = &m_pItemsClientSide->Element( i ); // item already exists
			bHasChanged = false;  // not changed yet
		}

		if ( length > -1 )
		{
			if ( item->SetUserData( m_nTickCount, length, userdata ) )
			{
				bHasChanged = true;
			}
		}

		if ( bHasChanged && !m_bChangeHistoryEnabled )
		{
			DataChanged( -i, item );
		}

		// Negate i for returning to client
		i = -i;
	}
	else
	{
		// See if it's already there
		i = m_pItems->Find( string );

		if ( !m_pItems->IsValidIndex( i ) )
		{
			// not in list yet, create it now
			if ( m_pItems->Count() >= (unsigned int)GetMaxStrings() )
			{
				// Too many strings, FIXME: Print warning message
				ConMsg( "Warning:  Table %s is full, can't add %s\n", GetTableName(), string );
				return INVALID_STRING_INDEX;
			}

			// create new item
			{
			MEM_ALLOC_CREDIT();
			i = m_pItems->Insert( string );
			}

			item = &m_pItems->Element( i );

			// set changed ticks

			item->m_nTickChanged = m_nTickCount;

	#ifndef	SHARED_NET_STRING_TABLES
			item->m_nTickCreated = m_nTickCount;

			if ( m_bChangeHistoryEnabled )
			{
				item->EnableChangeHistory();
			}
	#endif

			bHasChanged = true;
		}
		else
		{
			item = &m_pItems->Element( i ); // item already exists
			bHasChanged = false;  // not changed yet
		}

		if ( length > -1 )
		{
			if ( item->SetUserData( m_nTickCount, length, userdata ) )
			{
				bHasChanged = true;
			}
		}

		if ( bHasChanged && !m_bChangeHistoryEnabled )
		{
			DataChanged( i, item );
		}
	}

	return i;
}
DumpReturn PlayerDumpReader::LoadDump(std::string const& file, uint32 account, std::string name, ObjectGuid::LowType guid)
{
    uint32 charcount = AccountMgr::GetCharactersCount(account);
    if (charcount >= 10)
        return DUMP_TOO_MANY_CHARS;

    FILE* fin = fopen(file.c_str(), "r");
    if (!fin)
        return DUMP_FILE_OPEN_ERROR;

    char newguid[20], chraccount[20];

    // make sure the same guid doesn't already exist and is safe to use
    bool incHighest = true;
    if (guid && guid < sObjectMgr->GetGenerator<HighGuid::Player>().GetNextAfterMaxUsed())

    {
        PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHECK_GUID);
        stmt->setUInt32(0, guid);
        PreparedQueryResult result = CharacterDatabase.Query(stmt);

        if (result)
            guid = sObjectMgr->GetGenerator<HighGuid::Player>().GetNextAfterMaxUsed();                     // use first free if exists

        else
            incHighest = false;
    }
    else
        guid = sObjectMgr->GetGenerator<HighGuid::Player>().GetNextAfterMaxUsed();


    // normalize the name if specified and check if it exists
    if (!normalizePlayerName(name))
        name.clear();

    if (ObjectMgr::CheckPlayerName(name, sWorld->GetDefaultDbcLocale(), true) == CHAR_NAME_SUCCESS)
    {
        PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHECK_NAME);
        stmt->setString(0, name);
        PreparedQueryResult result = CharacterDatabase.Query(stmt);

        if (result)
            name.clear();                                       // use the one from the dump
    }
    else
        name.clear();

    // name encoded or empty

    snprintf(newguid, 20, "%u", guid);
    snprintf(chraccount, 20, "%u", account);

    DumpGuidMap items;
    DumpGuidMap mails;
    char buf[32000];
    memset(buf, 0, sizeof(buf));

    typedef std::map<uint32 /*old*/, uint32 /*new*/> PetIds;
    PetIds petIds;

    uint8 gender = GENDER_NONE;
    uint8 race = RACE_NONE;
    uint8 playerClass = 0;
    uint8 level = 1;

    ObjectGuid::LowType itemLowGuidOffset = sObjectMgr->GetGenerator<HighGuid::Item>().GetNextAfterMaxUsed();

    SQLTransaction trans = CharacterDatabase.BeginTransaction();
    while (!feof(fin))
    {
        if (!fgets(buf, 32000, fin))
        {
            if (feof(fin))
                break;
            ROLLBACK(DUMP_FILE_BROKEN);
        }

        std::string line; line.assign(buf);

        // skip empty strings
        size_t nw_pos = line.find_first_not_of(" \t\n\r\7");
        if (nw_pos == std::string::npos)
            continue;

        // skip logfile-side dump start notice, the important notes and dump end notices
        if ((line.substr(nw_pos, 16) == "== START DUMP ==") ||
            (line.substr(nw_pos, 15) == "IMPORTANT NOTE:") ||
            (line.substr(nw_pos, 14) == "== END DUMP =="))
            continue;

        // add required_ check
        /*
        if (line.substr(nw_pos, 41) == "UPDATE character_db_version SET required_")
        {
            if (!CharacterDatabase.Execute(line.c_str()))
                ROLLBACK(DUMP_FILE_BROKEN);

            continue;
        }
        */

        // determine table name and load type
        std::string tn = GetTableName(line);
        if (tn.empty())
        {
            TC_LOG_ERROR("misc", "LoadPlayerDump: Can't extract table name from line: '%s'!", line.c_str());
            ROLLBACK(DUMP_FILE_BROKEN);
        }

        DumpTableType type = DumpTableType(0);
        uint8 i;
        for (i = 0; i < DUMP_TABLE_COUNT; ++i)
        {
            if (tn == dumpTables[i].name)
            {
                type = dumpTables[i].type;
                break;
            }
        }

        if (i == DUMP_TABLE_COUNT)
        {
            TC_LOG_ERROR("misc", "LoadPlayerDump: Unknown table: '%s'!", tn.c_str());
            ROLLBACK(DUMP_FILE_BROKEN);
        }

        // change the data to server values
        switch (type)
        {
            case DTT_CHARACTER:
            {
                if (!ChangeNth(line, 1, newguid))           // characters.guid update
                    ROLLBACK(DUMP_FILE_BROKEN);

                if (!ChangeNth(line, 2, chraccount))        // characters.account update
                    ROLLBACK(DUMP_FILE_BROKEN);

                race = uint8(atoul(GetNth(line, 4).c_str()));
                playerClass = uint8(atoul(GetNth(line, 5).c_str()));
                gender = uint8(atoul(GetNth(line, 6).c_str()));
                level = uint8(atoul(GetNth(line, 7).c_str()));
                if (name.empty())
                {
                    // check if the original name already exists
                    name = GetNth(line, 3);

                    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHECK_NAME);
                    stmt->setString(0, name);
                    PreparedQueryResult result = CharacterDatabase.Query(stmt);

                    if (result)
                        if (!ChangeNth(line, 37, "1"))      // characters.at_login set to "rename on login"
                            ROLLBACK(DUMP_FILE_BROKEN);
                }
                else if (!ChangeNth(line, 3, name.c_str())) // characters.name
                    ROLLBACK(DUMP_FILE_BROKEN);

                const char null[5] = "NULL";
                if (!ChangeNth(line, 74, null))             // characters.deleteInfos_Account
                    ROLLBACK(DUMP_FILE_BROKEN);
                if (!ChangeNth(line, 75, null))             // characters.deleteInfos_Name
                    ROLLBACK(DUMP_FILE_BROKEN);
                if (!ChangeNth(line, 76, null))             // characters.deleteDate
                    ROLLBACK(DUMP_FILE_BROKEN);
                break;
            }
            case DTT_CHAR_TABLE:
            {
                if (!ChangeNth(line, 1, newguid))           // character_*.guid update
                    ROLLBACK(DUMP_FILE_BROKEN);
                break;
            }
            case DTT_EQSET_TABLE:
            {
                if (!ChangeNth(line, 1, newguid))
                    ROLLBACK(DUMP_FILE_BROKEN);             // character_equipmentsets.guid

                char newSetGuid[24];
                snprintf(newSetGuid, 24, UI64FMTD, sObjectMgr->GenerateEquipmentSetGuid());
                if (!ChangeNth(line, 2, newSetGuid))
                    ROLLBACK(DUMP_FILE_BROKEN);             // character_equipmentsets.setguid

                for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; ++slot)
                    if (!ChangeGuid(line, 7 + slot, items, itemLowGuidOffset, true))
                        ROLLBACK(DUMP_FILE_BROKEN);         // character_equipmentsets.item
                break;
            }
            case DTT_INVENTORY:
            {
                if (!ChangeNth(line, 1, newguid))           // character_inventory.guid update
                    ROLLBACK(DUMP_FILE_BROKEN);

                if (!ChangeGuid(line, 2, items, itemLowGuidOffset, true))
                    ROLLBACK(DUMP_FILE_BROKEN);             // character_inventory.bag update
                if (!ChangeGuid(line, 4, items, itemLowGuidOffset))
                    ROLLBACK(DUMP_FILE_BROKEN);             // character_inventory.item update
                break;
            }
            case DTT_MAIL:                                  // mail
            {
                if (!ChangeGuid(line, 1, mails, sObjectMgr->_mailId))
                    ROLLBACK(DUMP_FILE_BROKEN);             // mail.id update
                if (!ChangeNth(line, 6, newguid))           // mail.receiver update
                    ROLLBACK(DUMP_FILE_BROKEN);
                break;
            }
            case DTT_MAIL_ITEM:                             // mail_items
            {
                if (!ChangeGuid(line, 1, mails, sObjectMgr->_mailId))
                    ROLLBACK(DUMP_FILE_BROKEN);             // mail_items.id
                if (!ChangeGuid(line, 2, items, itemLowGuidOffset))
                    ROLLBACK(DUMP_FILE_BROKEN);             // mail_items.item_guid
                if (!ChangeNth(line, 3, newguid))           // mail_items.receiver
                    ROLLBACK(DUMP_FILE_BROKEN);
                break;
            }
            case DTT_ITEM:
            {
                // item, owner, data field:item, owner guid
                if (!ChangeGuid(line, 1, items, itemLowGuidOffset))
                   ROLLBACK(DUMP_FILE_BROKEN);              // item_instance.guid update
                if (!ChangeNth(line, 3, newguid))           // item_instance.owner_guid update
                    ROLLBACK(DUMP_FILE_BROKEN);
                break;
            }
            case DTT_ITEM_GIFT:
            {
                if (!ChangeNth(line, 1, newguid))           // character_gifts.guid update
                    ROLLBACK(DUMP_FILE_BROKEN);
                if (!ChangeGuid(line, 2, items, itemLowGuidOffset))
                    ROLLBACK(DUMP_FILE_BROKEN);             // character_gifts.item_guid update
                break;
            }
            case DTT_PET:
            {
                // store a map of old pet id to new inserted pet id for use by DTT_PET_TABLE tables
                std::string petIdStr = GetNth(line, 1);

                uint32 currentPetId = atoul(petIdStr.c_str());

                PetIds::const_iterator petIdsItr = petIds.find(currentPetId);
                if (petIdsItr != petIds.end())              // duplicate pets
                    ROLLBACK(DUMP_FILE_BROKEN);

                uint32 newPetId = sObjectMgr->GeneratePetNumber();
                petIds[currentPetId] = newPetId;

                if (!ChangeNth(line, 1, std::to_string(newPetId).c_str())) // character_pet.id update
                    ROLLBACK(DUMP_FILE_BROKEN);
                if (!ChangeNth(line, 3, newguid))           // character_pet.owner update
                    ROLLBACK(DUMP_FILE_BROKEN);

                break;
            }
            case DTT_PET_TABLE:                             // pet_aura, pet_spell, pet_spell_cooldown
            {
                std::string petIdStr = GetNth(line, 1);

                // lookup currpetid and match to new inserted pet id
                PetIds::const_iterator petIdsItr = petIds.find(atoul(petIdStr.c_str()));
                if (petIdsItr == petIds.end())              // couldn't find new inserted id
                    ROLLBACK(DUMP_FILE_BROKEN);

                if (!ChangeNth(line, 1, std::to_string(petIdsItr->second).c_str()))
                    ROLLBACK(DUMP_FILE_BROKEN);

                break;
            }
            default:
                TC_LOG_ERROR("misc", "Unknown dump table type: %u", type);
                break;
        }

        fixNULLfields(line);

        trans->Append(line.c_str());
    }

    CharacterDatabase.CommitTransaction(trans);

    // in case of name conflict player has to rename at login anyway
    sWorld->AddCharacterInfo(ObjectGuid(HighGuid::Player, guid), account, name, gender, race, playerClass, level);

    sObjectMgr->GetGenerator<HighGuid::Item>().Set(sObjectMgr->GetGenerator<HighGuid::Item>().GetNextAfterMaxUsed() + items.size());

    sObjectMgr->_mailId     += mails.size();

    if (incHighest)
        sObjectMgr->GetGenerator<HighGuid::Player>().Generate();


    fclose(fin);

    return DUMP_SUCCESS;
}
Esempio n. 25
0
BEGIN_NCBI_SCOPE

///////////////////////////////////////////////////////////////////////////////
BOOST_AUTO_TEST_CASE(Test_Procedure)
{
    try {
        // Test a regular IStatement with "exec"
        // Parameters are not allowed with this construction.
        {
            auto_ptr<IStatement> auto_stmt( GetConnection().GetStatement() );

            // Execute it first time ...
            auto_stmt->SendSql( "exec sp_databases" );
            while( auto_stmt->HasMoreResults() ) {
                if( auto_stmt->HasRows() ) {
                    auto_ptr<IResultSet> rs( auto_stmt->GetResultSet() );

                    switch ( rs->GetResultType() ) {
                    case eDB_RowResult:
                        while( rs->Next() ) {
                            // int col1 = rs->GetVariant(1).GetInt4();
                        }
                        break;
                    case eDB_ParamResult:
                        while( rs->Next() ) {
                            // int col1 = rs->GetVariant(1).GetInt4();
                        }
                        break;
                    case eDB_StatusResult:
                        while( rs->Next() ) {
                            int status = rs->GetVariant(1).GetInt4();
                            status = status;
                        }
                        break;
                    case eDB_ComputeResult:
                    case eDB_CursorResult:
                        break;
                    }
                }
            }

            // Execute it second time ...
            auto_stmt->SendSql( "exec sp_databases" );
            while( auto_stmt->HasMoreResults() ) {
                if( auto_stmt->HasRows() ) {
                    auto_ptr<IResultSet> rs( auto_stmt->GetResultSet() );

                    switch ( rs->GetResultType() ) {
                    case eDB_RowResult:
                        while( rs->Next() ) {
                            // int col1 = rs->GetVariant(1).GetInt4();
                        }
                        break;
                    case eDB_ParamResult:
                        while( rs->Next() ) {
                            // int col1 = rs->GetVariant(1).GetInt4();
                        }
                        break;
                    case eDB_StatusResult:
                        while( rs->Next() ) {
                            int status = rs->GetVariant(1).GetInt4();
                            status = status;
                        }
                        break;
                    case eDB_ComputeResult:
                    case eDB_CursorResult:
                        break;
                    }
                }
            }

            // Same as before but do not retrieve data ...
            auto_stmt->SendSql( "exec sp_databases" );
            auto_stmt->SendSql( "exec sp_databases" );
        }

        // Test ICallableStatement
        // No parameters at this time.
        {
            // Execute it first time ...
            auto_ptr<ICallableStatement> auto_stmt(
                GetConnection().GetCallableStatement("sp_databases")
            );
            auto_stmt->Execute();
            while(auto_stmt->HasMoreResults()) {
                if( auto_stmt->HasRows() ) {
                    auto_ptr<IResultSet> rs( auto_stmt->GetResultSet() );

                    switch( rs->GetResultType() ) {
                    case eDB_RowResult:
                        while(rs->Next()) {
                            // retrieve row results
                        }
                        break;
                    case eDB_ParamResult:
                        while(rs->Next()) {
                            // Retrieve parameter row
                        }
                        break;
                    default:
                        break;
                    }
                }
            }
            // Get status
            auto_stmt->GetReturnStatus();


            // Execute it second time ...
            auto_stmt.reset( GetConnection().GetCallableStatement("sp_databases") );
            auto_stmt->Execute();
            while(auto_stmt->HasMoreResults()) {
                if( auto_stmt->HasRows() ) {
                    auto_ptr<IResultSet> rs( auto_stmt->GetResultSet() );

                    switch( rs->GetResultType() ) {
                    case eDB_RowResult:
                        while(rs->Next()) {
                            // retrieve row results
                        }
                        break;
                    case eDB_ParamResult:
                        while(rs->Next()) {
                            // Retrieve parameter row
                        }
                        break;
                    default:
                        break;
                    }
                }
            }
            // Get status
            auto_stmt->GetReturnStatus();


            // Same as before but do not retrieve data ...
            auto_stmt.reset( GetConnection().GetCallableStatement("sp_databases") );
            auto_stmt->Execute();
            auto_stmt.reset( GetConnection().GetCallableStatement("sp_databases") );
            auto_stmt->Execute();
        }

        // Temporary test ...
        // !!! This is a bug ...
        if (false) {
            auto_ptr<IConnection> conn( GetDS().CreateConnection( CONN_OWNERSHIP ) );
            BOOST_CHECK( conn.get() != NULL );

            conn->Connect(
                "anyone",
                "allowed",
                "PUBSEQ_OS_LXA",
                ""
            );

            auto_ptr<ICallableStatement> auto_stmt(
                conn->GetCallableStatement("id_seqid4gi")
            );
            auto_stmt->SetParam( CVariant(1), "@gi" );
            auto_stmt->Execute();
            while(auto_stmt->HasMoreResults()) {
                if( auto_stmt->HasRows() ) {
                    auto_ptr<IResultSet> rs( auto_stmt->GetResultSet() );

                    switch( rs->GetResultType() ) {
                    case eDB_RowResult:
                        while(rs->Next()) {
                            // retrieve row results
                        }
                        break;
                    case eDB_ParamResult:
                        _ASSERT(false);
                        while(rs->Next()) {
                            // Retrieve parameter row
                        }
                        break;
                    default:
                        break;
                    }
                }
            }
            // Get status
            int status = auto_stmt->GetReturnStatus();
            status = status; // Get rid of warnings.
        }

        if (false) {
            const string query("[db_alias] is not null");

            auto_ptr<IConnection> conn( GetDS().CreateConnection( CONN_OWNERSHIP ) );
            BOOST_CHECK( conn.get() != NULL );

            conn->Connect(
                "*****",
                "******",
                "MSSQL31",
                "AlignDb_Info"
            );

            auto_ptr<ICallableStatement> auto_stmt(
                conn->PrepareCall("[dbo].[FindAttributesEx]")
            );
            auto_stmt->SetParam( CVariant(1), "@userid" );
            auto_stmt->SetParam( CVariant("ALIGNDB"), "@application" );
            auto_stmt->SetParam( CVariant("AlignDbMasterInfo"), "@classname" );
            // LongChar doesn't work.
            // auto_stmt->SetParam( CVariant(new CDB_LongChar(query.length(), query)), "@query" );
            // auto_stmt->SetParam( CVariant::LongChar(query.data(), query.length()), "@query" );
            auto_stmt->SetParam( CVariant(query), "@query" );
            auto_stmt->SetParam( CVariant(1), "@max_results" );

            auto_stmt->Execute();
            while(auto_stmt->HasMoreResults()) {
                if( auto_stmt->HasRows() ) {
                    auto_ptr<IResultSet> rs( auto_stmt->GetResultSet() );

                    switch( rs->GetResultType() ) {
                    case eDB_RowResult:
                        while(rs->Next()) {
                            // retrieve row results
                        }
                        break;
                    case eDB_ParamResult:
                        _ASSERT(false);
                        while(rs->Next()) {
                            // Retrieve parameter row
                        }
                        break;
                    default:
                        break;
                    }
                }
            }
            // Get status
            int status = auto_stmt->GetReturnStatus();
            status = status; // Get rid of warnings.
        }


        // Test returned recordset ...
        {
            // In case of MS SQL 2005 sp_databases returns empty result set.
            // It is not a bug. It is a difference in setiings for MS SQL
            // 2005.
            if (GetArgs().GetServerType() != CDBConnParams::eMSSqlServer) {
                int num = 0;
                // Execute it first time ...
                auto_ptr<ICallableStatement> auto_stmt(
                    GetConnection().GetCallableStatement("sp_databases")
                );

                auto_stmt->Execute();

                BOOST_CHECK(auto_stmt->HasMoreResults());
                BOOST_CHECK(auto_stmt->HasRows());
                auto_ptr<IResultSet> rs(auto_stmt->GetResultSet());
                BOOST_CHECK(rs.get() != NULL);

                while (rs->Next()) {
                    BOOST_CHECK(rs->GetVariant(1).GetString().size() > 0);
                    BOOST_CHECK(rs->GetVariant(2).GetInt4() > 0);
                    BOOST_CHECK_EQUAL(rs->GetVariant(3).IsNull(), true);
                    ++num;
                }

                BOOST_CHECK(num > 0);

                DumpResults(auto_stmt.get());
            }

            {
                int num = 0;
                auto_ptr<ICallableStatement> auto_stmt(
                    GetConnection().GetCallableStatement("sp_server_info")
                );

                auto_stmt->Execute();

                BOOST_CHECK(auto_stmt->HasMoreResults());
                BOOST_CHECK(auto_stmt->HasRows());
                auto_ptr<IResultSet> rs(auto_stmt->GetResultSet());
                BOOST_CHECK(rs.get() != NULL);

                while (rs->Next()) {
                    BOOST_CHECK(rs->GetVariant(1).GetInt4() > 0);
                    BOOST_CHECK(rs->GetVariant(2).GetString().size() > 0);
                    BOOST_CHECK(rs->GetVariant(3).GetString().size() > 0);
                    ++num;
                }

                BOOST_CHECK(num > 0);

                DumpResults(auto_stmt.get());
            }
        }

        // Test ICallableStatement
        // With parameters.
        {
            {
                auto_ptr<ICallableStatement> auto_stmt(
                    GetConnection().GetCallableStatement("sp_server_info")
                );

                // Set parameter to NULL ...
                auto_stmt->SetParam( CVariant(eDB_Int), "@attribute_id" );
                auto_stmt->Execute();

                if (GetArgs().GetServerType() == CDBConnParams::eSybaseSQLServer) {
                    BOOST_CHECK_EQUAL( size_t(30), GetNumOfRecords(auto_stmt) );
                } else {
                    BOOST_CHECK_EQUAL( size_t(29), GetNumOfRecords(auto_stmt) );
                }

                // Set parameter to 1 ...
                auto_stmt->SetParam( CVariant( Int4(1) ), "@attribute_id" );
                auto_stmt->Execute();

                BOOST_CHECK_EQUAL( size_t(1), GetNumOfRecords(auto_stmt) );
            }

            // NULL value with CVariant ...
            {
                auto_ptr<ICallableStatement> auto_stmt(
                    GetConnection().GetCallableStatement("sp_statistics")
                );

                auto_stmt->SetParam(CVariant((const char*) NULL), "@table_name");
                auto_stmt->Execute();
                DumpResults(auto_stmt.get());
            }

            // Doesn't work for some reason ...
            if (false) {
                // Execute it first time ...
                auto_ptr<ICallableStatement> auto_stmt(
                    GetConnection().GetCallableStatement("sp_statistics")
                );

                auto_stmt->SetParam(CVariant(GetTableName()), "@table_name");
                auto_stmt->Execute();

                {
                    BOOST_CHECK(auto_stmt->HasMoreResults());
                    BOOST_CHECK(auto_stmt->HasRows());
                    auto_ptr<IResultSet> rs(auto_stmt->GetResultSet());
                    BOOST_CHECK(rs.get() != NULL);

                    BOOST_CHECK(rs->Next());
                    DumpResults(auto_stmt.get());
                }

                // Execute it second time ...
                auto_stmt->SetParam(CVariant("#bulk_insert_table"), "@table_name");
                auto_stmt->Execute();

                {
                    BOOST_CHECK(auto_stmt->HasMoreResults());
                    BOOST_CHECK(auto_stmt->HasRows());
                    auto_ptr<IResultSet> rs(auto_stmt->GetResultSet());
                    BOOST_CHECK(rs.get() != NULL);

                    BOOST_CHECK(rs->Next());
                    DumpResults(auto_stmt.get());
                }
            }

            if (false) {
                auto_ptr<ICallableStatement> auto_stmt(
                    GetConnection().GetCallableStatement("DBAPI_Sample..TestBigIntProc")
                );

                auto_stmt->SetParam(CVariant(Int8(1234567890)), "@num");
                auto_stmt->ExecuteUpdate();
            }
        }

        // Test output parameters ...
        if (false) {
            CRef<CDB_UserHandler_Diag> handler(new  CDB_UserHandler_Diag());
            I_DriverContext* drv_context = GetDS().GetDriverContext();

            drv_context->PushDefConnMsgHandler(handler);

            auto_ptr<ICallableStatement> auto_stmt(
                GetConnection().GetCallableStatement("DBAPI_Sample..SampleProc3")
            );
            auto_stmt->SetParam(CVariant(1), "@id");
            auto_stmt->SetParam(CVariant(2.0), "@f");
            auto_stmt->SetOutputParam(CVariant(eDB_Int), "@o");

            auto_stmt->Execute();
            //         auto_stmt->SendSql( "exec DBAPI_Sample..TestProc4 @test_out output" );

            while(auto_stmt->HasMoreResults()) {
                if( auto_stmt->HasRows() ) {
                    auto_ptr<IResultSet> rs( auto_stmt->GetResultSet() );

                    switch( rs->GetResultType() ) {
                    case eDB_RowResult:
                        while(rs->Next()) {
                            // retrieve row results
                        }
                        break;
                    case eDB_ParamResult:
                        BOOST_CHECK(rs->Next());
                        NcbiCout << "Output param: "
                                 << rs->GetVariant(1).GetInt4()
                                 << endl;
                        break;
                    case eDB_ComputeResult:
                        break;
                    case eDB_StatusResult:
                        break;
                    case eDB_CursorResult:
                        break;
                    default:
                        break;
                    }
                }
            }

            //         BOOST_CHECK(auto_stmt->HasMoreResults());
            //         BOOST_CHECK(auto_stmt->HasRows());
            //         auto_ptr<IResultSet> rs(auto_stmt->GetResultSet());
            //         BOOST_CHECK(rs.get() != NULL);
            //
            //         while (rs->Next()) {
            //             BOOST_CHECK(rs->GetVariant(1).GetString().size() > 0);
            //             BOOST_CHECK(rs->GetVariant(2).GetInt4() > 0);
            //             BOOST_CHECK_EQUAL(rs->GetVariant(3).IsNull(), true);
            //             ++num;
            //         }
            //
            //         BOOST_CHECK(num > 0);

            DumpResults(auto_stmt.get());

            drv_context->PopDefConnMsgHandler(handler);
        }

        // Temporary test ...
        if (false) {
            auto_ptr<IConnection> conn( GetDS().CreateConnection( CONN_OWNERSHIP ) );
            BOOST_CHECK( conn.get() != NULL );

            conn->Connect(
                "anyone",
                "allowed",
                "",
                "GenomeHits"
            );

            auto_ptr<ICallableStatement> auto_stmt(
                conn->GetCallableStatement("NewSub")
            );
            auto_stmt->SetParam(CVariant("tsub2"), "@name");
            auto_stmt->SetParam(CVariant("tst"), "@center");
            auto_stmt->SetParam(CVariant("9606"), "@taxid");
            auto_stmt->SetParam(CVariant("H**o sapiens"), "@organism");
            auto_stmt->SetParam(CVariant(""), "@notes");
            auto_stmt->Execute();

            while(auto_stmt->HasMoreResults()) {
                if( auto_stmt->HasRows() ) {
                    auto_ptr<IResultSet> rs( auto_stmt->GetResultSet() );

                    switch( rs->GetResultType() ) {
                    case eDB_RowResult:
                        while(rs->Next()) {
                            // retrieve row results
                        }
                        break;
                    case eDB_ParamResult:
                        _ASSERT(false);
                        while(rs->Next()) {
                            // Retrieve parameter row
                        }
                        break;
                    default:
                        break;
                    }
                }
            }

            // Get status
            int status = auto_stmt->GetReturnStatus();
            status = status; // Get rid of warnings.
        }

        // Temporary test ...
        if (false && GetArgs().GetServerType() != CDBConnParams::eSybaseSQLServer) {
            auto_ptr<IConnection> conn( GetDS().CreateConnection( CONN_OWNERSHIP ) );
            BOOST_CHECK( conn.get() != NULL );

            conn->Connect(
                "pmcupdate",
                "*******",
                "PMC3QA",
                "PMC3QA"
            );

            auto_ptr<ICallableStatement> auto_stmt(
                conn->PrepareCall("id_new_id")
            );
            auto_stmt->SetParam(CVariant("tsub2"), "@IdName");

            auto_stmt->Execute();

            while(auto_stmt->HasMoreResults()) {
                if( auto_stmt->HasRows() ) {
                    auto_ptr<IResultSet> rs( auto_stmt->GetResultSet() );

                    switch( rs->GetResultType() ) {
                    case eDB_RowResult:
                        while(rs->Next()) {
                            // retrieve row results
                        }
                        break;
                    case eDB_ParamResult:
                        _ASSERT(false);
                        while(rs->Next()) {
                            // Retrieve parameter row
                        }
                        break;
                    default:
                        break;
                    }
                }
            }

            // Get status
            int status = auto_stmt->GetReturnStatus();
            status = status; // Get rid of warnings.
        }
    }
    catch(const CException& ex) {
        DBAPI_BOOST_FAIL(ex);
    }
}
int CNetworkStringTable::WriteUpdate( CBaseClient *client, bf_write &buf, int tick_ack )
{
	CUtlVector< StringHistoryEntry > history;

	int entriesUpdated = 0;
	int lastEntry = -1;

	int count = m_pItems->Count();

	for ( int i = 0; i < count; i++ )
	{
		CNetworkStringTableItem *p = &m_pItems->Element( i );

		// Client is up to date
		if ( p->GetTickChanged() <= tick_ack )
			continue;

		int nStartBit = buf.GetNumBitsWritten();

		// Write Entry index
		if ( (lastEntry+1) == i )
		{
			buf.WriteOneBit( 1 );
		}
		else
		{
			buf.WriteOneBit( 0 );
			buf.WriteUBitLong( i, m_nEntryBits );
		}

		// check if string can use older string as base eg "models/weapons/gun1" & "models/weapons/gun2"
		char const *pEntry = m_pItems->String( i );

		if ( p->GetTickCreated() > tick_ack )
		{
			// this item has just been created, send string itself
			buf.WriteOneBit( 1 );
			
			int substringsize = 0;
			int bestprevious = GetBestPreviousString( history, pEntry, substringsize );
			if ( bestprevious != -1 )
			{
				buf.WriteOneBit( 1 );
				buf.WriteUBitLong( bestprevious, 5 );	// history never has more than 32 entries
				buf.WriteUBitLong( substringsize, SUBSTRING_BITS );
				buf.WriteString( pEntry + substringsize );
			}
			else
			{
				buf.WriteOneBit( 0 );
				buf.WriteString( pEntry  );
			}
		}
		else
		{
			buf.WriteOneBit( 0 );
		}

		// Write the item's user data.
		int len;
		const void *pUserData = GetStringUserData( i, &len );
		if ( pUserData && len > 0 )
		{
			buf.WriteOneBit( 1 );

			if ( IsUserDataFixedSize() )
			{
				// Don't have to send length, it was sent as part of the table definition
				buf.WriteBits( pUserData, GetUserDataSizeBits() );
			}
			else
			{
				buf.WriteUBitLong( len, CNetworkStringTableItem::MAX_USERDATA_BITS );
				buf.WriteBits( pUserData, len*8 );
			}
		}
		else
		{
			buf.WriteOneBit( 0 );
		}

		// limit string history to 32 entries
		if ( history.Count() > 31 )
		{
			history.Remove( 0 );
		}

		// add string to string history
		StringHistoryEntry she;
		Q_strncpy( she.string, pEntry, sizeof( she.string ) );
		history.AddToTail( she );

		entriesUpdated++;
		lastEntry = i;

		if ( client && client->IsTracing() )
		{
			int nBits = buf.GetNumBitsWritten() - nStartBit;
			client->TraceNetworkMsg( nBits, " [%s] %d:%s ", GetTableName(), i, GetString( i ) );
		}
	}

	return entriesUpdated;
}
//-----------------------------------------------------------------------------
// Purpose: Parse string update
//-----------------------------------------------------------------------------
void CNetworkStringTable::ParseUpdate( bf_read &buf, int entries )
{
	int lastEntry = -1;

	CUtlVector< StringHistoryEntry > history;

	for (int i=0; i<entries; i++)
	{
		int entryIndex = lastEntry + 1;

		if ( !buf.ReadOneBit() )
		{
			entryIndex = buf.ReadUBitLong( GetEntryBits() );
		}

		lastEntry = entryIndex;
		
		if ( entryIndex < 0 || entryIndex >= GetMaxStrings() )
		{
			Host_Error( "Server sent bogus string index %i for table %s\n", entryIndex, GetTableName() );
		}

		const char *pEntry = NULL;
		char entry[ 1024 ]; 
		char substr[ 1024 ];

		if ( buf.ReadOneBit() )
		{
			bool substringcheck = buf.ReadOneBit() ? true : false;

			if ( substringcheck )
			{
				int index = buf.ReadUBitLong( 5 );
				int bytestocopy = buf.ReadUBitLong( SUBSTRING_BITS );
				Q_strncpy( entry, history[ index ].string, bytestocopy + 1 );
				buf.ReadString( substr, sizeof(substr) );
				Q_strncat( entry, substr, sizeof(entry), COPY_ALL_CHARACTERS );
			}
			else
			{
				buf.ReadString( entry, sizeof( entry ) );
			}

			pEntry = entry;
		}
		
		// Read in the user data.
		unsigned char tempbuf[ CNetworkStringTableItem::MAX_USERDATA_SIZE ];
		memset( tempbuf, 0, sizeof( tempbuf ) );
		const void *pUserData = NULL;
		int nBytes = 0;

		if ( buf.ReadOneBit() )
		{
			if ( IsUserDataFixedSize() )
			{
				// Don't need to read length, it's fixed length and the length was networked down already.
				nBytes = GetUserDataSize();
				Assert( nBytes > 0 );
				tempbuf[nBytes-1] = 0; // be safe, clear last byte
				buf.ReadBits( tempbuf, GetUserDataSizeBits() );
			}
			else
			{
				nBytes = buf.ReadUBitLong( CNetworkStringTableItem::MAX_USERDATA_BITS );
				ErrorIfNot( nBytes <= sizeof( tempbuf ),
					("CNetworkStringTableClient::ParseUpdate: message too large (%d bytes).", nBytes)
				);

				buf.ReadBytes( tempbuf, nBytes );
			}

			pUserData = tempbuf;
		}

		// Check if we are updating an old entry or adding a new one
		if ( entryIndex < GetNumStrings() )
		{
			SetStringUserData( entryIndex, nBytes, pUserData );
#ifdef _DEBUG
			if ( pEntry )
			{
				Assert( !Q_strcmp( pEntry, GetString( entryIndex ) ) ); // make sure string didn't change
			}
#endif
			pEntry = GetString( entryIndex ); // string didn't change
		}
		else
		{
			// Grow the table (entryindex must be the next empty slot)
			Assert( (entryIndex == GetNumStrings()) && (pEntry != NULL) );
				
			if ( pEntry == NULL )
			{
				Msg("CNetworkStringTable::ParseUpdate: NULL pEntry, table %s, index %i\n", GetTableName(), entryIndex );
				pEntry = "";// avoid crash because of NULL strings
			}

			AddString( true, pEntry, nBytes, pUserData );
		}

		if ( history.Count() > 31 )
		{
			history.Remove( 0 );
		}

		StringHistoryEntry she;
		Q_strncpy( she.string, pEntry, sizeof( she.string ) );
		history.AddToTail( she );
	}
}
Esempio n. 28
0
AnsiString _fastcall  TSaveObj::BuildSql(TDataSet* ADS)
{
    AnsiString FieldStr, ParamStr ="";
    int i =0;
    AnsiString FieldFmt,ParamFmt;
    AnsiString tmp;
    TDateTime atime;
    AnsiString tmpstr;
    DynamicArray <AnsiString> FPrimaryKeys;
    TUpdateStatus Status = ADS->UpdateStatus();
     Field_Info tmpfield ;
    if (Status == usInserted)
    {
       FieldFmt = ",%s";
       ParamFmt = ",%s";
       for (i = 0;i < FFieldInfoArr.Length;i++)
       {
             FieldStr = FieldStr + Format(FieldFmt,ARRAYOFCONST((FFieldInfoArr[i].FieldName)));
             if  (FFieldInfoArr[i].FieldType == ftString)
                  ParamStr = ParamStr + Format(ParamFmt,ARRAYOFCONST((QuotedStr(FFieldInfoArr[i].FieldValue))));
             else if (FFieldInfoArr[i].FieldType == ftDateTime)
             {

                  TryStrToDateTime(FFieldInfoArr[i].FieldValue,atime) ;
                  AnsiString tmp = cnDateFormat;
                  tmpstr=FormatDateTime("YYYYMMDD",atime);
                  ParamStr = ParamStr + Format(ParamFmt,ARRAYOFCONST(("to_date("+QuotedStr(tmpstr)+",'"+ tmp +"')")));

             }
             else
                  ParamStr = ParamStr + Format(ParamFmt,ARRAYOFCONST((FFieldInfoArr[i].FieldValue)));
       }
       FieldStr.Delete(1,1);
       ParamStr.Delete(1,1);
       tmp = Format("insert into %s(%s) values (%s)",ARRAYOFCONST((GetTableName(),FieldStr,ParamStr)));

    }
    else if (Status == usModified)
    {
       if (FFieldInfoArr.Length ==0)
          return "";
       //    throw Exception(Format("%s没有指定要更新的字段",ARRAYOFCONST((GetTableName()))));
       //得到更新的字段
        ParamFmt = ",%s=%s";
        for (i = 0;i < FFieldInfoArr.Length;i++)
        {
           if  (FFieldInfoArr[i].FieldType == ftString)
                ParamStr = ParamStr + Format(ParamFmt,ARRAYOFCONST((FFieldInfoArr[i].FieldName,QuotedStr(FFieldInfoArr[i].FieldValue))));
           else if (FFieldInfoArr[i].FieldType == ftDateTime)
           {
               TryStrToDateTime(FFieldInfoArr[i].FieldValue,atime) ;
               AnsiString tmp = cnDateFormat;
               tmpstr=FormatDateTime("YYYYMMDD",atime);
               ParamStr = ParamStr + Format(ParamFmt,ARRAYOFCONST((FFieldInfoArr[i].FieldName,"to_date("+QuotedStr(tmpstr)+",'"+tmp+"')")));

           }
           else
                ParamStr = ParamStr + Format(ParamFmt,ARRAYOFCONST((FFieldInfoArr[i].FieldName,FFieldInfoArr[i].FieldValue)));
        }
       //得到主键值
       ADS->Prior();
       Split(GetPrimaryKey(),FPrimaryKeys);
       FieldFmt =" and %s=%s";
       for (i = 0;i < FPrimaryKeys.Length;i++)
       {
           tmpfield = AssignFieldVal(ADS,FPrimaryKeys[i]);
           if  (tmpfield.FieldType == ftString)
              FieldStr = FieldStr + Format(FieldFmt,ARRAYOFCONST((FPrimaryKeys[i],QuotedStr(tmpfield.FieldValue))));
           else
              FieldStr = FieldStr + Format(FieldFmt,ARRAYOFCONST((FPrimaryKeys[i],tmpfield.FieldValue)));
       }
       ADS->Next();
       FieldStr.Delete(1,4);
       ParamStr.Delete(1,1);
       tmp = Format("update %s set %s where %s",ARRAYOFCONST((GetTableName(),ParamStr,FieldStr)));
    }
    else if (Status == usDeleted)
    {
       Split(GetPrimaryKey(),FPrimaryKeys);
       FieldFmt =" and %s=%s";
       for (i = 0;i < FPrimaryKeys.Length;i++)
       {
            tmpfield = AssignFieldVal(ADS,FPrimaryKeys[i]);
           if  (FFieldInfoArr[i].FieldType == ftString)
              FieldStr = FieldStr + Format(FieldFmt,ARRAYOFCONST((FPrimaryKeys[i],QuotedStr(tmpfield.FieldValue))));
           else
              FieldStr = FieldStr + Format(FieldFmt,ARRAYOFCONST((FPrimaryKeys[i],tmpfield.FieldValue)));
       }
       FieldStr.Delete(1,4);
       tmp = Format("delete from %s where %s",ARRAYOFCONST((GetTableName(),FieldStr)));
    }
    FPrimaryKeys.Length = 0;
    tmp = tmp;
    return tmp;
}