* object classes update

* first touch with update packets!
* added some code coloring
This commit is contained in:
False.Genesis 2007-02-02 23:08:28 +00:00
parent aa703e896f
commit f7415df6e3
24 changed files with 470 additions and 1514 deletions

View File

@ -72,6 +72,7 @@ DefScriptFunctionTable *DefScriptPackage::_GetFunctionTable(void) const
{"applypermissions",&DefScriptPackage::SCapplypermissions},
{"log",&DefScriptPackage::SClog},
{"logdetail",&DefScriptPackage::SClogdetail},
{"logerror",&DefScriptPackage::SClogerror},
{"logdebug",&DefScriptPackage::SClogdebug},
{"castspell", &DefScriptPackage::SCcastspell},

View File

@ -154,6 +154,7 @@ private:
bool SClog(CmdSet);
bool SClogdetail(CmdSet);
bool SClogdebug(CmdSet);
bool SClogerror(CmdSet);
bool SCcastspell(CmdSet);
// Own variable declarations

View File

@ -23,7 +23,7 @@ bool DefScriptPackage::SCpause(CmdSet Set){
bool DefScriptPackage::SCSendChatMessage(CmdSet Set){
if(!(((PseuInstance*)parentMethod)->GetWSession() && ((PseuInstance*)parentMethod)->GetWSession()->IsValid()))
{
log("Invalid Script call: SCSendChatMessage: WorldSession not valid");
logerror("Invalid Script call: SCSendChatMessage: WorldSession not valid");
return false;
}
std::stringstream ss;
@ -65,7 +65,7 @@ bool DefScriptPackage::SCemote(CmdSet Set){
return true;
if(!(((PseuInstance*)parentMethod)->GetWSession() && ((PseuInstance*)parentMethod)->GetWSession()->IsValid()))
{
log("Invalid Script call: SCEmote: WorldSession not valid");
logerror("Invalid Script call: SCEmote: WorldSession not valid");
return false;
}
uint32 id=atoi(Set.defaultarg.c_str());
@ -96,7 +96,7 @@ bool DefScriptPackage::SCjoinchannel(CmdSet Set){
return true;
if(!(((PseuInstance*)parentMethod)->GetWSession() && ((PseuInstance*)parentMethod)->GetWSession()->IsValid()))
{
log("Invalid Script call: SCjoinchannel: WorldSession not valid");
logerror("Invalid Script call: SCjoinchannel: WorldSession not valid");
return false;
}
((PseuInstance*)parentMethod)->GetWSession()->GetChannels()->Join(Set.defaultarg,Set.arg[0]);
@ -108,7 +108,7 @@ bool DefScriptPackage::SCleavechannel(CmdSet Set){
return true;
if(!(((PseuInstance*)parentMethod)->GetWSession() && ((PseuInstance*)parentMethod)->GetWSession()->IsValid()))
{
log("Invalid Script call: SCleavechannel: WorldSession not valid");
logerror("Invalid Script call: SCleavechannel: WorldSession not valid");
return false;
}
((PseuInstance*)parentMethod)->GetWSession()->GetChannels()->Leave(Set.defaultarg);
@ -155,13 +155,18 @@ bool DefScriptPackage::SClogdebug(CmdSet Set){
return true;
}
bool DefScriptPackage::SClogerror(CmdSet Set){
logerror(Set.defaultarg.c_str());
return true;
}
bool DefScriptPackage::SCcastspell(CmdSet Set)
{
if(Set.defaultarg.empty())
return true;
if(!(((PseuInstance*)parentMethod)->GetWSession() && ((PseuInstance*)parentMethod)->GetWSession()->IsValid()))
{
log("Invalid Script call: SCcastspell: WorldSession not valid");
logerror("Invalid Script call: SCcastspell: WorldSession not valid");
return false;
}
@ -172,7 +177,7 @@ bool DefScriptPackage::SCcastspell(CmdSet Set)
if (spellId <= 0)
{
log("Invalid Script call: SCcastspell: SpellId not valid");
logerror("Invalid Script call: SCcastspell: SpellId not valid");
return false;
}
@ -181,7 +186,7 @@ bool DefScriptPackage::SCcastspell(CmdSet Set)
spellTarget = ((PseuInstance*)parentMethod)->GetWSession()->GetGuid();
}
((PseuInstance*)parentMethod)->GetWSession()->GetPlayerSettings()->CastSpell(spellId, spellTarget);
// ((PseuInstance*)parentMethod)->GetWSession()->GetPlayerSettings()->CastSpell(spellId, spellTarget);
return true;
}
@ -196,7 +201,7 @@ void DefScriptPackage::My_LoadUserPermissions(VarSet &vs)
{
usr = variables[i].name.substr(strlen(prefix), variables[i].name.length() - strlen(prefix));
my_usrPermissionMap[usr] = atoi(variables[i].value.c_str());
DEBUG( log("Player '%s' permission = %u",usr.c_str(),atoi(variables[i].value.c_str())); )
DEBUG( logdebug("Player '%s' permission = %u",usr.c_str(),atoi(variables[i].value.c_str())); )
}
}
}

View File

@ -399,7 +399,7 @@ void RealmSocket::_HandleLogonProof(void)
}
else
{
log("Auth failed, M2 differs!");
logcritical("Auth failed, M2 differs!");
printf("My M2 :"); printchex((char*)_m2,20,true);
printf("Srv M2:"); printchex((char*)lp.M2,20,true);
GetInstance()->SetError();

View File

@ -0,0 +1,55 @@
#include "common.h"
#include "ZCompressor.h"
#include "WorldSession.h"
#include "UpdateData.h"
void WorldSession::_HandleCompressedUpdateObjectOpcode(WorldPacket& recvPacket)
{
printf("-> COMPRESSED_UPDATE_OBJECT, pktlen=%u\n",recvPacket.size());
//recvPacket.hexlike();
uint32 realsize;
recvPacket >> realsize;
ZCompressor z;
z.append(recvPacket.contents() + sizeof(uint32),recvPacket.size() - sizeof(uint32));
z.Compressed(true);
z.RealSize(realsize);
z.Inflate();
printf("-> Uncompressed to %u bytes\n",z.size());
if(z.Compressed())
{
log("ERROR: _HandleCompressedUpdateObjectOpcode(): Inflate() failed!");
return;
}
WorldPacket wp;
wp.SetOpcode(recvPacket.GetOpcode());
wp.append(z.contents(),z.size());
_HandleUpdateObjectOpcode(wp);
}
void WorldSession::_HandleUpdateObjectOpcode(WorldPacket& recvPacket)
{
printf("-> UPDATE_OBJECT, pktlen=%u\n",recvPacket.size());
//recvPacket.hexlike();
uint8 utype;
uint32 usize;
uint64 uguid;
//while(true)
{
recvPacket >> utype >> usize;
switch(utype)
{
case UPDATETYPE_OUT_OF_RANGE_OBJECTS:
for(uint16 i=0;i<usize;i++)
{
recvPacket >> uguid;
printf("DEBUG: GUID "I64FMT" out of range\n",uguid);
// TODO: delete object from known objects list
}
break;
default:
break;
}
}
}

View File

@ -0,0 +1,18 @@
#ifndef _UPDATEDATA_H
#define _UPDATEDATA_H
enum OBJECT_UPDATE_TYPE
{
UPDATETYPE_VALUES = 0,
UPDATETYPE_MOVEMENT = 1,
UPDATETYPE_CREATE_OBJECT = 2,
UPDATETYPE_CREATE_OBJECT2 = 3,
UPDATETYPE_OUT_OF_RANGE_OBJECTS = 4,
UPDATETYPE_NEAR_OBJECTS = 5
};
#endif

View File

@ -24,7 +24,7 @@ WorldSession::WorldSession(PseuInstance *in)
plrNameCache.ReadFromFile(); // load names/guids of known players
_deleteme = false;
_channels = new Channel(this);
_playerSettings->Init(this);
// _playerSettings->Init(this);
//...
}
@ -112,11 +112,8 @@ void WorldSession::Update(void)
|| ((!known) && GetInstance()->GetConf()->showopcodes==2)
|| (GetInstance()->GetConf()->showopcodes==3) )
{
log(">> Opcode %u - %s - [%s]", packet->GetOpcode(), known ? "Known" : "UNKNOWN", LookupName(packet->GetOpcode(),g_worldOpcodeNames));
logcustom(1,YELLOW,">> Opcode %u [%s] (%s)", packet->GetOpcode(), LookupName(packet->GetOpcode(),g_worldOpcodeNames), known ? "Known" : "UNKNOWN");
}
delete packet;
}
@ -159,7 +156,7 @@ OpcodeHandler *WorldSession::_GetOpcodeHandlerTable() const
{MSG_MOVE_FALL_LAND, &WorldSession::_HandleMovementOpcode},
{MSG_MOVE_TELEPORT_ACK, &WorldSession::_HandleTelePortAckOpcode},
{SMSG_COMPRESSED_UPDATE_OBJECT, &WorldSession::_HandleCompressedUpdateObjectOpcode},
{SMSG_CAST_RESULT, &WorldSession::_HandleCastResultOpcode},
// table termination
@ -265,7 +262,8 @@ void WorldSession::_HandleAuthResponseOpcode(WorldPacket& recvPacket)
pkt.SetOpcode(CMSG_CHAR_ENUM);
SendWorldPacket(pkt);
} else {
log("World Authentication failed, errcode=0x%X",(unsigned char)errcode);
logcritical("World Authentication failed, errcode=0x%X",(unsigned char)errcode);
GetInstance()->SetError();
}
}
@ -278,7 +276,7 @@ void WorldSession::_HandleCharEnumOpcode(WorldPacket& recvPacket)
recvPacket >> num;
if(num==0){
log("No chars found!\n");
logerror("No chars found!");
GetInstance()->SetError();
return;
}
@ -328,12 +326,12 @@ void WorldSession::_HandleCharEnumOpcode(WorldPacket& recvPacket)
}
if(!char_found){
log("Character \"%s\" was not found on char list!",GetInstance()->GetConf()->charname.c_str());
logerror("Character \"%s\" was not found on char list!",GetInstance()->GetConf()->charname.c_str());
GetInstance()->SetError();
return;
} else {
log("Entering World with Character \"%s\"...",GetInstance()->GetConf()->charname.c_str());
_player->Init(plr[i]);
// _player->Init(plr[i]);
WorldPacket pkt;
pkt.SetOpcode(CMSG_PLAYER_LOGIN);
@ -392,19 +390,19 @@ void WorldSession::_HandleMessageChatOpcode(WorldPacket& recvPacket)
recvPacket >> msglen >> msg;
if (type == CHAT_MSG_SYSTEM)
{
log("SYSMSG: \"%s\"",msg.c_str());
logcustom(0,WHITE,"SYSMSG: \"%s\"",msg.c_str());
}
else if (type==CHAT_MSG_WHISPER )
{
log("WHISP: %s [%s]: %s",plrname.c_str(),LookupName(lang,langNames),msg.c_str());
logcustom(0,WHITE,"WHISP: %s [%s]: %s",plrname.c_str(),LookupName(lang,langNames),msg.c_str());
}
else if (type==CHAT_MSG_CHANNEL )
{
log("CHANNEL [%s]: %s [%s]: %s",channel.c_str(),plrname.c_str(),LookupName(lang,langNames),msg.c_str());
logcustom(0,WHITE,"CHANNEL [%s]: %s [%s]: %s",channel.c_str(),plrname.c_str(),LookupName(lang,langNames),msg.c_str());
}
else
{
log("CHAT: %s [%s]: %s",plrname.c_str(),LookupName(lang,langNames),msg.c_str());
logcustom(0,WHITE,"CHAT: %s [%s]: %s",plrname.c_str(),LookupName(lang,langNames),msg.c_str());
}
if(target_guid!=_myGUID && msg.length()>1 && msg.at(0)=='-' && GetInstance()->GetConf()->allowgamecmd)
@ -552,5 +550,5 @@ void WorldSession::_HandleChannelNotifyOpcode(WorldPacket& recvPacket)
void WorldSession::_HandleCastResultOpcode(WorldPacket& recvPacket)
{
_playerSettings->HandleCastResultOpcode(recvPacket);
// _playerSettings->HandleCastResultOpcode(recvPacket);
}

View File

@ -47,8 +47,8 @@ public:
uint64 GetFollowTarget(void) { return _followGUID; }
uint64 GetGuid(void) { return _myGUID; }
Channel *GetChannels(void) { return _channels; }
Player *GetPlayer(void) { return _player; }
PlayerSettings *GetPlayerSettings(void) { return _playerSettings; }
// Player *GetPlayer(void) { return _player; }
// PlayerSettings *GetPlayerSettings(void) { return _playerSettings; }
// CMSGConstructor
@ -81,10 +81,12 @@ private:
void _HandleTelePortAckOpcode(WorldPacket& recvPacket);
void _HandleChannelNotifyOpcode(WorldPacket& recvPacket);
void _HandleCastResultOpcode(WorldPacket& recvPacket);
void _HandleCompressedUpdateObjectOpcode(WorldPacket& recvPacket);
void _HandleUpdateObjectOpcode(WorldPacket& recvPacket);
Player *_player; // The connected character
PlayerSettings *_playerSettings; // Settings for the connected character
//Player *_player; // The connected character
//PlayerSettings *_playerSettings; // Settings for the connected character
PseuInstance *_instance;
WorldSocket *_socket;

View File

@ -71,7 +71,7 @@ void WorldSocket::OnRead()
_opcode = hdr.cmd;
if(_opcode > 800) // no opcode has yet a number over 800
{
printf("CRYPT ERROR: opcode=%u, remain=%u\n",_opcode,_remaining);
logcritical("CRYPT ERROR: opcode=%u, remain=%u",_opcode,_remaining);
GetSession()->GetInstance()->SetError();
// if the crypt gets messy its hardly possible to recover it, especially if we dont know
// the lentgh of the following data part

View File

@ -18,9 +18,11 @@ void log(const char *str, ...)
if(!str)
return;
va_list ap;
_log_setcolor(true,GREY);
va_start(ap, str);
vprintf( str, ap );
va_end(ap);
_log_resetcolor(true);
printf("\n");
@ -41,9 +43,11 @@ void logdetail(const char *str, ...)
if(!str || instance->GetConf()->debug < 1)
return;
va_list ap;
_log_setcolor(true,LCYAN);
va_start(ap, str);
vprintf( str, ap );
va_end(ap);
_log_resetcolor(true);
printf("\n");
@ -64,9 +68,85 @@ void logdebug(const char *str, ...)
if(!str || instance->GetConf()->debug < 2)
return;
va_list ap;
_log_setcolor(true,LBLUE);
va_start(ap, str);
vprintf( str, ap );
va_end(ap);
_log_resetcolor(true);
printf("\n");
if(logfile)
{
fprintf(logfile, getDateString().c_str());
va_start(ap, str);
vfprintf(logfile, str, ap);
fprintf(logfile, "\n" );
va_end(ap);
fflush(logfile);
}
fflush(stdout);
}
void logerror(const char *str, ...)
{
va_list ap;
_log_setcolor(true,LRED);
va_start(ap, str);
vprintf( str, ap );
va_end(ap);
_log_resetcolor(true);
printf("\n");
if(logfile)
{
fprintf(logfile, getDateString().c_str());
va_start(ap, str);
vfprintf(logfile, str, ap);
fprintf(logfile, "\n" );
va_end(ap);
fflush(logfile);
}
fflush(stdout);
}
void logcritical(const char *str, ...)
{
if(!str || instance->GetConf()->debug < 2)
return;
va_list ap;
_log_setcolor(true,RED);
va_start(ap, str);
vprintf( str, ap );
va_end(ap);
_log_resetcolor(true);
printf("\n");
if(logfile)
{
fprintf(logfile, getDateString().c_str());
va_start(ap, str);
vfprintf(logfile, str, ap);
fprintf(logfile, "\n" );
va_end(ap);
fflush(logfile);
}
fflush(stdout);
}
void logcustom(uint8 loglevel, Color color, const char *str, ...)
{
if(!str || instance->GetConf()->debug < loglevel)
return;
va_list ap;
_log_setcolor(true,color);
va_start(ap, str);
vprintf( str, ap );
va_end(ap);
_log_resetcolor(true);
printf("\n");
@ -86,4 +166,90 @@ void log_close()
{
fclose(logfile);
}
void _log_setcolor(bool stdout_stream, Color color)
{
#if PLATFORM == PLATFORM_WIN32
static WORD WinColorFG[Color_count] =
{
0, // BLACK
FOREGROUND_RED, // RED
FOREGROUND_GREEN, // GREEN
FOREGROUND_RED | FOREGROUND_GREEN, // BROWN
FOREGROUND_BLUE, // BLUE
FOREGROUND_RED | FOREGROUND_BLUE,// MAGENTA
FOREGROUND_GREEN | FOREGROUND_BLUE, // CYAN
FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,// WHITE
// YELLOW
FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY,
// RED_BOLD
FOREGROUND_RED | FOREGROUND_INTENSITY,
// GREEN_BOLD
FOREGROUND_GREEN | FOREGROUND_INTENSITY,
FOREGROUND_BLUE | FOREGROUND_INTENSITY, // BLUE_BOLD
// MAGENTA_BOLD
FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY,
// CYAN_BOLD
FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY,
// WHITE_BOLD
FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY
};
HANDLE hConsole = GetStdHandle(stdout_stream ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE );
SetConsoleTextAttribute(hConsole, WinColorFG[color]);
#else
enum ANSITextAttr
{
TA_NORMAL=0,
TA_BOLD=1,
TA_BLINK=5,
TA_REVERSE=7
};
enum ANSIFgTextAttr
{
FG_BLACK=30, FG_RED, FG_GREEN, FG_BROWN, FG_BLUE,
FG_MAGENTA, FG_CYAN, FG_WHITE, FG_YELLOW
};
enum ANSIBgTextAttr
{
BG_BLACK=40, BG_RED, BG_GREEN, BG_BROWN, BG_BLUE,
BG_MAGENTA, BG_CYAN, BG_WHITE
};
static uint8 UnixColorFG[Color_count] =
{
FG_BLACK, // BLACK
FG_RED, // RED
FG_GREEN, // GREEN
FG_BROWN, // BROWN
FG_BLUE, // BLUE
FG_MAGENTA, // MAGENTA
FG_CYAN, // CYAN
FG_WHITE, // WHITE
FG_YELLOW, // YELLOW
FG_RED, // LRED
FG_GREEN, // LGREEN
FG_BLUE, // LBLUE
FG_MAGENTA, // LMAGENTA
FG_CYAN, // LCYAN
FG_WHITE // LWHITE
};
fprintf((stdout_stream? stdout : stderr), "\x1b[%d%sm",UnixColorFG[color],(color>=YELLOW&&color<Color_count ?";1":""));
#endif
}
void _log_resetcolor(bool stdout_stream)
{
#if PLATFORM == PLATFORM_WIN32
HANDLE hConsole = GetStdHandle(stdout_stream ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE );
SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED );
#else
fprintf(( stdout_stream ? stdout : stderr ), "\x1b[0m");
#endif
}

View File

@ -3,11 +3,38 @@
class PseuInstance;
enum Color
{
BLACK,
RED,
GREEN,
BROWN,
BLUE,
MAGENTA,
CYAN,
GREY,
YELLOW,
LRED,
LGREEN,
LBLUE,
LMAGENTA,
LCYAN,
WHITE
};
void log_prepare(char *fn, PseuInstance* p);
void log(const char *str, ...);
void logdetail(const char *str, ...);
void logdebug(const char *str, ...);
void logerror(const char *str, ...);
void logcritical(const char *str, ...);
void logcustom(uint8 loglevel, Color color, const char *str, ...);
void log_close();
void _log_setcolor(bool,Color);
void _log_resetcolor(bool);
const int Color_count = int(WHITE)+1;
#endif

View File

@ -296,6 +296,12 @@
<File
RelativePath=".\Client\World\SharedDefines.h">
</File>
<File
RelativePath=".\Client\World\UpdateData.cpp">
</File>
<File
RelativePath=".\Client\World\UpdateData.h">
</File>
<File
RelativePath=".\Client\World\UpdateFields.h">
</File>

View File

@ -137,6 +137,12 @@
<File
RelativePath=".\shared\tools.h">
</File>
<File
RelativePath=".\shared\ZCompressor.cpp">
</File>
<File
RelativePath=".\shared\ZCompressor.h">
</File>
<Filter
Name="Network"
Filter="">

122
src/shared/ZCompressor.cpp Normal file
View File

@ -0,0 +1,122 @@
#include "common.h"
#include "zlib/zlib.h"
#include "ZCompressor.h"
ZCompressor::ZCompressor()
{
_iscompressed=false;
_real_size=0;
}
void ZCompressor::_compress(void* dst, uint32 *dst_size, void* src, uint32 src_size, uint8 level)
{
z_stream c_stream;
c_stream.zalloc = (alloc_func)0;
c_stream.zfree = (free_func)0;
c_stream.opaque = (voidpf)0;
// default Z_BEST_SPEED (1)
if (Z_OK != deflateInit(&c_stream, level))
{
//printf("ZLIB: Can't compress (zlib: deflateInit).\n");
*dst_size = 0;
return;
}
c_stream.next_out = (Bytef*)dst;
c_stream.avail_out = *dst_size;
c_stream.next_in = (Bytef*)src;
c_stream.avail_in = (uInt)src_size;
if (Z_OK != deflate(&c_stream, Z_NO_FLUSH))
{
//printf("ZLIB: Can't compress (zlib: deflate)\n");
*dst_size = 0;
return;
}
if (c_stream.avail_in != 0)
{
//printf("Can't compress (zlib: deflate not greedy)\n");
*dst_size = 0;
return;
}
if (Z_STREAM_END != deflate(&c_stream, Z_FINISH))
{
//printf("Can't compress (zlib: deflate should report Z_STREAM_END)\n");
*dst_size = 0;
//return;
exit(1);
}
if (Z_OK != deflateEnd(&c_stream))
{
//printf("Can't compress (zlib: deflateEnd)\n");
*dst_size = 0;
return;
}
*dst_size = c_stream.total_out;
}
void ZCompressor::Deflate(uint8 level)
{
if( _iscompressed || (!size()) || level>9 )
return;
char *buf;
buf=new char[size()+8];
uint32 newsize,oldsize=size();
reserve(size()+8);
_compress((void*)buf, &newsize, (void*)contents(),size(),level);
if(!newsize)
return;
resize(newsize);
rpos(0);
wpos(0);
append(buf,newsize);
_iscompressed=true;
_real_size=oldsize;
}
void ZCompressor::Inflate(void)
{
if( (!_iscompressed) || (!_real_size) || (!size()))
return;
uLongf origsize=_real_size;
int8 result;
uint8 *target=new uint8[_real_size];
wpos(0);
rpos(0);
result = uncompress(target, &origsize, (uint8*)contents(), size());
if( result!=Z_OK || origsize!=_real_size)
{
//printf("ZCompressor: Inflate error! result=%d cursize=%u origsize=%u realsize=%u\n",result,size(),origsize,_real_size);
delete [] target;
return;
}
clear();
append(target,origsize);
delete [] target;
_real_size=0;
_iscompressed=false;
}
void ZCompressor::clear(void)
{
ByteBuffer::clear();
_real_size=0;
_iscompressed=false;
}

34
src/shared/ZCompressor.h Normal file
View File

@ -0,0 +1,34 @@
#ifndef _ZCOMPRESSOR_H
#define _ZCOMPRESSOR_H
#include "Auth/ByteBuffer.h"
class ZCompressor : public ByteBuffer
{
public:
ZCompressor();
void Deflate(uint8 level=4);
void Inflate(void);
bool Compressed(void) { return _iscompressed; }
void Compressed(bool b) { _iscompressed = b; }
uint32 RealSize(void) { return _iscompressed ? _real_size : 0; }
void RealSize(uint32 realsize) { _real_size=realsize; }
void clear(void);
protected:
bool _iscompressed;
void _compress(void* dst, uint32 *dst_size, void* src, uint32 src_size, uint8 level=4);
uint32 _real_size;
};
#endif

View File

@ -1,344 +0,0 @@
/*
** Database.cpp
**
** Published / author: 2005-08-12 / grymse@alhem.net
**/
/*
Copyright (C) 2001-2006 Anders Hedstrom
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#ifdef _WIN32
#pragma warning(disable:4786)
#endif
#include <string>
#include <map>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../../dep/src/sqlite/sqlite3.h"
#include <stdarg.h>
#include "IError.h"
#include "Database.h"
#ifdef SQLITEW_NAMESPACE
namespace SQLITEW_NAMESPACE {
#endif
Database::Database(const std::string& d,IError *e)
:database(d)
,m_errhandler(e)
,m_embedded(true)
,m_mutex(m_mutex)
,m_b_use_mutex(false)
{
}
Database::Database(Mutex& m,const std::string& d,IError *e)
:database(d)
,m_errhandler(e)
,m_embedded(true)
,m_mutex(m)
,m_b_use_mutex(true)
{
}
Database::~Database()
{
for (opendb_v::iterator it = m_opendbs.begin(); it != m_opendbs.end(); it++)
{
OPENDB *p = *it;
sqlite3_close(p -> db);
}
while (m_opendbs.size())
{
opendb_v::iterator it = m_opendbs.begin();
OPENDB *p = *it;
if (p -> busy)
{
error("destroying Database object before Query object");
}
delete p;
m_opendbs.erase(it);
}
}
void Database::RegErrHandler(IError *p)
{
m_errhandler = p;
}
Database::OPENDB *Database::grabdb()
{
Lock lck(m_mutex, m_b_use_mutex);
OPENDB *odb = NULL;
for (opendb_v::iterator it = m_opendbs.begin(); it != m_opendbs.end(); it++)
{
odb = *it;
if (!odb -> busy)
{
break;
}
else
{
odb = NULL;
}
}
if (!odb)
{
odb = new OPENDB;
if (!odb)
{
error("grabdb: OPENDB struct couldn't be created");
return NULL;
}
int rc = sqlite3_open(database.c_str(), &odb -> db);
if (rc)
{
error("Can't open database: %s\n", sqlite3_errmsg(odb -> db));
sqlite3_close(odb -> db);
delete odb;
return NULL;
}
odb -> busy = true;
m_opendbs.push_back(odb);
}
else
{
odb -> busy = true;
}
return odb;
}
void Database::freedb(Database::OPENDB *odb)
{
Lock lck(m_mutex, m_b_use_mutex);
if (odb)
{
odb -> busy = false;
}
}
void Database::error(const char *format, ...)
{
if (m_errhandler)
{
va_list ap;
char errstr[5000];
va_start(ap, format);
#ifdef WIN32
vsprintf(errstr, format, ap);
#else
vsnprintf(errstr, 5000, format, ap);
#endif
va_end(ap);
m_errhandler -> error(*this, errstr);
}
}
void Database::error(Query& q,const char *format, ...)
{
if (m_errhandler)
{
va_list ap;
char errstr[5000];
va_start(ap, format);
#ifdef WIN32
vsprintf(errstr, format, ap);
#else
vsnprintf(errstr, 5000, format, ap);
#endif
va_end(ap);
m_errhandler -> error(*this, q, errstr);
}
}
void Database::error(Query& q,const std::string& msg)
{
if (m_errhandler)
{
m_errhandler -> error(*this, q, msg);
}
}
bool Database::Connected()
{
OPENDB *odb = grabdb();
if (!odb)
{
return false;
}
freedb(odb);
return true;
}
Database::Lock::Lock(Mutex& mutex,bool use) : m_mutex(mutex),m_b_use(use)
{
if (m_b_use)
{
m_mutex.Lock();
}
}
Database::Lock::~Lock()
{
if (m_b_use)
{
m_mutex.Unlock();
}
}
Database::Mutex::Mutex()
{
#ifdef _WIN32
m_mutex = ::CreateMutex(NULL, FALSE, NULL);
#else
pthread_mutex_init(&m_mutex, NULL);
#endif
}
Database::Mutex::~Mutex()
{
#ifdef _WIN32
::CloseHandle(m_mutex);
#else
pthread_mutex_destroy(&m_mutex);
#endif
}
void Database::Mutex::Lock()
{
#ifdef _WIN32
DWORD d = WaitForSingleObject(m_mutex, INFINITE);
// %! check 'd' for result
#else
pthread_mutex_lock(&m_mutex);
#endif
}
void Database::Mutex::Unlock()
{
#ifdef _WIN32
::ReleaseMutex(m_mutex);
#else
pthread_mutex_unlock(&m_mutex);
#endif
}
std::string Database::safestr(const std::string& str)
{
std::string str2;
for (size_t i = 0; i < str.size(); i++)
{
switch (str[i])
{
case '\'':
case '\\':
case 34:
str2 += '\'';
default:
str2 += str[i];
}
}
return str2;
}
std::string Database::xmlsafestr(const std::string& str)
{
std::string str2;
for (size_t i = 0; i < str.size(); i++)
{
switch (str[i])
{
case '&':
str2 += "&amp;";
break;
case '<':
str2 += "&lt;";
break;
case '>':
str2 += "&gt;";
break;
case '"':
str2 += "&quot;";
break;
case '\'':
str2 += "&apos;";
break;
default:
str2 += str[i];
}
}
return str2;
}
int64_t Database::a2bigint(const std::string& str)
{
int64_t val = 0;
bool sign = false;
size_t i = 0;
if (str[i] == '-')
{
sign = true;
i++;
}
for (; i < str.size(); i++)
{
val = val * 10 + (str[i] - 48);
}
return sign ? -val : val;
}
uint64_t Database::a2ubigint(const std::string& str)
{
uint64_t val = 0;
for (size_t i = 0; i < str.size(); i++)
{
val = val * 10 + (str[i] - 48);
}
return val;
}
#ifdef SQLITEW_NAMESPACE
} // namespace SQLITEW_NAMESPACE {
#endif

View File

@ -1,154 +0,0 @@
/*
** Database.h
**
** Published / author: 2005-08-12 / grymse@alhem.net
**/
/*
Copyright (C) 2001-2006 Anders Hedstrom
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef _DATABASE_H_SQLITE
#define _DATABASE_H_SQLITE
#ifdef _WIN32
#include <windows.h>
#else
#include <pthread.h>
#endif
#include <string>
#include <list>
#ifdef WIN32
typedef unsigned __int64 uint64_t;
typedef __int64 int64_t;
#else
#include <stdint.h>
#endif
#ifdef SQLITEW_NAMESPACE
namespace SQLITEW_NAMESPACE {
#endif
class IError;
class Query;
class Mutex;
/** Connection information and pool. */
class Database
{
public:
/** Mutex container class, used by Lock.
\ingroup threading */
class Mutex {
public:
Mutex();
~Mutex();
void Lock();
void Unlock();
private:
#ifdef _WIN32
HANDLE m_mutex;
#else
pthread_mutex_t m_mutex;
#endif
};
private:
/** Mutex helper class. */
class Lock {
public:
Lock(Mutex& mutex,bool use);
~Lock();
private:
Mutex& m_mutex;
bool m_b_use;
};
public:
/** Connection pool struct. */
struct OPENDB {
OPENDB() : busy(false) {}
sqlite3 *db;
bool busy;
};
typedef std::list<OPENDB *> opendb_v;
public:
/** Use file */
Database(const std::string& database,
IError * = NULL);
/** Use file + thread safe */
Database(Mutex& ,const std::string& database,
IError * = NULL);
virtual ~Database();
/** try to establish connection with given host */
bool Connected();
void RegErrHandler(IError *);
void error(Query&,const char *format, ...);
void error(Query&,const std::string& );
/** Request a database connection.
The "grabdb" method is used by the Query class, so that each object instance of Query gets a unique
database connection. I will reimplement your connection check logic in the Query class, as that's where
the database connection is really used.
It should be used something like this.
{
Query q(db);
if (!q.Connected())
return false;
q.execute("delete * from user"); // well maybe not
}
When the Query object is deleted, then "freedb" is called - the database connection stays open in the
m_opendbs vector. New Query objects can then reuse old connections.
*/
OPENDB *grabdb();
void freedb(OPENDB *odb);
/** Escape string - change all ' to ''. */
std::string safestr(const std::string& );
/** Make string xml safe. */
std::string xmlsafestr(const std::string& );
/** Convert string to 64-bit integer. */
int64_t a2bigint(const std::string& );
/** Convert string to unsigned 64-bit integer. */
uint64_t a2ubigint(const std::string& );
private:
Database(const Database& ) : m_mutex(m_mutex) {}
Database& operator=(const Database& ) { return *this; }
void error(const char *format, ...);
//
std::string database;
opendb_v m_opendbs;
IError *m_errhandler;
bool m_embedded;
Mutex& m_mutex;
bool m_b_use_mutex;
};
#ifdef SQLITEW_NAMESPACE
} // namespace SQLITEW_NAMESPACE {
#endif
#endif // _DATABASE_H

View File

@ -1,53 +0,0 @@
/*
** IError.h
**
** Published / author: 2004-06-11 / grymse@alhem.net
**/
/*
Copyright (C) 2004,2005,2006 Anders Hedstrom
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef _IERROR_H_SQLITE
#define _IERROR_H_SQLITE
#include <string>
#ifdef SQLITEW_NAMESPACE
namespace SQLITEW_NAMESPACE {
#endif
class Database;
class Query;
/** Log class interface. */
class IError
{
public:
virtual void error(Database&,const std::string&) = 0;
virtual void error(Database&,Query&,const std::string&) = 0;
};
#ifdef SQLITEW_NAMESPACE
} // namespace SQLITEW_NAMESPACE {
#endif
#endif // _IERROR_H

View File

@ -1,524 +0,0 @@
/*
** Query.cpp
**
** Published / author: 2005-08-12 / grymse@alhem.net
**/
/*
Copyright (C) 2001-2006 Anders Hedstrom
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifdef _WIN32
#pragma warning(disable:4786)
#endif
#include <string>
#include <map>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../../dep/src/sqlite/sqlite3.h"
#include "Database.h"
#include "Query.h"
#ifdef SQLITEW_NAMESPACE
namespace SQLITEW_NAMESPACE {
#endif
Query::Query(Database& dbin)
: m_db(dbin)
,odb(dbin.grabdb())
,res(NULL)
,row(false)
,cache_rc(0)
,cache_rc_valid(false)
,m_row_count(0)
,m_num_cols(0)
{
}
Query::Query(Database& dbin,const std::string& sql)
: m_db(dbin)
,odb(dbin.grabdb())
,res(NULL)
,row(false)
,cache_rc(0)
,cache_rc_valid(false)
,m_row_count(0)
,m_num_cols(0)
{
execute(sql);
}
Query::~Query()
{
if (res)
{
GetDatabase().error(*this, "sqlite3_finalize in destructor");
sqlite3_finalize(res);
}
if (odb)
{
m_db.freedb(odb);
}
}
Database& Query::GetDatabase() const
{
return m_db;
}
/*
The sqlite3_finalize() routine deallocates a prepared SQL statement.
All prepared statements must be finalized before the database can be closed.
*/
bool Query::execute(const std::string& sql)
{ // query, no result
m_last_query = sql;
if (odb && res)
{
GetDatabase().error(*this, "execute: query busy");
}
if (odb && !res)
{
const char *s = NULL;
int rc = sqlite3_prepare(odb -> db, sql.c_str(), sql.size(), &res, &s);
if (rc != SQLITE_OK)
{
GetDatabase().error(*this, "execute: prepare query failed");
return false;
}
if (!res)
{
GetDatabase().error(*this, "execute: query failed");
return false;
}
rc = sqlite3_step(res); // execute
sqlite3_finalize(res); // deallocate statement
res = NULL;
switch (rc)
{
case SQLITE_BUSY:
GetDatabase().error(*this, "execute: database busy");
return false;
case SQLITE_DONE:
case SQLITE_ROW:
return true;
case SQLITE_ERROR:
GetDatabase().error(*this, sqlite3_errmsg(odb -> db));
return false;
case SQLITE_MISUSE:
GetDatabase().error(*this, "execute: database misuse");
return false;
}
GetDatabase().error(*this, "execute: unknown result code");
}
return false;
}
// methods using db specific api calls
sqlite3_stmt *Query::get_result(const std::string& sql)
{ // query, result
if (odb && res)
{
GetDatabase().error(*this, "get_result: query busy");
}
if (odb && !res)
{
const char *s = NULL;
int rc = sqlite3_prepare(odb -> db, sql.c_str(), sql.size(), &res, &s);
if (rc != SQLITE_OK)
{
GetDatabase().error(*this, "get_result: prepare query failed");
return NULL;
}
if (!res)
{
GetDatabase().error(*this, "get_result: query failed");
return NULL;
}
// get column names from result
{
int i = 0;
do
{
const char *p = sqlite3_column_name(res, i);
if (!p)
break;
m_nmap[p] = ++i;
} while (true);
m_num_cols = i + 1;
}
cache_rc = sqlite3_step(res);
cache_rc_valid = true;
m_row_count = (cache_rc == SQLITE_ROW) ? 1 : 0;
}
return res;
}
void Query::free_result()
{
if (odb && res)
{
sqlite3_finalize(res);
res = NULL;
row = false;
cache_rc_valid = false;
}
// clear column names
while (m_nmap.size())
{
std::map<std::string,int>::iterator it = m_nmap.begin();
m_nmap.erase(it);
}
}
bool Query::fetch_row()
{
rowcount = 0;
row = false;
if (odb && res)
{
int rc = cache_rc_valid ? cache_rc : sqlite3_step(res); // execute
cache_rc_valid = false;
switch (rc)
{
case SQLITE_BUSY:
GetDatabase().error(*this, "execute: database busy");
return false;
case SQLITE_DONE:
return false;
case SQLITE_ROW:
row = true;
return true;
case SQLITE_ERROR:
GetDatabase().error(*this, sqlite3_errmsg(odb -> db));
return false;
case SQLITE_MISUSE:
GetDatabase().error(*this, "execute: database misuse");
return false;
}
GetDatabase().error(*this, "execute: unknown result code");
}
return false;
}
sqlite_int64 Query::insert_id()
{
if (odb)
{
return sqlite3_last_insert_rowid(odb -> db);
}
else
{
return 0;
}
}
long Query::num_rows()
{
return odb && res ? m_row_count : 0;
}
bool Query::is_null(int x)
{
if (odb && res && row)
{
if (sqlite3_column_type(res, x) == SQLITE_NULL)
return true;
}
return false; // ...
}
const char *Query::getstr(const std::string& x)
{
int index = m_nmap[x] - 1;
if (index >= 0)
return getstr(index);
error("Column name lookup failure: " + x);
return "";
}
const char *Query::getstr(int x)
{
if (odb && res && row && x < sqlite3_column_count(res) )
{
const unsigned char *tmp = sqlite3_column_text(res, x);
return tmp ? (const char *)tmp : "";
}
return "";
}
const char *Query::getstr()
{
return getstr(rowcount++);
}
double Query::getnum(const std::string& x)
{
int index = m_nmap[x] - 1;
if (index >= 0)
return getnum(index);
error("Column name lookup failure: " + x);
return 0;
}
double Query::getnum(int x)
{
if (odb && res && row)
{
return sqlite3_column_double(res, x);
}
return 0;
}
long Query::getval(const std::string& x)
{
int index = m_nmap[x] - 1;
if (index >= 0)
return getval(index);
error("Column name lookup failure: " + x);
return 0;
}
long Query::getval(int x)
{
if (odb && res && row)
{
return sqlite3_column_int(res, x);
}
return 0;
}
double Query::getnum()
{
return getnum(rowcount++);
}
long Query::getval()
{
return getval(rowcount++);
}
unsigned long Query::getuval(const std::string& x)
{
int index = m_nmap[x] - 1;
if (index >= 0)
return getuval(index);
error("Column name lookup failure: " + x);
return 0;
}
unsigned long Query::getuval(int x)
{
unsigned long l = 0;
if (odb && res && row)
{
l = sqlite3_column_int(res, x);
}
return l;
}
unsigned long Query::getuval()
{
return getuval(rowcount++);
}
int64_t Query::getbigint(const std::string& x)
{
int index = m_nmap[x] - 1;
if (index >= 0)
return getbigint(index);
error("Column name lookup failure: " + x);
return 0;
}
int64_t Query::getbigint(int x)
{
if (odb && res && row)
{
return sqlite3_column_int64(res, x);
}
return 0;
}
int64_t Query::getbigint()
{
return getbigint(rowcount++);
}
uint64_t Query::getubigint(const std::string& x)
{
int index = m_nmap[x] - 1;
if (index >= 0)
return getubigint(index);
error("Column name lookup failure: " + x);
return 0;
}
uint64_t Query::getubigint(int x)
{
uint64_t l = 0;
if (odb && res && row)
{
l = sqlite3_column_int64(res, x);
}
return l;
}
uint64_t Query::getubigint()
{
return getubigint(rowcount++);
}
double Query::get_num(const std::string& sql)
{
double l = 0;
if (get_result(sql))
{
if (fetch_row())
{
l = getnum();
}
free_result();
}
return l;
}
long Query::get_count(const std::string& sql)
{
long l = 0;
if (get_result(sql))
{
if (fetch_row())
l = getval();
free_result();
}
return l;
}
const char *Query::get_string(const std::string& sql)
{
bool found = false;
m_tmpstr = "";
if (get_result(sql))
{
if (fetch_row())
{
m_tmpstr = getstr();
found = true;
}
free_result();
}
return m_tmpstr.c_str(); // %! changed from 1.0 which didn't return NULL on failed query
}
const std::string& Query::GetLastQuery()
{
return m_last_query;
}
std::string Query::GetError()
{
if (odb)
return sqlite3_errmsg(odb -> db);
return "";
}
int Query::GetErrno()
{
if (odb)
return sqlite3_errcode(odb -> db);
return 0;
}
bool Query::Connected()
{
return odb ? true : false;
}
void Query::ViewRes()
{
if (!res)
{
printf("no result stored\n");
return;
}
printf("result column count = %d\n", sqlite3_column_count(res));
for (int i = 0; i < sqlite3_column_count(res); i++)
{
printf(" %2d type %d name '%s'", i, sqlite3_column_type(res, i), sqlite3_column_name(res, i));
printf(" / '%s'", (char *)sqlite3_column_text(res, i));
printf(" / %d", sqlite3_column_int(res, i));
printf(" / %f", sqlite3_column_double(res, i));
printf("\n");
}
}
void Query::error(const std::string& msg)
{
GetDatabase().error(*this, msg);
}
#ifdef SQLITEW_NAMESPACE
} // namespace SQLITEW_NAMESPACE {
#endif

View File

@ -1,165 +0,0 @@
#ifdef _WIN32
#pragma warning(disable:4786)
#endif
/*
** Query.h
**
** Published / author: 2005-08-12 / grymse@alhem.net
**/
/*
Copyright (C) 2001-2006 Anders Hedstrom
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef _QUERY_H_SQLITE
#define _QUERY_H_SQLITE
#include <string>
#include <map>
#ifdef WIN32
typedef unsigned __int64 uint64_t;
typedef __int64 int64_t;
#else
#include <stdint.h>
#endif
#ifdef SQLITEW_NAMESPACE
namespace SQLITEW_NAMESPACE {
#endif
/** SQL Statement execute / result. */
class Query
{
public:
/** Constructor accepting reference to database object. */
Query(Database& dbin);
/** Constructor accepting reference to database object
and query string to execute. */
Query(Database& dbin,const std::string& sql);
~Query();
/** Check if database object is connectable. */
bool Connected();
/** Return reference to database object. */
Database& GetDatabase() const;
/** Return string containing last query executed. */
const std::string& GetLastQuery();
/** execute() returns true if query is successful,
does not store result. */
bool execute(const std::string& sql);
/** Execute query and store result. */
sqlite3_stmt *get_result(const std::string& sql);
/** Free stored result, must be called after get_result() before calling
execute()/get_result() again. */
void free_result();
/** Fetch next result row.
\return false if there was no row to fetch (end of rows) */
bool fetch_row();
/** Get id of last insert. */
sqlite_int64 insert_id();
/** Returns 0 if there are no rows to fetch. */
long num_rows();
/** Last error string. */
std::string GetError();
/** Last error code. */
int GetErrno();
/** Execute query and return first result as a string. */
const char *get_string(const std::string& sql);
/** Execute query and return first result as a long integer. */
long get_count(const std::string& sql);
/** Execute query and return first result as a double. */
double get_num(const std::string& sql);
/** Check if column x in current row is null. */
bool is_null(int x);
/** Return column named x as a string value. */
const char *getstr(const std::string& x);
/** Return column x as a string value. */
const char *getstr(int x);
/** Return next column as a string value - see rowcount. */
const char *getstr();
/** Return column named x as a long integer. */
long getval(const std::string& x);
/** Return column x as a long integer. */
long getval(int x);
/** Return next column as a long integer - see rowcount. */
long getval();
/** Return column named x as an unsigned long integer. */
unsigned long getuval(const std::string& x);
/** Return column x as an unsigned long integer. */
unsigned long getuval(int x);
/** Return next column as an unsigned long integer. */
unsigned long getuval();
/** Return column named x as a 64-bit integer value. */
int64_t getbigint(const std::string& x);
/** Return column x as a 64-bit integer value. */
int64_t getbigint(int x);
/** Return next column as a 64-bit integer value. */
int64_t getbigint();
/** Return column named x as an unsigned 64-bit integer value. */
uint64_t getubigint(const std::string& x);
/** Return column x as an unsigned 64-bit integer value. */
uint64_t getubigint(int x);
/** Return next column as an unsigned 64-bit integer value. */
uint64_t getubigint();
/** Return column named x as a double. */
double getnum(const std::string& x);
/** Return column x as a double. */
double getnum(int x);
/** Return next column as a double. */
double getnum();
private:
/** Hide the copy constructor. */
Query(const Query& q) : m_db(q.GetDatabase()) {}
/** Hide the assignment operator. */
Query& operator=(const Query& ) { return *this; }
/** Print current result to stdout. */
void ViewRes();
/** Print error to debug class. */
void error(const std::string& );
Database& m_db; ///< Reference to database object
Database::OPENDB *odb; ///< Connection pool handle
sqlite3_stmt *res; ///< Stored result
bool row; ///< true if fetch_row succeeded
short rowcount; ///< Current column pointer in result
std::string m_tmpstr; ///< Used to store result in get_string() call
std::string m_last_query; ///< Last query executed
int cache_rc; ///< Cached result after call to get_result()
bool cache_rc_valid; ///< Indicates cache_rc is valid
int m_row_count; ///< 0 if get_result() returned no rows
//
std::map<std::string,int> m_nmap; ///< map translating column names to index
int m_num_cols; ///< number of columns in result
};
#ifdef SQLITEW_NAMESPACE
} // namespace SQLITEW_NAMESPACE {
#endif
#endif // _QUERY_H

View File

@ -1,71 +0,0 @@
/*
** StderrLog.cpp
**
** Published / author: 2004-08-18 / grymse@alhem.net
**/
/*
Copyright (C) 2004,2005,2006 Anders Hedstrom
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <stdio.h>
#ifdef _WIN32
#pragma warning(disable:4786)
#endif
#include <string>
#include <map>
#include <time.h>
#include "../../dep/src/sqlite/sqlite3.h"
#include "Database.h"
#include "Query.h"
#include "IError.h"
#include "StderrLog.h"
#ifdef SQLITEW_NAMESPACE
namespace SQLITEW_NAMESPACE {
#endif
void StderrLog::error(Database& db,const std::string& str)
{
time_t t = time(NULL);
struct tm *tp = localtime(&t);
fprintf(stderr,"%d-%02d-%02d %02d:%02d:%02d :: Database: %s\n",
tp -> tm_year + 1900,tp -> tm_mon + 1,tp -> tm_mday,
tp -> tm_hour,tp -> tm_min, tp -> tm_sec,
str.c_str());
}
void StderrLog::error(Database& db,Query& q,const std::string& str)
{
time_t t = time(NULL);
struct tm *tp = localtime(&t);
fprintf(stderr,"%d-%02d-%02d %02d:%02d:%02d :: Query: %s: %s(%d)\n",
tp -> tm_year + 1900,tp -> tm_mon + 1,tp -> tm_mday,
tp -> tm_hour,tp -> tm_min, tp -> tm_sec,
str.c_str(),q.GetError().c_str(),q.GetErrno());
fprintf(stderr," (QUERY: \"%s\")\n",q.GetLastQuery().c_str());
}
#ifdef SQLITEW_NAMESPACE
} // namespace SQLITEW_NAMESPACE {
#endif

View File

@ -1,48 +0,0 @@
/*
** StderrLog.h
**
** Published / author: 2004-08-18 / grymse@alhem.net
**/
/*
Copyright (C) 2004,2005,2006 Anders Hedstrom
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef _STDERRLOG_H_SQLITE
#define _STDERRLOG_H_SQLITE
#ifdef SQLITEW_NAMESPACE
namespace SQLITEW_NAMESPACE {
#endif
/** Log class writing to standard error. */
class StderrLog : public IError
{
public:
void error(Database&,const std::string&);
void error(Database&,Query&,const std::string&);
};
#ifdef SQLITEW_NAMESPACE
} // namespace SQLITEW_NAMESPACE {
#endif
#endif // _STDERRLOG_H

View File

@ -1,71 +0,0 @@
/*
** SysLog.cpp
**
** Published / author: 2004-08-18 / grymse@alhem.net
**/
/*
Copyright (C) 2004,2005,2006 Anders Hedstrom
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef WIN32
#include "../dep/src/sqlite/sqlite3.h"
#include <syslog.h>
#include "Database.h"
#include "Query.h"
#include "IError.h"
#include "SysLog.h"
#ifdef SQLITEW_NAMESPACE
namespace SQLITEW_NAMESPACE {
#endif
SysLog::SysLog(const std::string& appname,int option,int facility)
{
static char blah[100];
strcpy(blah, appname.c_str());
openlog(blah, option, facility);
}
SysLog::~SysLog()
{
closelog();
}
void SysLog::error(Database& db,const std::string& str)
{
syslog(LOG_ERR, "%s", str.c_str() );
}
void SysLog::error(Database& db,Query& q,const std::string& str)
{
syslog(LOG_ERR, "%s: %s(%d)", str.c_str(),q.GetError().c_str(),q.GetErrno() );
syslog(LOG_ERR, "QUERY: \"%s\"", q.GetLastQuery().c_str());
}
#ifdef SQLITEW_NAMESPACE
} // namespace SQLITEW_NAMESPACE {
#endif
#endif // WIN32

View File

@ -1,55 +0,0 @@
/*
** SysLog.h
**
** Published / author: 2004-08-18 / grymse@alhem.net
**/
/*
Copyright (C) 2004,2005,2006 Anders Hedstrom
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef _SYSLOG_H_SQLITE
#define _SYSLOG_H_SQLITE
#ifndef WIN32
#include <syslog.h>
#ifdef SQLITEW_NAMESPACE
namespace SQLITEW_NAMESPACE {
#endif
/** Log class writing to syslog. */
class SysLog : public IError
{
public:
SysLog(const std::string& = "database", int = LOG_PID, int = LOG_USER);
virtual ~SysLog();
void error(Database&,const std::string&);
void error(Database&,Query&,const std::string&);
};
#ifdef SQLITEW_NAMESPACE
} // namespace SQLITEW_NAMESPACE {
#endif
#endif // WIN32
#endif // _SYSLOG_H