Example #1
0
void CVoxSQLite::InsertGroup( const char* username, Group& rGroup )
{
	//TODO: compile as a member var?
	std::string	strSql = "INSERT INTO [Group] "
						 "( [username], [name] ) "
						 "VALUES( ?, ? ); ";

	try
	{
		CppSQLite3Statement stmt = m_db.compileStatement( strSql.c_str() );

		stmt.bind( 1, username );
		stmt.bind( 2, rGroup.getName() );

		stmt.execDML();		//We expect a return value == 1 (Number of rows changed);
		stmt.reset();

		int nId = (int)m_db.lastRowId();
	}

	catch (CppSQLite3Exception& e)
	{
		e.errorCode();
	}
}
Example #2
0
void CVoxSQLite::GetGroups( const char* username, Groups& rList )
{
	CppSQLite3Buffer buf;
	buf.format( "SELECT * from [Group] WHERE [username] = %Q;", username );

	try
	{
		CppSQLite3Statement stmt = m_db.compileStatement( (const char*)buf );

		int				nContactId	= 0;
		std::string		type		= "";
		CppSQLite3Query q			= stmt.execQuery();
		Group			grp;

		//Process record set.
        while (!q.eof())
        {
			grp.setUsername( q.getStringField( 0 ) );
			grp.setName    ( q.getStringField( 1 ) );

			rList.Add( &grp );

			q.nextRow();
        }

		stmt.reset();
	}

	catch (CppSQLite3Exception& e)
	{
		e.errorCode();
	}
}
Example #3
0
void CVoxSQLite::GetMergedContacts( const char* parent_username, MergedContacts& rList )
{
	CppSQLite3Buffer buf;
	buf.format( "SELECT * from [MergedContact] WHERE [parent_username] = %Q;", parent_username );

	try
	{
		CppSQLite3Statement stmt = m_db.compileStatement( (const char*)buf );

		int				nContactId	= 0;
		std::string		type		= "";
		CppSQLite3Query q			= stmt.execQuery();
		MergedContact	mc;

		//Process record set.
        while (!q.eof())
        {
			mc.setParentUsername( q.getStringField( 0 ) );
			mc.setUsername      ( q.getStringField( 1 ) );

			rList.Add( &mc );

			q.nextRow();
        }

		stmt.reset();
	}

	catch (CppSQLite3Exception& e)
	{
		e.errorCode();
	}
}
Example #4
0
void CVoxSQLite::InsertMergedContact( const char* strContactUsername, const char* strUsername )
{
	//TODO: compile as a member var?
	std::string	strSql = "INSERT INTO [MergedContact] "
						 "( [parent_username], [username] ) "
						 "VALUES( ?, ? ); ";

	try
	{
		CppSQLite3Statement stmt = m_db.compileStatement( strSql.c_str() );

		stmt.bind( 1, strContactUsername );
		stmt.bind( 2, strUsername );

		stmt.execDML();		//We expect a return value == 1 (Number of rows changed);
		stmt.reset();

		int nId = (int)m_db.lastRowId();
	}

	catch (CppSQLite3Exception& e)
	{
		e.errorCode();
	}
}
Example #5
0
void CVoxSQLite::InsertUrl ( int nId, const std::string& type, const std::string& url, EnumVisibility::Visibility vis )
{
	if ( IsValidUrl( url.c_str() ) )
	{
		std::string	strSql = "INSERT INTO Url "
			"( [profile_id], [type], [url], [visibility] ) "
							 "VALUES( ?, ?, ?, ? ); ";

		try
		{
			//TODO: compile as a member var?
			CppSQLite3Statement stmt = m_db.compileStatement( strSql.c_str() );

			stmt.bind( 1, nId			);
			stmt.bind( 2, type.c_str()	);
			stmt.bind( 3, url.c_str()   );
			stmt.bind( 4, (int)vis		);

			stmt.execDML();		//We expect a return value == 1 (Number of rows changed);
			stmt.reset();
		}

		catch (CppSQLite3Exception& e)
		{
			e.errorCode();
		}
	}
}
Example #6
0
void CVoxSQLite::InsertStreetAddress( int nId, StreetAddress& addr )
{
	std::string	strSql = "INSERT INTO StreetAddress "
		"( [profile_id], [type], [street], [locality], [region], [postcode], [country], [visibility] ) "
						 "VALUES( ?, ?, ?, ?, ?, ?, ?, ? ); ";

	try
	{
		//TODO: compile as a member var?
		CppSQLite3Statement stmt = m_db.compileStatement( strSql.c_str() );

		stmt.bind( 1, nId	);
		stmt.bind( 2, addr.getType().c_str()		);
		stmt.bind( 3, addr.getStreet1().c_str() 	);
		stmt.bind( 4, addr.getCity().c_str()		);
		stmt.bind( 5, addr.getStateProvince().c_str());
		stmt.bind( 6, addr.getPostalCode().c_str()	);
		stmt.bind( 7, addr.getCountry().c_str()		);
		stmt.bind( 8, (int) addr.getVisibility()	);

		stmt.execDML();		//We expect a return value == 1 (Number of rows changed);
		stmt.reset();
	}

	catch (CppSQLite3Exception& e)
	{
		e.errorCode();
	}
}
Example #7
0
void CVoxSQLite::InsertContact( Contact& rContact )
{
	//TODO: compile as a member var?
	std::string	strSql = "INSERT INTO Contact "
						 "( [username], [nickname], [merged_parent_username]) "
						 "VALUES( ?, ?, ? ); ";

	try
	{
		CppSQLite3Statement stmt = m_db.compileStatement( strSql.c_str() );

//		stmt.bind( 1, rContact.getName().c_str()	);
//		stmt.bind( 2, rContact.getNickname().c_str());
//		stmt.bind( 3, rContact.getMergedContact().c_str() );

		stmt.execDML();		//We expect a return value == 1 (Number of rows changed);
		stmt.reset();

		int nContactId = (int)m_db.lastRowId();

//		InsertGroups	    ( rContact.getName().c_str(), rContact.getGroups()			);
//		InsertMergedContacts( rContact.getName().c_str(), rContact.getMergedContacts()	);
	}

	catch (CppSQLite3Exception& e)
	{
		e.errorCode();
	}
}
Example #8
0
//##ModelId=474D30760272
bool CClip_ImportExport::ExportToSqliteDB(CppSQLite3DB &db)
{
	bool bRet = false;
	try
	{
		//Add to Main Table
		m_Desc.Replace(_T("'"), _T("''"));
		db.execDMLEx(_T("insert into Main values(NULL, %d, '%s');"), CURRENT_EXPORT_VERSION, m_Desc);
		long lId = (long)db.lastRowId();

		//Add to Data table
		CClipFormat* pCF;
		CppSQLite3Statement stmt = db.compileStatement(_T("insert into Data values (NULL, ?, ?, ?, ?);"));

		for(int i = m_Formats.GetSize()-1; i >= 0 ; i--)
		{
			pCF = & m_Formats.ElementAt(i);

			stmt.bind(1, lId);
			stmt.bind(2, GetFormatName(pCF->m_cfType));
			long lOriginalSize = GlobalSize(pCF->m_hgData);
			stmt.bind(3, lOriginalSize);

			const unsigned char *Data = (const unsigned char *)GlobalLock(pCF->m_hgData);
			if(Data)
			{
				//First compress the data
				long lZippedSize = compressBound(lOriginalSize);
				Bytef *pZipped = new Bytef[lZippedSize];
				if(pZipped)
				{				
					int nZipReturn = compress(pZipped, (uLongf *)&lZippedSize, (const Bytef *)Data, lOriginalSize);
					if(nZipReturn == Z_OK)
					{
						stmt.bind(4, pZipped, lZippedSize);
					}

					delete []pZipped;
					pZipped = NULL;
				}
			}
			GlobalUnlock(pCF->m_hgData);

			stmt.execDML();
			stmt.reset();

			m_Formats.RemoveAt(i);
		}

		bRet = true;
	}
	CATCH_SQLITE_EXCEPTION_AND_RETURN(false)

	return bRet;
}
Example #9
0
void CVoxSQLite::GetProfile( const char* username, Profile& rProfile )
{
	CppSQLite3Buffer buf;
	buf.format( "SELECT * from Profile WHERE username = %Q;", username );

	try
	{
		CppSQLite3Statement stmt = m_db.compileStatement( (const char*)buf );

		int	nProfileId	  = 0;
		CppSQLite3Query q = stmt.execQuery();

		//Process record set.
        while (!q.eof())
        {
			nProfileId = q.getIntField(0);

			rProfile.setFirstName	( q.getStringField(2) );
			rProfile.setLastName	( q.getStringField(3) );
			rProfile.setAlias		( q.getStringField(4) );
			rProfile.setSmsSignature( q.getStringField(5) );
			rProfile.setCompany		( q.getStringField(6) );
			rProfile.setSex			( (EnumSex::Sex)q.getIntField(7)	  );
			rProfile.setNotes		( q.getStringField(10) );
//			rProfile.setBirthday( q.getStringField(8) );
//			photo (filename)
//TODO		rProfile.setPhoto( q.getBlobField(9) );
			
			//Address, email, phone numbers, and URLs will be in separate tables to allow for easy
			GetStreetAddresses( nProfileId, rProfile.getStreetAddresses() );
			GetEmailAddresses ( nProfileId, rProfile.getEmailAddresses()  );
			GetTelephones	  ( nProfileId, rProfile.getTelephones()	  );
			GetUrls			  ( nProfileId, rProfile.getUrls()			  );

			q.nextRow();
        }

		stmt.reset();
	}

	catch (CppSQLite3Exception& e)
	{
		e.errorCode();
	}
}
Example #10
0
void CVoxSQLite::GetStreetAddresses( int nProfileId, StreetAddresses& rAddrs )
{
	CppSQLite3Buffer buf;
	buf.format( "SELECT * from StreetAddress WHERE profile_id = %d;", nProfileId );

	try
	{
		CppSQLite3Statement stmt = m_db.compileStatement( (const char*)buf );

		int				nId		= 0;
		CppSQLite3Query q		= stmt.execQuery();

		StreetAddress	addr;

		//Process record set.
        while (!q.eof())
        {
//			"( [profile_id], [type], [street], [locality], [region], [postcode], [country], [visibility] ) "
			nId  = q.getIntField(0);			//Not part of Profile.

			addr.setType		 ( q.getStringField(1) );
			addr.setStreet1		 ( q.getStringField(2) );
			addr.setCity		 ( q.getStringField(3) );
			addr.setStateProvince( q.getStringField(4) );
			addr.setPostalCode	 ( q.getStringField(5) );
			addr.setCountry		 ( q.getStringField(6) );
			addr.setVisibility   ( (EnumVisibility::Visibility)q.getIntField(7) );

			rAddrs.Add( &addr );

			q.nextRow();
        }

		stmt.reset();
	}

	catch (CppSQLite3Exception& e)
	{
		e.errorCode();
	}
}
Example #11
0
void CVoxSQLite::InsertProfile( const char* username, Profile& rProfile )
{
	//TODO: compile as a member var?
	std::string	strSql = "INSERT INTO Profile "
						 "( [username], [first_name], [last_name], [alias], [sms_signature], [company], [notes], [sex] ) "
//						 "[birthday], [photo] ) "		//TODO
						 "VALUES( ?, ?, ?, ?, ?, ?, ?, ? ); ";

	try
	{
		CppSQLite3Statement stmt = m_db.compileStatement( strSql.c_str() );

		stmt.bind( 1, username	);
		stmt.bind( 2, rProfile.getFirstName().c_str()	);
		stmt.bind( 3, rProfile.getLastName().c_str() 	);
		stmt.bind( 4, rProfile.getAlias().c_str()		);
		stmt.bind( 5, rProfile.getSmsSignature().c_str());
		stmt.bind( 6, rProfile.getCompany().c_str()		);
		stmt.bind( 7, rProfile.getNotes().c_str()		);
		stmt.bind( 8, rProfile.getSex()					);
//		stmt.bind( 10, rProfile.getBirthday()			);
//		stmt.bind( 11, rProfile.getPhoto()				);

		stmt.execDML();		//We expect a return value == 1 (Number of rows changed);
		stmt.reset();

		int nId = (int)m_db.lastRowId();

		InsertUrls			 ( nId, rProfile.getUrls()			  );
		InsertStreetAddresses( nId, rProfile.getStreetAddresses() );
		InsertEmailAddresses ( nId, rProfile.getEmailAddresses()  );
		InsertTelephones	 ( nId, rProfile.getTelephones()	  );
	}

	catch (CppSQLite3Exception& e)
	{
		e.errorCode();
	}
}
Example #12
0
void CVoxSQLite::GetEmailAddresses( int nProfileId, EmailAddresses& rList )
{
	CppSQLite3Buffer buf;
	buf.format( "SELECT * from EmailAddress WHERE profile_id = %d;", nProfileId );

	try
	{
		CppSQLite3Statement stmt = m_db.compileStatement( (const char*)buf );

		int				nProfileId	= 0;
		std::string		type		= "";
		EmailAddress	addr;
		CppSQLite3Query q			= stmt.execQuery();

		//Process record set.
        while (!q.eof())
        {
//			"( [profile_id], [type], [email], [visiblity]
			nProfileId = q.getIntField(0);		//Not part of Profile.
			type = q.getStringField( 1 );		//Use to determine which address to update.

			addr.setType	  ( q.getStringField(1) );
			addr.setAddress	  ( q.getStringField(2) );
			addr.setVisibility( (EnumVisibility::Visibility) q.getIntField(3)	);

			rList.Add( &addr );

			q.nextRow();
        }

		stmt.reset();
	}

	catch (CppSQLite3Exception& e)
	{
		e.errorCode();
	}
}
Example #13
0
void CVoxSQLite::GetUrls( int nProfileId, Urls& rList )
{
	CppSQLite3Buffer buf;
	buf.format( "SELECT * from Url WHERE profile_id = %d;", nProfileId );

	try
	{
		CppSQLite3Statement stmt = m_db.compileStatement( (const char*)buf );

		int				nProfileId	= 0;
		std::string		type		= "";
		CppSQLite3Query q			= stmt.execQuery();
		Url				url;

		//Process record set.
        while (!q.eof())
        {
//			"( [profile_id], [type], [address]
			nProfileId = q.getIntField(0);		//Not part of Profile.

			url.setType   ( q.getStringField( 1 ) );
			url.setUrl    ( q.getStringField( 2 ) );
			url.setVisibility( (EnumVisibility::Visibility)q.getIntField(3) );

			rList.Add( &url );

			q.nextRow();
        }

		stmt.reset();
	}

	catch (CppSQLite3Exception& e)
	{
		e.errorCode();
	}
}
Example #14
0
void CVoxSQLite::GetContact( const char* username, Contact& c )
{
	CppSQLite3Buffer buf;
	buf.format( "SELECT * from Contact WHERE username = %Q;", username );

	try
	{
		CppSQLite3Statement stmt = m_db.compileStatement( (const char*)buf );

		int	nContactId = 0;
		CppSQLite3Query q = stmt.execQuery();

		//Process record set.
        while (!q.eof())
        {
			nContactId = q.getIntField(0);

//			c.setName		( q.getStringField(1) );
//			c.setNickname	( q.getStringField(2) );
//			c.setBirthday	( q.getStringField(3) );
//			c.setMergedContact( q.getStringField(3) );

			GetMergedContacts( username, c.getMergedContacts() );
			GetGroups		 ( username, c.getGroups() );
			GetProfile		 ( username, c );

			q.nextRow();
        }

		stmt.reset();
	}

	catch (CppSQLite3Exception& e)
	{
		e.errorCode();
	}
}
Example #15
0
void CVoxSQLite::GetTelephones( int nProfileId, Telephones& rList )
{
	CppSQLite3Buffer buf;
	buf.format( "SELECT * from Telephone WHERE profile_id = %d;", nProfileId );

	try
	{
		CppSQLite3Statement stmt = m_db.compileStatement( (const char*)buf );

		int				nProfileId	= 0;
		std::string		type		= "";
		CppSQLite3Query q			= stmt.execQuery();
		Telephone		tel;

		//Process record set.
        while (!q.eof())
        {
//			"( [profile_id], [type], [number]
			nProfileId = q.getIntField(0);		//Not part of Profile.

			tel.setType  ( q.getStringField( 1 ) );
			tel.setNumber( q.getStringField( 2 ) );

			rList.Add( &tel );

			q.nextRow();
        }

		stmt.reset();
	}

	catch (CppSQLite3Exception& e)
	{
		e.errorCode();
	}
}
Example #16
0
void testCppSQLite()
{
    try
    {
        int i, fld;
        time_t tmStart, tmEnd;
        
        remove(gszFile);
        
        CppSQLite3DB* db = getSQLiteDB();
        cout << "SQLite Version: " << db->SQLiteVersion() << endl;
        
        cout << endl << "Creating emp table" << endl;
        db->execDML("create table emp(empno int, empname char(20));");
        ///////////////////////////////////////////////////////////////
        // Execute some DML, and print number of rows affected by each one
        ///////////////////////////////////////////////////////////////
        cout << endl << "DML tests" << endl;
        int nRows = db->execDML("insert into emp values (7, 'David Beckham');");
        cout << nRows << " rows inserted" << endl;
        
        nRows = db->execDML(
                           "update emp set empname = 'Christiano Ronaldo' where empno = 7;");
        cout << nRows << " rows updated" << endl;
        
        nRows = db->execDML("delete from emp where empno = 7;");
        cout << nRows << " rows deleted" << endl;
        
        /////////////////////////////////////////////////////////////////
        // Transaction Demo
        // The transaction could just as easily have been rolled back
        /////////////////////////////////////////////////////////////////
        int nRowsToCreate(50000);
        cout << endl << "Transaction test, creating " << nRowsToCreate;
        cout << " rows please wait..." << endl;
        tmStart = time(0);
        db->execDML("begin transaction;");
        
        for (i = 0; i < nRowsToCreate; i++)
        {
            char buf[128];
            sprintf(buf, "insert into emp values (%d, 'Empname%06d');", i, i);
            db->execDML(buf);
        }
        
        db->execDML("commit transaction;");
        tmEnd = time(0);
        
        ////////////////////////////////////////////////////////////////
        // Demonstrate CppSQLiteDB::execScalar()
        ////////////////////////////////////////////////////////////////
        cout << db->execScalar("select count(*) from emp;") 
        << " rows in emp table in ";
        cout << tmEnd-tmStart << " seconds (that was fast!)" << endl;
        
        ////////////////////////////////////////////////////////////////
        // Re-create emp table with auto-increment field
        ////////////////////////////////////////////////////////////////
        cout << endl << "Auto increment test" << endl;
        db->execDML("drop table emp;");
        db->execDML(
                   "create table emp(empno integer primary key, empname char(20));");
        cout << nRows << " rows deleted" << endl;
        
        for (i = 0; i < 5; i++)
        {
            char buf[128];
            sprintf(buf, 
                    "insert into emp (empname) values ('Empname%06d');", i+1);
            db->execDML(buf);
            cout << " primary key: " << db->lastRowId() << endl;
        }
        
        ///////////////////////////////////////////////////////////////////
        // Query data and also show results of inserts into auto-increment field
        //////////////////////////////////////////////////////////////////
        cout << endl << "Select statement test" << endl;
        CppSQLite3Query q = db->execQuery("select * from emp order by 1;");
        
        for (fld = 0; fld < q.numFields(); fld++)
        {
            cout << q.fieldName(fld) << "(" << q.fieldDeclType(fld) << ")|";
        }
        cout << endl;
        
        while (!q.eof())
        {
            cout << q.fieldValue(0) << "|";
            cout << q.fieldValue(1) << "|" << endl;
            q.nextRow();
        }
        
        ///////////////////////////////////////////////////////////////
        // SQLite's printf() functionality. Handles embedded quotes and NULLs
        ////////////////////////////////////////////////////////////////
        cout << endl << "SQLite sprintf test" << endl;
        CppSQLite3Buffer bufSQL;
        bufSQL.format("insert into emp (empname) values (%Q);", "He's bad");
        cout << (const char*)bufSQL << endl;
        db->execDML(bufSQL);
        
        bufSQL.format("insert into emp (empname) values (%Q);", NULL);
        cout << (const char*)bufSQL << endl;
        db->execDML(bufSQL);
        
        ////////////////////////////////////////////////////////////////////
        // Fetch table at once, and also show how to 
        // use CppSQLiteTable::setRow() method
        //////////////////////////////////////////////////////////////////
        cout << endl << "getTable() test" << endl;
        CppSQLite3Table t = db->getTable("select * from emp order by 1;");
        
        for (fld = 0; fld < t.numFields(); fld++)
        {
            cout << t.fieldName(fld) << "|";
        }
        cout << endl;
        for (int row = 0; row < t.numRows(); row++)
        {
            t.setRow(row);
            for (int fld = 0; fld < t.numFields(); fld++)
            {
                if (!t.fieldIsNull(fld))
                    cout << t.fieldValue(fld) << "|";
                else
                    cout << "NULL" << "|";
            }
            cout << endl;
        }
        
        ////////////////////////////////////////////////////////////////////
        // Test CppSQLiteBinary by storing/retrieving some binary data, checking
        // it afterwards to make sure it is the same
        //////////////////////////////////////////////////////////////////
        cout << endl << "Binary data test" << endl;
        db->execDML("create table bindata(desc char(10), data blob);");
        
        unsigned char bin[256];
        CppSQLite3Binary blob;
        
        for (i = 0; i < sizeof bin; i++)
        {
            bin[i] = i;
        }
        
        blob.setBinary(bin, sizeof bin);
        
        bufSQL.format("insert into bindata values ('testing', %Q);", 
                      blob.getEncoded());
        db->execDML(bufSQL);
        cout << "Stored binary Length: " << sizeof bin << endl;
        
        q = db->execQuery("select data from bindata where desc = 'testing';");
        
        if (!q.eof())
        {
            blob.setEncoded((unsigned char*)q.fieldValue("data"));
            cout << "Retrieved binary Length: " 
            << blob.getBinaryLength() << endl;
        }
        
        const unsigned char* pbin = blob.getBinary();
        for (i = 0; i < sizeof bin; i++)
        {
            if (pbin[i] != i)
            {
                cout << "Problem: i: ," << i << " bin[i]: " 
                << pbin[i] << endl;
            }
        }
        
        /////////////////////////////////////////////////////////
        // Pre-compiled Statements Demo
        /////////////////////////////////////////////////////////////
        cout << endl << "Transaction test, creating " << nRowsToCreate;
        cout << " rows please wait..." << endl;
        db->execDML("drop table emp;");
        db->execDML("create table emp(empno int, empname char(20));");
        tmStart = time(0);
        db->execDML("begin transaction;");
        
        CppSQLite3Statement stmt = db->compileStatement(
                                                      "insert into emp values (?, ?);");
        for (i = 0; i < nRowsToCreate; i++)
        {
            char buf[16];
            sprintf(buf, "EmpName%06d", i);
            stmt.bind(1, i);
            stmt.bind(2, buf);
            stmt.execDML();
            stmt.reset();
        }
        
        db->execDML("commit transaction;");
        tmEnd = time(0);
        
        cout << db->execScalar("select count(*) from emp;") 
        << " rows in emp table in ";
        cout << tmEnd-tmStart << " seconds (that was even faster!)" << endl;
        cout << endl << "End of tests" << endl;
    }
    catch (CppSQLite3Exception& e)
    {
        cerr << e.errorCode() << ":" << e.errorMessage() << endl;
    }
    
}
Example #17
0
EXPORT_C gint32 CContactDb::UpdateEntity(CDbEntity * pEntity)
	{
	int i;
	char sql[256] = {0};
	OpenDatabase();
	
	try 
		{
		m_dbBeluga.execDML("begin transaction;");
		/* update contact entity */
		strcpy(sql, "update contact set "); 
		for (i=1; i<ContactField_EndFlag; i++)
			{
			GString * fieldName = (GString*)g_ptr_array_index(m_pFieldsName, i);
			strcat(sql, fieldName->str);
			strcat(sql, " = ?");
			if (i != ContactField_EndFlag - 1)
				strcat(sql, ", ");
			}
		strcat(sql, "where cid = ?;");
		
		CppSQLite3Statement statement = m_dbBeluga.compileStatement(sql);

		GString * idValue = NULL;
		if (ECode_No_Error == pEntity->GetFieldValue(0, &idValue))
		{
			statement.bind(ContactField_EndFlag, idValue->str);
			g_string_free(idValue, TRUE);
		}
		else
			statement.bindNull(ContactField_EndFlag);

		for (i=1; i<ContactField_EndFlag; i++)
			{
			GString * fieldValue = NULL;
			if (ECode_No_Error == pEntity->GetFieldValue(i, &fieldValue))
				{
				statement.bind(i, fieldValue->str);
				g_string_free(fieldValue, TRUE);
				}
			else
				statement.bindNull(i);
			}
		statement.execDML();
		statement.reset();
		
		/* update contact_ext entity */
		CContact * contact = (CContact*)pEntity;
		GString * fieldValue = NULL;
		contact->GetFieldValue(ContactField_Type, &fieldValue);
		if (ContactType_Phone == atoi(fieldValue->str))
			{
			CPhoneContact * phonecontact = (CPhoneContact*)pEntity;
			GString * fieldId = NULL;
			phonecontact->GetFieldValue(ContactField_Id, &fieldId);
			memset(sql, 0, sizeof(sql));
			sprintf(sql, "delete from contact_ext where cid = %d;", atoi(fieldId->str));
			m_dbBeluga.execDML(sql);
			
			/* insert phones */
			GHashTable * phones = NULL;
			phonecontact->GetAllPhones(&phones);
			g_hash_table_foreach(phones, update_contact_ext_row, phonecontact);
			g_hash_table_destroy(phones);
			
			/* insert emails */
			GHashTable * emails = NULL;
			phonecontact->GetAllEmails(&emails);
			g_hash_table_foreach(emails, update_contact_ext_row, phonecontact);
			g_hash_table_destroy(emails);
			
			/* insert ims */
			GHashTable * ims = NULL;
			phonecontact->GetAllIMs(&ims);
			g_hash_table_foreach(ims, update_contact_ext_row, phonecontact);
			g_hash_table_destroy(ims);
			
			/* insert addresses */
			GPtrArray * addresses = NULL;
			phonecontact->GetAllAddresses(&addresses);
			for (guint32 j=0; j<addresses->len; j++)
				{
				memset(sql, 0, sizeof(sql));
				stAddress * addr = (stAddress*)g_ptr_array_index(addresses, j);
				sprintf(sql, "insert into address values(NULL, %d, '%s', '%s', '%s', '%s', '%s', '%s');", 
									addr->atype, addr->block, addr->street, addr->district,
									addr->city, addr->state, addr->country, addr->postcode);
									
				guint32 nAddrId = m_dbBeluga.execScalar("select max(aid) from address;");
				memset(sql, 0, sizeof(sql));
				sprintf(sql, "insert into contact_ext values(NULL, %d, %d, %d);", 
									atoi(fieldId->str), addr->atype, nAddrId);
				m_dbBeluga.execDML(sql);
				}
			freeAddressArray(addresses);
			g_string_free(fieldId, TRUE);
			}
		g_string_free(fieldValue, TRUE);
		
		m_dbBeluga.execDML("commit transaction;");
		delete pEntity;
		pEntity = NULL;
		CloseDatabase();
		return 0;
		}
	catch(CppSQLite3Exception& e)
		{
		m_dbBeluga.execDML("rollback transaction;");
		delete pEntity;
		pEntity = NULL;
		CloseDatabase();
		return ERROR(ESide_Client, EModule_Db, ECode_Update_Failed);
		}
		
	return 0;
	}
Example #18
0
int Maxthon3PlugIn::ImportFavoriteData( PFAVORITELINEDATA pData, int32& nDataNum )
{
	if (pData == NULL || nDataNum == 0)
	{
		return ERROR_INVALID_PARAM;
	}

	#define MAX_BUFFER_LEN	4096

	CppSQLite3DB  m_SqliteDatabase;
	wchar_t szInsert[MAX_BUFFER_LEN] = {0};
	wchar_t szDelete[MAX_BUFFER_LEN] = {0};

	if (m_pMemFavoriteDB != NULL)
	{
		m_SqliteDatabase.openmem(m_pMemFavoriteDB, "");

		int i = 0;

		m_SqliteDatabase.execDML(StringHelper::UnicodeToUtf8(L"delete from MyFavNodes where parent_id <> ''").c_str());

		m_SqliteDatabase.execDML("begin transaction");

		for (int i = 0; i < nDataNum; i++)
		{
			if (pData[i].bDelete == true)
			{
				continue;
			}

			swprintf_s(szInsert, MAX_BUFFER_LEN-1, L"insert into MyFavNodes"
				L"(id,parent_id,type,title,url,most_fav,visit_count,norder,add_date,shortcut)"
				L" values(?,?,%d,?,?,0,0,%d,%d,0)",
				pData[i].bFolder == true ? IT_FOLDER : IT_URL,
				pData[i].nOrder,
				(int32)pData[i].nAddTimes);

			CppSQLite3Statement sqliteStatement = m_SqliteDatabase.compileStatement(StringHelper::UnicodeToANSI(szInsert).c_str());

			std::string strTemp1 = StringHelper::StringToHex(
				StringHelper::ANSIToUnicode(CMD5Checksum::GetMD5((BYTE *)&pData[i].nId, sizeof(int32))));
			sqliteStatement.bind(1, (unsigned char *)strTemp1.c_str(), strTemp1.length());

			if (pData[i].nPid == 0)
			{
				unsigned char szParentNode[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

				sqliteStatement.bind(2, szParentNode, 16);
			}
			else
			{
				strTemp1 = StringHelper::StringToHex(StringHelper::ANSIToUnicode(
					CMD5Checksum::GetMD5((BYTE *)&pData[i].nPid, sizeof(int32))).c_str());
				sqliteStatement.bind(2, (unsigned char *)strTemp1.c_str(), strTemp1.length());
			}

			sqliteStatement.bind(3, (unsigned char *)pData[i].szTitle, (wcslen(pData[i].szTitle) + 1) * sizeof(wchar_t));
			sqliteStatement.bind(4, (unsigned char *)pData[i].szUrl, (wcslen(pData[i].szUrl) + 1) * sizeof(wchar_t));

			sqliteStatement.execDML();
			sqliteStatement.reset();
		}
		m_SqliteDatabase.execDML("commit transaction");

		SaveDatabase();
		return ERROR_OK;
	}

	return ERROR_SQLITE_ERROR;
}