Click here to Skip to main content
15,883,799 members
Articles / Database Development / SQL Server

CppSQLite - C++ Wrapper for SQLite

Rate me:
Please Sign up or sign in to vote.
4.93/5 (228 votes)
24 Jun 2011CPOL16 min read 2.6M   51.6K   554  
A C++ wrapper around the SQLite embedded database library.
////////////////////////////////////////////////////////////////////////////////
// CppSQLite - A very thin wrapper around the SQLite database engine
//
// Author
//		Rob Groves, rob.groves@btinternet.com
//
// -----------------------------------------------------------------------------
// V1.0		05/03/2004	-Initial Version
//
// V1.1		09/03/2004	-Added CppSQLiteException::errorCodeAsString()
//						-Renamed CppSQLiteException::errorMess() - errorMessage()
//						-2 different CppSQLiteException constructors
//						-Added CppSQLiteBinary
//						-Now call sqlite_finalize() straight after error with
//						 sqlite_step()
//
// V1.2		02/04/2004	-Utilise sqlite_busy_timeout() and sqlite_interrupt()
//						 to help with multithreaded use
//						-Revert to single CppSQLiteException constructor
//						-Removed dependency on a Microsoft specific extension
//						-Added CppSQLiteQuery::fieldType()
//						-Added code to check for null pointers
//						-Added CppSQLiteStatement for SQLite pre-compiled statements
//						-Added CppSQLiteDB::execScalar()
////////////////////////////////////////////////////////////////////////////////
#include "CppSQLite.h"
#include <cstdlib>


// Named constant for passing to CppSQLiteException when passing it a string
// that cannot be deleted.
static const bool DONT_DELETE_MSG=false;

////////////////////////////////////////////////////////////////////////////////
// Prototypes for SQLite functions not included in SQLite DLL, but copied below
// from SQLite encode.c
////////////////////////////////////////////////////////////////////////////////
int sqlite_encode_binary(const unsigned char *in, int n, unsigned char *out);
int sqlite_decode_binary(const unsigned char *in, unsigned char *out);

////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////

CppSQLiteException::CppSQLiteException(const int nErrCode,
									char* szErrMess,
									bool bDeleteMsg/*=true*/) :
									mnErrCode(nErrCode)
{
	mpszErrMess = sqlite_mprintf("%s[%d]: %s",
								errorCodeAsString(nErrCode),
								nErrCode,
								szErrMess ? szErrMess : "");

	if (bDeleteMsg && szErrMess)
	{
		sqlite_freemem(szErrMess);
	}
}

									
CppSQLiteException::CppSQLiteException(const CppSQLiteException&  e) :
									mnErrCode(e.mnErrCode)
{
	mpszErrMess = 0;
	if (e.mpszErrMess)
	{
		mpszErrMess = sqlite_mprintf("%s", e.mpszErrMess);
	}
}


const char* CppSQLiteException::errorCodeAsString(int nErrCode)
{
	switch (nErrCode)
	{
		case SQLITE_OK          : return "SQLITE_OK";
		case SQLITE_ERROR       : return "SQLITE_ERROR";
		case SQLITE_INTERNAL    : return "SQLITE_INTERNAL";
		case SQLITE_PERM        : return "SQLITE_PERM";
		case SQLITE_ABORT       : return "SQLITE_ABORT";
		case SQLITE_BUSY        : return "SQLITE_BUSY";
		case SQLITE_LOCKED      : return "SQLITE_LOCKED";
		case SQLITE_NOMEM       : return "SQLITE_NOMEM";
		case SQLITE_READONLY    : return "SQLITE_READONLY";
		case SQLITE_INTERRUPT   : return "SQLITE_INTERRUPT";
		case SQLITE_IOERR       : return "SQLITE_IOERR";
		case SQLITE_CORRUPT     : return "SQLITE_CORRUPT";
		case SQLITE_NOTFOUND    : return "SQLITE_NOTFOUND";
		case SQLITE_FULL        : return "SQLITE_FULL";
		case SQLITE_CANTOPEN    : return "SQLITE_CANTOPEN";
		case SQLITE_PROTOCOL    : return "SQLITE_PROTOCOL";
		case SQLITE_EMPTY       : return "SQLITE_EMPTY";
		case SQLITE_SCHEMA      : return "SQLITE_SCHEMA";
		case SQLITE_TOOBIG      : return "SQLITE_TOOBIG";
		case SQLITE_CONSTRAINT  : return "SQLITE_CONSTRAINT";
		case SQLITE_MISMATCH    : return "SQLITE_MISMATCH";
		case SQLITE_MISUSE      : return "SQLITE_MISUSE";
		case SQLITE_NOLFS       : return "SQLITE_NOLFS";
		case SQLITE_AUTH        : return "SQLITE_AUTH";
		case SQLITE_FORMAT      : return "SQLITE_FORMAT";
		case SQLITE_RANGE       : return "SQLITE_RANGE";
		case SQLITE_ROW         : return "SQLITE_ROW";
		case SQLITE_DONE        : return "SQLITE_DONE";
		case CPPSQLITE_ERROR    : return "CPPSQLITE_ERROR";
		default: return "UNKNOWN_ERROR";
	}
}


CppSQLiteException::~CppSQLiteException()
{
	if (mpszErrMess)
	{
		sqlite_freemem(mpszErrMess);
		mpszErrMess = 0;
	}
}


////////////////////////////////////////////////////////////////////////////////

CppSQLiteBuffer::CppSQLiteBuffer()
{
	mpBuf = 0;
}


CppSQLiteBuffer::~CppSQLiteBuffer()
{
	clear();
}


void CppSQLiteBuffer::clear()
{
	if (mpBuf)
	{
		sqlite_freemem(mpBuf);
		mpBuf = 0;
	}

}


const char* CppSQLiteBuffer::format(const char* szFormat, ...)
{
	clear();
	va_list va;
	va_start(va, szFormat);
	mpBuf = sqlite_vmprintf(szFormat, va);
	va_end(va);
	return mpBuf;
}


////////////////////////////////////////////////////////////////////////////////

CppSQLiteBinary::CppSQLiteBinary() :
						mpBuf(0),
						mnBinaryLen(0),
						mnBufferLen(0),
						mnEncodedLen(0),
						mbEncoded(false)
{
}


CppSQLiteBinary::~CppSQLiteBinary()
{
	clear();
}


void CppSQLiteBinary::setBinary(const unsigned char* pBuf, int nLen)
{
	mpBuf = allocBuffer(nLen);
	memcpy(mpBuf, pBuf, nLen);
}


void CppSQLiteBinary::setEncoded(const unsigned char* pBuf)
{
	clear();

	mnEncodedLen = strlen((const char*)pBuf);
	mnBufferLen = mnEncodedLen + 1; // Allow for NULL terminator

	mpBuf = (unsigned char*)malloc(mnBufferLen);

	if (!mpBuf)
	{
		throw CppSQLiteException(CPPSQLITE_ERROR,
								"Cannot allocate memory",
								DONT_DELETE_MSG);
	}

	memcpy(mpBuf, pBuf, mnBufferLen);
	mbEncoded = true;
}


const unsigned char* CppSQLiteBinary::getEncoded()
{
	if (!mbEncoded)
	{
		unsigned char* ptmp = (unsigned char*)malloc(mnBinaryLen);
		memcpy(ptmp, mpBuf, mnBinaryLen);
		mnEncodedLen = sqlite_encode_binary(ptmp, mnBinaryLen, mpBuf);
		free(ptmp);
		mbEncoded = true;
	}

	return mpBuf;
}


const unsigned char* CppSQLiteBinary::getBinary()
{
	if (mbEncoded)
	{
		// in/out buffers can be the same
		mnBinaryLen = sqlite_decode_binary(mpBuf, mpBuf);

		if (mnBinaryLen == -1)
		{
			throw CppSQLiteException(CPPSQLITE_ERROR,
									"Cannot decode binary",
									DONT_DELETE_MSG);
		}

		mbEncoded = false;
	}

	return mpBuf;
}


int CppSQLiteBinary::getBinaryLength()
{
	getBinary();
	return mnBinaryLen;
}


unsigned char* CppSQLiteBinary::allocBuffer(int nLen)
{
	clear();

	// Allow extra space for encoded binary as per comments in
	// SQLite encode.c See bottom of this file for implementation
	// of SQLite functions use 3 instead of 2 just to be sure ;-)
	mnBinaryLen = nLen;
	mnBufferLen = 3 + (257*nLen)/254;

	mpBuf = (unsigned char*)malloc(mnBufferLen);

	if (!mpBuf)
	{
		throw CppSQLiteException(CPPSQLITE_ERROR,
								"Cannot allocate memory",
								DONT_DELETE_MSG);
	}

	mbEncoded = false;

	return mpBuf;
}


void CppSQLiteBinary::clear()
{
	if (mpBuf)
	{
		mnBinaryLen = 0;
		mnBufferLen = 0;
		free(mpBuf);
		mpBuf = 0;
	}
}


////////////////////////////////////////////////////////////////////////////////

CppSQLiteQuery::CppSQLiteQuery()
{
	mpVM = 0;
	mbEof = true;
	mnCols = 0;
	mpaszValues = 0;
	mpaszColNames = 0;
	mbOwnVM = false;
}


CppSQLiteQuery::CppSQLiteQuery(const CppSQLiteQuery& rQuery)
{
	mpVM = rQuery.mpVM;
	// Only one object can own the VM
	const_cast<CppSQLiteQuery&>(rQuery).mpVM = 0;
	mbEof = rQuery.mbEof;
	mnCols = rQuery.mnCols;
	mpaszValues = rQuery.mpaszValues;
	mpaszColNames = rQuery.mpaszColNames;
	mbOwnVM = rQuery.mbOwnVM;
}


CppSQLiteQuery::CppSQLiteQuery(sqlite_vm* pVM,
							bool bEof,
							int nCols,
							const char** paszValues,
							const char** paszColNames,
							bool bOwnVM/*=true*/)
{
	mpVM = pVM;
	mbEof = bEof;
	mnCols = nCols;
	mpaszValues = paszValues;
	mpaszColNames = paszColNames;
	mbOwnVM = bOwnVM;
}


CppSQLiteQuery::~CppSQLiteQuery()
{
	try
	{
		finalize();
	}
	catch (...)
	{
	}
}


CppSQLiteQuery& CppSQLiteQuery::operator=(const CppSQLiteQuery& rQuery)
{
	try
	{
		finalize();
	}
	catch (...)
	{
	}
	mpVM = rQuery.mpVM;
	// Only one object can own the VM
	const_cast<CppSQLiteQuery&>(rQuery).mpVM = 0;
	mbEof = rQuery.mbEof;
	mnCols = rQuery.mnCols;
	mpaszValues = rQuery.mpaszValues;
	mpaszColNames = rQuery.mpaszColNames;
	mbOwnVM = rQuery.mbOwnVM;
	return *this;
}


int CppSQLiteQuery::numFields()
{
	checkVM();
	return mnCols;
}


const char* CppSQLiteQuery::fieldValue(int nField)
{
	checkVM();

	if (nField < 0 || nField > mnCols-1)
	{
		throw CppSQLiteException(CPPSQLITE_ERROR,
								"Invalid field index requested",
								DONT_DELETE_MSG);
	}

	return mpaszValues[nField];
}


bool CppSQLiteQuery::fieldIsNull(int nField)
{
	checkVM();
	return (fieldValue(nField) == 0);
}



const char* CppSQLiteQuery::fieldName(int nCol)
{
	checkVM();

	if (nCol < 0 || nCol > mnCols-1)
	{
		throw CppSQLiteException(CPPSQLITE_ERROR,
								"Invalid field index requested",
								DONT_DELETE_MSG);
	}

	return mpaszColNames[nCol];
}


const char* CppSQLiteQuery::fieldType(int nCol)
{
	checkVM();

	if (nCol < 0 || nCol > mnCols-1)
	{
		throw CppSQLiteException(CPPSQLITE_ERROR,
								"Invalid field index requested",
								DONT_DELETE_MSG);
	}

	return mpaszColNames[mnCols+nCol];
}


bool CppSQLiteQuery::eof()
{
	checkVM();
	return mbEof;
}


void CppSQLiteQuery::nextRow()
{
	checkVM();

	int nRet = sqlite_step(mpVM, &mnCols, &mpaszValues, &mpaszColNames);

	if (nRet == SQLITE_DONE)
	{
		// no rows
		mbEof = true;
	}
	else if (nRet == SQLITE_ROW)
	{
		// more rows, nothing to do
	}
	else
	{
		char *szError = 0;
		nRet = sqlite_finalize(mpVM, &szError);
		mpVM = 0;
		throw CppSQLiteException(nRet, szError);
	}
}


void CppSQLiteQuery::finalize()
{
	if (mpVM && mbOwnVM)
	{
		char *szError = 0;
		int nError = sqlite_finalize(mpVM, &szError);
		mpVM = 0;

		if (nError != SQLITE_OK)
		{
			throw CppSQLiteException(nError, szError);
		}
	}
}


void CppSQLiteQuery::checkVM()
{
	if (mpVM == 0)
	{
		throw CppSQLiteException(CPPSQLITE_ERROR,
								"Null Virtual Machine pointer",
								DONT_DELETE_MSG);
	}
}


////////////////////////////////////////////////////////////////////////////////

CppSQLiteTable::CppSQLiteTable()
{
	mpaszResults = 0;
	mnRows = 0;
	mnCols = 0;
	mnCurrentRow = 0;
}


CppSQLiteTable::CppSQLiteTable(const CppSQLiteTable& rTable)
{
	mpaszResults = rTable.mpaszResults;
	// Only one object can own the results
	const_cast<CppSQLiteTable&>(rTable).mpaszResults = 0;
	mnRows = rTable.mnRows;
	mnCols = rTable.mnCols;
	mnCurrentRow = rTable.mnCurrentRow;
}


CppSQLiteTable::CppSQLiteTable(char** paszResults, int nRows, int nCols)
{
	mpaszResults = paszResults;
	mnRows = nRows;
	mnCols = nCols;
	mnCurrentRow = 0;
}


CppSQLiteTable::~CppSQLiteTable()
{
	try
	{
		finalize();
	}
	catch (...)
	{
	}
}


CppSQLiteTable& CppSQLiteTable::operator=(const CppSQLiteTable& rTable)
{
	try
	{
		finalize();
	}
	catch (...)
	{
	}
	mpaszResults = rTable.mpaszResults;
	// Only one object can own the results
	const_cast<CppSQLiteTable&>(rTable).mpaszResults = 0;
	mnRows = rTable.mnRows;
	mnCols = rTable.mnCols;
	mnCurrentRow = rTable.mnCurrentRow;
	return *this;
}


void CppSQLiteTable::finalize()
{
	if (mpaszResults)
	{
		sqlite_free_table(mpaszResults);
		mpaszResults = 0;
	}
}


int CppSQLiteTable::numFields()
{
	checkResults();
	return mnCols;
}


int CppSQLiteTable::numRows()
{
	checkResults();
	return mnRows;
}


const char* CppSQLiteTable::fieldValue(int nField)
{
	checkResults();

	if (nField < 0 || nField > mnCols-1)
	{
		throw CppSQLiteException(CPPSQLITE_ERROR,
								"Invalid field index requested",
								DONT_DELETE_MSG);
	}

	int nIndex = (mnCurrentRow*mnCols) + mnCols + nField;
	return mpaszResults[nIndex];
}


bool CppSQLiteTable::fieldIsNull(int nField)
{
	checkResults();
	return (fieldValue(nField) == 0);
}



const char* CppSQLiteTable::fieldName(int nCol)
{
	checkResults();

	if (nCol < 0 || nCol > mnCols-1)
	{
		throw CppSQLiteException(CPPSQLITE_ERROR,
								"Invalid field index requested",
								DONT_DELETE_MSG);
	}

	return mpaszResults[nCol];
}


void CppSQLiteTable::setRow(int nRow)
{
	checkResults();

	if (nRow < 0 || nRow > mnRows-1)
	{
		throw CppSQLiteException(CPPSQLITE_ERROR,
								"Invalid row index requested",
								DONT_DELETE_MSG);
	}

	mnCurrentRow = nRow;
}


void CppSQLiteTable::checkResults()
{
	if (mpaszResults == 0)
	{
		throw CppSQLiteException(CPPSQLITE_ERROR,
								"Null Results pointer",
								DONT_DELETE_MSG);
	}
}


////////////////////////////////////////////////////////////////////////////////

CppSQLiteStatement::CppSQLiteStatement()
{
	mpDB = 0;
	mpVM = 0;
}


CppSQLiteStatement::CppSQLiteStatement(const CppSQLiteStatement& rStatement)
{
	mpDB = rStatement.mpDB;
	mpVM = rStatement.mpVM;
	// Only one object can own VM
	const_cast<CppSQLiteStatement&>(rStatement).mpVM = 0;
}


CppSQLiteStatement::CppSQLiteStatement(sqlite* pDB, sqlite_vm* pVM)
{
	mpDB = pDB;
	mpVM = pVM;
}


CppSQLiteStatement::~CppSQLiteStatement()
{
	try
	{
		finalize();
	}
	catch (...)
	{
	}
}


CppSQLiteStatement& CppSQLiteStatement::operator=(const CppSQLiteStatement& rStatement)
{
	mpDB = rStatement.mpDB;
	mpVM = rStatement.mpVM;
	// Only one object can own VM
	const_cast<CppSQLiteStatement&>(rStatement).mpVM = 0;
	return *this;
}


int CppSQLiteStatement::execDML()
{
	checkDB();
	checkVM();

	int nCols(0);
	char* szError=0;
	const char** paszValues=0;
	const char** paszColNames=0;

	int nRet = sqlite_step(mpVM, &nCols, &paszValues, &paszColNames);

	if (nRet == SQLITE_DONE)
	{
		int nRowsChanged = sqlite_last_statement_changes(mpDB);

		nRet = sqlite_reset(mpVM, &szError);

		if (nRet != SQLITE_OK)
		{
			throw CppSQLiteException(nRet, szError);
		}

		return nRowsChanged;
	}
	else
	{
		nRet = sqlite_reset(mpVM, &szError);
		throw CppSQLiteException(nRet, szError);
	}
}


CppSQLiteQuery CppSQLiteStatement::execQuery()
{
	checkDB();
	checkVM();

	int nCols(0);
	const char** paszValues=0;
	const char** paszColNames=0;

	int nRet = sqlite_step(mpVM, &nCols, &paszValues, &paszColNames);

	if (nRet == SQLITE_DONE)
	{
		// no rows
		return CppSQLiteQuery(mpVM, true/*eof*/, nCols, paszValues, paszColNames, false);
	}
	else if (nRet == SQLITE_ROW)
	{
		// at least 1 row
		return CppSQLiteQuery(mpVM, false/*eof*/, nCols, paszValues, paszColNames, false);
	}
	else
	{
		char* szError=0;
		nRet = sqlite_finalize(mpVM, &szError);
		throw CppSQLiteException(nRet, szError);
	}
}


void CppSQLiteStatement::bind(int nParam, const char* szValue)
{
	checkVM();
	sqlite_bind(mpVM, nParam, szValue, -1, 1);
}


void CppSQLiteStatement::bind(int nParam, const int nValue)
{
	char buf[16];
	sprintf(buf, "%d", nValue);
	bind(nParam, buf);
}


void CppSQLiteStatement::bind(int nParam, const double dValue)
{
	char buf[16];
	sprintf(buf, "%f", dValue);
	bind(nParam, buf);
}


void CppSQLiteStatement::bindNull(int nParam)
{
	checkVM();
	sqlite_bind(mpVM, nParam, 0, -1, 1);
}


void CppSQLiteStatement::reset()
{
	if (mpVM)
	{
		char *szError = 0;
		int nError = sqlite_reset(mpVM, &szError);

		if (nError != SQLITE_OK)
		{
			throw CppSQLiteException(nError, szError);
		}
	}
}


void CppSQLiteStatement::finalize()
{
	if (mpVM)
	{
		char *szError = 0;
		int nError = sqlite_finalize(mpVM, &szError);
		mpVM = 0;

		if (nError != SQLITE_OK)
		{
			throw CppSQLiteException(nError, szError);
		}
	}
}


void CppSQLiteStatement::checkDB()
{
	if (mpDB == 0)
	{
		throw CppSQLiteException(CPPSQLITE_ERROR,
								"Database not open",
								DONT_DELETE_MSG);
	}
}


void CppSQLiteStatement::checkVM()
{
	if (mpVM == 0)
	{
		throw CppSQLiteException(CPPSQLITE_ERROR,
								"Null Virtual Machine pointer",
								DONT_DELETE_MSG);
	}
}


////////////////////////////////////////////////////////////////////////////////

CppSQLiteDB::CppSQLiteDB()
{
	mpDB = 0;
	mnBusyTimeoutMs = 60000; // 60 seconds
}


CppSQLiteDB::CppSQLiteDB(const CppSQLiteDB& db)
{
	mpDB = db.mpDB;
	mnBusyTimeoutMs = 60000; // 60 seconds
}


CppSQLiteDB::~CppSQLiteDB()
{
	close();
}


CppSQLiteDB& CppSQLiteDB::operator=(const CppSQLiteDB& db)
{
	mpDB = db.mpDB;
	mnBusyTimeoutMs = 60000; // 60 seconds
	return *this;
}


void CppSQLiteDB::open(const char* szFile)
{
	char *szError = 0;
	mpDB = sqlite_open(szFile, 0, &szError);

	if (!mpDB)
	{
		throw CppSQLiteException(SQLITE_CANTOPEN, szError);
	}

	setBusyTimeout(mnBusyTimeoutMs);
}


void CppSQLiteDB::close()
{
	if (mpDB)
	{
		sqlite_close(mpDB);
		mpDB = 0;
	}
}


CppSQLiteStatement CppSQLiteDB::compileStatement(const char* szSQL)
{
	checkDB();

	sqlite_vm* pVM = compile(szSQL);
	return CppSQLiteStatement(mpDB, pVM);
}


int CppSQLiteDB::execDML(const char* szSQL)
{
	checkDB();

	sqlite_vm* pVM = compile(szSQL);

	int nCols(0);
	char* szError=0;
	const char** paszValues=0;
	const char** paszColNames=0;

	int nRet = sqlite_step(pVM, &nCols, &paszValues, &paszColNames);

	if (nRet == SQLITE_DONE)
	{
		int nRowsChanged = sqlite_changes(mpDB);

		nRet = sqlite_finalize(pVM, &szError);

		if (nRet != SQLITE_OK)
		{
			throw CppSQLiteException(nRet, szError);
		}

		return nRowsChanged;
	}
	else
	{
		nRet = sqlite_finalize(pVM, &szError);
		throw CppSQLiteException(nRet, szError);
	}
}


CppSQLiteQuery CppSQLiteDB::execQuery(const char* szSQL)
{
	checkDB();

	sqlite_vm* pVM = compile(szSQL);

	int nCols(0);
	const char** paszValues=0;
	const char** paszColNames=0;

	int nRet = sqlite_step(pVM, &nCols, &paszValues, &paszColNames);

	if (nRet == SQLITE_DONE)
	{
		// no rows
		return CppSQLiteQuery(pVM, true/*eof*/, nCols, paszValues, paszColNames);
	}
	else if (nRet == SQLITE_ROW)
	{
		// at least 1 row
		return CppSQLiteQuery(pVM, false/*eof*/, nCols, paszValues, paszColNames);
	}
	else
	{
		char* szError=0;
		nRet = sqlite_finalize(pVM, &szError);
		throw CppSQLiteException(nRet, szError);
	}
}


int CppSQLiteDB::execScalar(const char* szSQL)
{
	CppSQLiteQuery q = execQuery(szSQL);

	if (q.eof() || q.numFields() < 1)
	{
		throw CppSQLiteException(CPPSQLITE_ERROR,
								"Invalid scalar query",
								DONT_DELETE_MSG);
	}

	return atoi(q.fieldValue(0));
}


CppSQLiteTable CppSQLiteDB::getTable(const char* szSQL)
{
	checkDB();

	char* szError=0;
	char** paszResults=0;
	int nRet;
	int nRows(0);
	int nCols(0);

	nRet = sqlite_get_table(mpDB, szSQL, &paszResults, &nRows, &nCols, &szError);

	if (nRet == SQLITE_OK)
	{
		return CppSQLiteTable(paszResults, nRows, nCols);
	}
	else
	{
		throw CppSQLiteException(nRet, szError);
	}
}


int CppSQLiteDB::lastRowId()
{
	return sqlite_last_insert_rowid(mpDB);
}


void CppSQLiteDB::setBusyTimeout(int nMillisecs)
{
	mnBusyTimeoutMs = nMillisecs;
	sqlite_busy_timeout(mpDB, mnBusyTimeoutMs);
}


void CppSQLiteDB::checkDB()
{
	if (!mpDB)
	{
		throw CppSQLiteException(CPPSQLITE_ERROR,
								"Database not open",
								DONT_DELETE_MSG);
	}
}


sqlite_vm* CppSQLiteDB::compile(const char* szSQL)
{
	checkDB();

	char* szError=0;
	const char* szTail=0;
	sqlite_vm* pVM;

	int nRet = sqlite_compile(mpDB, szSQL, &szTail, &pVM, &szError);

	if (nRet != SQLITE_OK)
	{
		throw CppSQLiteException(nRet, szError);
	}

	return pVM;
}


////////////////////////////////////////////////////////////////////////////////
// SQLite encode.c reproduced here, containing implementation notes and source
// for sqlite_encode_binary() and sqlite_decode_binary() 
////////////////////////////////////////////////////////////////////////////////

/*
** 2002 April 25
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains helper routines used to translate binary data into
** a null-terminated string (suitable for use in SQLite) and back again.
** These are convenience routines for use by people who want to store binary
** data in an SQLite database.  The code in this file is not used by any other
** part of the SQLite library.
**
** $Id: encode.c,v 1.10 2004/01/14 21:59:23 drh Exp $
*/

/*
** How This Encoder Works
**
** The output is allowed to contain any character except 0x27 (') and
** 0x00.  This is accomplished by using an escape character to encode
** 0x27 and 0x00 as a two-byte sequence.  The escape character is always
** 0x01.  An 0x00 is encoded as the two byte sequence 0x01 0x01.  The
** 0x27 character is encoded as the two byte sequence 0x01 0x03.  Finally,
** the escape character itself is encoded as the two-character sequence
** 0x01 0x02.
**
** To summarize, the encoder works by using an escape sequences as follows:
**
**       0x00  ->  0x01 0x01
**       0x01  ->  0x01 0x02
**       0x27  ->  0x01 0x03
**
** If that were all the encoder did, it would work, but in certain cases
** it could double the size of the encoded string.  For example, to
** encode a string of 100 0x27 characters would require 100 instances of
** the 0x01 0x03 escape sequence resulting in a 200-character output.
** We would prefer to keep the size of the encoded string smaller than
** this.
**
** To minimize the encoding size, we first add a fixed offset value to each 
** byte in the sequence.  The addition is modulo 256.  (That is to say, if
** the sum of the original character value and the offset exceeds 256, then
** the higher order bits are truncated.)  The offset is chosen to minimize
** the number of characters in the string that need to be escaped.  For
** example, in the case above where the string was composed of 100 0x27
** characters, the offset might be 0x01.  Each of the 0x27 characters would
** then be converted into an 0x28 character which would not need to be
** escaped at all and so the 100 character input string would be converted
** into just 100 characters of output.  Actually 101 characters of output - 
** we have to record the offset used as the first byte in the sequence so
** that the string can be decoded.  Since the offset value is stored as
** part of the output string and the output string is not allowed to contain
** characters 0x00 or 0x27, the offset cannot be 0x00 or 0x27.
**
** Here, then, are the encoding steps:
**
**     (1)   Choose an offset value and make it the first character of
**           output.
**
**     (2)   Copy each input character into the output buffer, one by
**           one, adding the offset value as you copy.
**
**     (3)   If the value of an input character plus offset is 0x00, replace
**           that one character by the two-character sequence 0x01 0x01.
**           If the sum is 0x01, replace it with 0x01 0x02.  If the sum
**           is 0x27, replace it with 0x01 0x03.
**
**     (4)   Put a 0x00 terminator at the end of the output.
**
** Decoding is obvious:
**
**     (5)   Copy encoded characters except the first into the decode 
**           buffer.  Set the first encoded character aside for use as
**           the offset in step 7 below.
**
**     (6)   Convert each 0x01 0x01 sequence into a single character 0x00.
**           Convert 0x01 0x02 into 0x01.  Convert 0x01 0x03 into 0x27.
**
**     (7)   Subtract the offset value that was the first character of
**           the encoded buffer from all characters in the output buffer.
**
** The only tricky part is step (1) - how to compute an offset value to
** minimize the size of the output buffer.  This is accomplished by testing
** all offset values and picking the one that results in the fewest number
** of escapes.  To do that, we first scan the entire input and count the
** number of occurances of each character value in the input.  Suppose
** the number of 0x00 characters is N(0), the number of occurances of 0x01
** is N(1), and so forth up to the number of occurances of 0xff is N(255).
** An offset of 0 is not allowed so we don't have to test it.  The number
** of escapes required for an offset of 1 is N(1)+N(2)+N(40).  The number
** of escapes required for an offset of 2 is N(2)+N(3)+N(41).  And so forth.
** In this way we find the offset that gives the minimum number of escapes,
** and thus minimizes the length of the output string.
*/

/*
** Encode a binary buffer "in" of size n bytes so that it contains
** no instances of characters '\'' or '\000'.  The output is 
** null-terminated and can be used as a string value in an INSERT
** or UPDATE statement.  Use sqlite_decode_binary() to convert the
** string back into its original binary.
**
** The result is written into a preallocated output buffer "out".
** "out" must be able to hold at least 2 +(257*n)/254 bytes.
** In other words, the output will be expanded by as much as 3
** bytes for every 254 bytes of input plus 2 bytes of fixed overhead.
** (This is approximately 2 + 1.0118*n or about a 1.2% size increase.)
**
** The return value is the number of characters in the encoded
** string, excluding the "\000" terminator.
*/
int sqlite_encode_binary(const unsigned char *in, int n, unsigned char *out){
  int i, j, e, m;
  int cnt[256];
  if( n<=0 ){
    out[0] = 'x';
    out[1] = 0;
    return 1;
  }
  memset(cnt, 0, sizeof(cnt));
  for(i=n-1; i>=0; i--){ cnt[in[i]]++; }
  m = n;
  for(i=1; i<256; i++){
    int sum;
    if( i=='\'' ) continue;
    sum = cnt[i] + cnt[(i+1)&0xff] + cnt[(i+'\'')&0xff];
    if( sum<m ){
      m = sum;
      e = i;
      if( m==0 ) break;
    }
  }
  out[0] = e;
  j = 1;
  for(i=0; i<n; i++){
    int c = (in[i] - e)&0xff;
    if( c==0 ){
      out[j++] = 1;
      out[j++] = 1;
    }else if( c==1 ){
      out[j++] = 1;
      out[j++] = 2;
    }else if( c=='\'' ){
      out[j++] = 1;
      out[j++] = 3;
    }else{
      out[j++] = c;
    }
  }
  out[j] = 0;
  return j;
}

/*
** Decode the string "in" into binary data and write it into "out".
** This routine reverses the encoding created by sqlite_encode_binary().
** The output will always be a few bytes less than the input.  The number
** of bytes of output is returned.  If the input is not a well-formed
** encoding, -1 is returned.
**
** The "in" and "out" parameters may point to the same buffer in order
** to decode a string in place.
*/
int sqlite_decode_binary(const unsigned char *in, unsigned char *out){
  int i, c, e;
  e = *(in++);
  i = 0;
  while( (c = *(in++))!=0 ){
    if( c==1 ){
      c = *(in++);
      if( c==1 ){
        c = 0;
      }else if( c==2 ){
        c = 1;
      }else if( c==3 ){
        c = '\'';
      }else{
        return -1;
      }
    }
    out[i++] = (c + e)&0xff;
  }
  return i;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United Kingdom United Kingdom
Software developer using C/C++, ASP, .NET and SQL Server/Oracle relational databases.

Comments and Discussions