summaryrefslogtreecommitdiffstats
path: root/plugins/contacts/symbian/contactsmodel/cntplsql/src/pplcontactitemmanager.cpp
blob: d1255042c73ab45f0fd0667fa38831dff4a71747 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
/*
* Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: 
*
*/


/**
 @file
 @internalComponent
 @released
*/

#include "pplcontactitemmanager.h"
#include "cntsqlprovider.h"
#include "dbsqlconstants.h"
#include "cntpersistenceutility.h"
#include "cntsqldbstructure.h"

//#include "cntmetadataoperation.h"

#include <cntdef.h>
#include <sqldb.h>
#include <cntdb.h>

//uncomment for commonly required debug printing
//#define __VERBOSE_DEBUG__


/**
Creates a concrete CPplContactItemManager object 

@param 	aDatabase reference to RSqlDatabase
		aTransactionManager reference to MLplTransactionManager (provided by CPlContactsFile)
@return concrete CPplContactItemManager object
@leave KErrNoMemory, an out of memory occured
*/		
CPplContactItemManager* CPplContactItemManager::NewL(RSqlDatabase& aDatabase, MLplTransactionManager& aTransactionManager, CLplContactProperties&  aContactProperties, RPplIccContactStore& aIccContactStore)
	{
	CPplContactItemManager* self = new (ELeave) CPplContactItemManager(aDatabase, aTransactionManager, aContactProperties, aIccContactStore);
	CleanupStack::PushL(self);
	self->ConstructL();
	CleanupStack::Pop(self);
	return self;	
	}

/**
Class destructor. Deletes holded CCntSqlStatement

*/		
CPplContactItemManager::~CPplContactItemManager()
	{
	delete iSelectStatement;	
	delete iContactTable;
	delete iCommAddrTable;
    delete iGroupTable;
	delete iPreferencePersistor;
	//iColSession.Close();
	}
	
/**
Class constructor

@param aDatabase reference to RSqlDatabase
@param aTransactionManager reference to transaction manager
@param aContactProperties reference to contact properties
*/	
CPplContactItemManager::CPplContactItemManager(RSqlDatabase& aDatabase, MLplTransactionManager& aTransactionManager, CLplContactProperties&  aContactProperties, RPplIccContactStore& aIccContactStore) :
	iDatabase(aDatabase),
	iTransactionManager(aTransactionManager),
	iContactProperties(aContactProperties),
	iIccContactStore(aIccContactStore)
	{
	}
	
/**
Add the given contact item to the database. Forward the call to CPplTableBase
based classes representing the tables in the contact database.

@param 	aItem The contact item to be added to the database. 
@param 	aSessionId The ID of the session that issued the request.  Used to
		prevent Phonebook Synchroniser deadlock.

@return Contact item ID of the contact added to the database.
*/
TContactItemId CPplContactItemManager::CreateL(CContactItem& aItem, TUint aSessionId)
	{
	TBool controlTransaction = !(iTransactionManager.IsTransactionActive());
	
	TBool compressedGuid=EFalse;

	// If needed generate a gui for the current contact item
	if (aItem.Guid() == TPtrC(KNullDesC))
		{
		iPreferencePersistor->SetGuidL(aItem, compressedGuid);
		}

	if (compressedGuid)
		{
		aItem.SetHasCompressedGuid(compressedGuid);
		}

	if (aItem.Type() == KUidContactICCEntry) 
		{
		const TInt ret = iContactProperties.ContactSynchroniserL(aSessionId).ValidateWriteContact(static_cast<CContactICCEntry&>(aItem));
		User::LeaveIfError(ret);	
		}
	
	if(controlTransaction)
		{
		StartTransactionL(aSessionId);
		}
		
	iContactTable->CreateInDbL(aItem);	
	iGroupTable->CreateInDbL(aItem);	
	iCommAddrTable->CreateInDbL(aItem);

   	TContactItemId groupId = iIccContactStore.CreateInDbL(aItem, aSessionId);
   	if(groupId != KNullContactId)
   	    {
   	    //Every ICC entry is added to a special group, created by the Phonebook
        //Synchroniser server during the initial synchronisation with the Contacts Model.
		CContactItemViewDef* itemDef = CContactItemViewDef::NewLC(CContactItemViewDef::EIncludeFields,CContactItemViewDef::EMaskHiddenFields);
		itemDef->AddL(KUidContactFieldMatchAll);

		// Add ICC entry to the group.
		CContactGroup* grp = static_cast<CContactGroup*>(ReadLC(groupId, *itemDef, EPlAllInfo, aSessionId));
		
		grp->AddContactL(aItem.Id());
		UpdateL(*grp, aSessionId);

		CleanupStack::PopAndDestroy(2, itemDef); // grp
   	    }

	if(controlTransaction)
		{
		CommitTransactionL();
		}
	
	// Assuming success if no leaves at this point, so update
	// the metadata search store for this entry
	//CCntMetadataOperation* op = CCntMetadataOperation::NewLC(iColSession);
	//TRAP_IGNORE(op->SaveContactLD(aItem));
	//CleanupStack::Pop(op); // Do not destroy - called LD function
	
	return aItem.Id();	
	}
	
/**
Reads the contact item from the database using the given contact item ID.

@param aItemId The Id number of the contact to be read.
@param aView Specifies the fields to be read.
@param aInfoToRead not used 
@param aSessionId The ID of the session that issued the request.  This is used
to prevent Phonebook Synchroniser deadlock.
@param aIccOpenCheck Specifies if validation with the Phonebook Synchroniser is
needed for this contact.

@leave 	KErrArgument 	if the itemID can't be set within select statement
@leave  KErrNotFound 	if a contact item with aItemId does not exist within contact database
@leave  KSqlErrBusy 	the database file is locked; thrown if RSqlStatement::Next() 
						returns this error
@leave  KErrNoMemory 	an out of memory condition has occurred - the statement
                        will be reset;thrown if RSqlStatement::Next() returns this error
@leave  KSqlErrGeneral	a run-time error has occured - this function must not
                        be called again;thrown if RSqlStatement::Next() returns this error
@leave	KSqlErrMisuse	this function has been called after a previous call
                        returned KSqlAtEnd or KSqlErrGeneral.thrown if RSqlStatement::Next() 
                        returns this error
@leave  KSqlErrStmtExpired	the SQL statement has expired (if new functions or
                            collating sequences have been registered or if an
                            authorizer function has been added or changed);
                            thrown if RSqlStatement::Next() returns this error

@return CContactItem created from reading the database tables.
*/	
CContactItem* CPplContactItemManager::ReadLC(TContactItemId aItemId, const CContactItemViewDef& aView, TInt aInfoToRead, TUint aSessionId, TBool aIccOpenCheck) const
	{	
	CContactTemplate* sysTemplate = NULL;
	if (aItemId != KGoldenTemplateId) 
		{
		sysTemplate = const_cast<CContactTemplate*>(&iContactProperties.SystemTemplateL());
		}
	
	RSqlStatement selectStmt;
	CleanupClosePushL(selectStmt);
	User::LeaveIfError(selectStmt.Prepare(iDatabase, iSelectStatement->SqlStringL()));
	
	TInt err = selectStmt.BindInt(KFirstParam, aItemId);
	
	if(err != KErrNone)
		{
		User::Leave(KErrArgument);	
		}
	
	CContactItem* item = NULL;
	TUid type(KNullUid);
	
	if((err = selectStmt.Next()) == KSqlAtRow)
		{
		TInt contactId = selectStmt.ColumnInt(iSelectStatement->ParameterIndex(KContactId));
		TInt templateId = selectStmt.ColumnInt(iSelectStatement->ParameterIndex(KContactTemplateId));
		TInt typeFlags = selectStmt.ColumnInt(iSelectStatement->ParameterIndex(KContactTypeFlags));
		type = TCntPersistenceUtility::TypeFlagsToContactTypeUid(typeFlags); 
		item = CContactItem::NewLC(type);
		item->SetId(contactId);
		TPtrC guid = selectStmt.ColumnTextL(iSelectStatement->ParameterIndex(KContactGuidString));
		item->SetUidStringL(guid);
		TInt attr = (typeFlags & EContactAttributes_Mask) >> EContactAttributes_Shift; 
		item->SetAttributes(attr);
		item->SetTemplateRefId(templateId);
		item->SetLastModified(TTime(selectStmt.ColumnInt64(iSelectStatement->ParameterIndex(KContactLastModified)))); 
		item->SetCreationDate(TTime(selectStmt.ColumnInt64(iSelectStatement->ParameterIndex(KContactCreationDate))));
		item->SetAccessCount(selectStmt.ColumnInt(iSelectStatement->ParameterIndex(KContactAccessCount)));
			
		RArray<TPtrC> fastAccessFields;
		CleanupClosePushL(fastAccessFields);
		fastAccessFields.AppendL(selectStmt.ColumnTextL(iSelectStatement->ParameterIndex(KContactFirstName)));
		fastAccessFields.AppendL(selectStmt.ColumnTextL(iSelectStatement->ParameterIndex(KContactLastName)));
		fastAccessFields.AppendL(selectStmt.ColumnTextL(iSelectStatement->ParameterIndex(KContactCompanyName)));
		fastAccessFields.AppendL(selectStmt.ColumnTextL(iSelectStatement->ParameterIndex(KContactFirstNamePrn)));
		fastAccessFields.AppendL(selectStmt.ColumnTextL(iSelectStatement->ParameterIndex(KContactLastNamePrn)));
		fastAccessFields.AppendL(selectStmt.ColumnTextL(iSelectStatement->ParameterIndex(KContactCompanyNamePrn)));
				
		//set first name, last name, company name, first name pronunciation, last name pronunciation, company name pronunciation
		for (TInt fieldNum = item->CardFields().Count() - 1; fieldNum>=0; --fieldNum) 
			{
			CContactItemField& textField = (item->CardFields())[fieldNum];
			const TInt nameFieldIndex = NameFieldIndex(textField);

			// Check if field is first name, last name, company name,
			// first name pronunciation, last name pronunciation, company name pronunciation.
			if (nameFieldIndex != KErrNotFound)
				{
				HBufC* text = HBufC::NewLC(fastAccessFields[nameFieldIndex].Size());
				text->Des() = fastAccessFields[nameFieldIndex];
				textField.TextStorage()->SetText(text);
				CleanupStack::PopAndDestroy(text);
				}
			}
			
		CleanupStack::PopAndDestroy(&fastAccessFields);
		}
	else
		{
		if(err == KSqlAtEnd)
			{
			User::Leave(KErrNotFound);	// Select statement did not return any row		
			}
		else
			{
			User::Leave(err); 	// Otherwise selectStmt.Next() generated a sql error
			}	
		
		}

	if (!(item->IsDeleted()) || type == KUidContactCardTemplate)
		{
		TCntPersistenceUtility::ReadBlobL(*item, aView, sysTemplate, iDatabase);
		}
    
    //Fill in group content.
    static_cast<CPplGroupsTable*>(iGroupTable)->ReadL(*item);
    
    //Validate checking ICC entry.
    iIccContactStore.ReadL(*item, aInfoToRead, aSessionId, aIccOpenCheck);
    
	CleanupStack::Pop(item);
	CleanupStack::PopAndDestroy(&selectStmt);
	CleanupStack::PushL(item);
	
	return item;
	}
	
/** 
Updates the given contact item in the database.Forward the call to CPplTableBase
based classes representing the tables in the contact database.

@param aItem The contact to be updated with all the changes (received from the
user).
@param aSessionId The ID of the session that issued the request.  Used to
prevent Phonebook Synchroniser deadlock.
*/	
void CPplContactItemManager::UpdateL(CContactItem& aItem, TUint aSessionId, TBool /*aSpeeDailUpdate*/)
	{
	TBool controlTransaction = !(iTransactionManager.IsTransactionActive());
	
	if (aItem.Type() == KUidContactICCEntry) 
		{
        //Fakely validating read right to ICC entry to keep BC.
		const TInt ret = iContactProperties.ContactSynchroniserL(aSessionId).ValidateContact(MContactSynchroniser::ERead, aItem.Id());
		User::LeaveIfError(ret);	
		}
		
	if(controlTransaction)
		{
		StartTransactionL(aSessionId);
		}

	iIccContactStore.UpdateL(aItem, aSessionId);
	iContactTable->UpdateL(aItem);	
	iGroupTable->UpdateL(aItem);	
	iCommAddrTable->UpdateL(aItem);

	if(controlTransaction)
		{
		CommitTransactionL();
		}
		
	// If the item is the System template then delete it from the template
	// manager.  The template can later be recreated from the table.
	if (aItem.Id() == KGoldenTemplateId)
		{
		iContactProperties.SystemTemplateManager().DeleteTemplate();
		}
	
    // Assuming success if no leaves at this point, so update
    // the metadata search store for this entry
    //CCntMetadataOperation* op = CCntMetadataOperation::NewLC(iColSession);
    //TRAP_IGNORE(op->SaveContactLD(aItem));
    //CleanupStack::Pop(op); // Do not destroy - called LD function
	}

/**
Deletes the given contact from the database.Forward the call to CPplTableBase
based classes representing the tables in the contact database. In low disk condition
checks if it can gain access to reserver database space and perform the deletion. If 
this is not possible a KErrDiskFull will be thrown.

@param aItemId The contact ID of the contact item to be deleted.
@param aSessionId The ID of the session that issued the request.  Used to
prevent Phonebook Synchroniser deadlock.

@leave KErrDiskFull if a full disk error appears

@return The item which was read from the database before it was deleted.   This
object can be used by, for example, the CLplAnalyserProxy::DeleteLC() method to
create a notification message.
*/	
CContactItem* CPplContactItemManager::DeleteLC(TContactItemId  aItemId, TUint aSessionId, TCntSendEventAction /*aEventType*/)
	{
	TBool controlTransaction = !(iTransactionManager.IsTransactionActive());

	CContactItemViewDef* viewDef = CContactItemViewDef::NewL(CContactItemViewDef::EIncludeFields, CContactItemViewDef::EIncludeHiddenFields);
	CleanupStack::PushL(viewDef);

	if(controlTransaction)
		{
		StartTransactionL(aSessionId);
		}

	TBool lowDisk = EFalse;
	CContactItem* savedContactItem = static_cast<CPplContactTable*>(iContactTable)->DeleteLC(aItemId, lowDisk);
	if (lowDisk) 
		{
		CleanupStack::PopAndDestroy(savedContactItem); // this was returned from the first call, but not deleted in the db
		TInt err = iDatabase.GetReserveAccess();
		if(err != KErrNotFound)
			{
			User::Leave(KErrDiskFull);	
			}
		
		lowDisk = EFalse;
		
		savedContactItem = static_cast<CPplContactTable*>(iContactTable)->DeleteLC(aItemId, lowDisk);
		if(lowDisk)
			{
			iDatabase.FreeReservedSpace();
			User::Leave(KErrDiskFull);	
			}
		iDatabase.FreeReservedSpace();		
		}

	lowDisk = EFalse;	
	iGroupTable->DeleteL(*savedContactItem, lowDisk);	
	if (lowDisk) 
		{
		DeleteInLowDiskConditionL(iGroupTable, savedContactItem);
		}

	lowDisk = EFalse;
	iCommAddrTable->DeleteL(*savedContactItem, lowDisk);	
	if (lowDisk) 
		{
		DeleteInLowDiskConditionL(iCommAddrTable, savedContactItem);
		}

    //Fake checking read access to ICCEntry store to keep BC.
    iIccContactStore.ReadL(*savedContactItem, EPlGroupMembershipInfo, aSessionId, EFalse);    
    
	//Don't need to check low disk state for ICC synchronizer.
	iIccContactStore.DeleteL(*savedContactItem, aSessionId);

	if(controlTransaction)
		{
		CommitTransactionL();  	// Pops item
		}
		
	CleanupStack::Pop();		// Pops item or transaction
	CleanupStack::PopAndDestroy(viewDef);	
	CleanupStack::PushL(savedContactItem);

	// Assume no leaves by this point indicates successful delete,
	// therefore update the metadata store
	//CCntMetadataOperation* op = CCntMetadataOperation::NewLC(iColSession);
	//TRAP_IGNORE(op->DeleteContactLD(aItemId));
	//CleanupStack::Pop(op); // Do not destroy - called LD function
	
	return savedContactItem;
	
	}

/**
Perform a deletion in low disk condition

@param aTable CPplTableBase on which the deletion will be done
@param aContactItem the contact item to be deleted

@leave KErrDiskFull if the deletion can't be done a KerrDiskFull will be throw
*/
void CPplContactItemManager::DeleteInLowDiskConditionL(CPplTableBase* aTable, CContactItem* aContactItem)
	{
	TInt err = iDatabase.GetReserveAccess();
	if(err != KErrNotFound)
		{
		User::Leave(KErrDiskFull);	
		}
		
	TBool lowDisk = EFalse;
	aTable->DeleteL(*aContactItem, lowDisk);
	if(lowDisk)
		{
		iDatabase.FreeReservedSpace();
		User::Leave(KErrDiskFull);	
		}
	iDatabase.FreeReservedSpace();		
	}
	
/**
Change the type of the given contact item to the given type.Forward the call to CPplTableBase
based classes representing the tables in the contact database.

@param aItemId Contact item ID whose type is to be changed.
@param aNewType New type for contact item.
*/	
void CPplContactItemManager::ChangeTypeL(TContactItemId aItemId, TUid aNewType)
	{
	static_cast<CPplContactTable*>(iContactTable)->ChangeTypeL(aItemId, aNewType);
	}

/** 
Does nothing: the CLplAnalyserProxy class sets the connetion ID.
*/
void CPplContactItemManager::SetConnectionId(TInt /*aConnectionId*/)
	{
	}
	
/**
Second phase constructor for CPplContactItemManager object.
Sets the CCntSqlStatement to be used for reading contact item.

*/
void CPplContactItemManager::ConstructL()
	{
#if defined(__VERBOSE_DEBUG__)
	RDebug::Print(_L("CPplContactItemManager::ConstructL"));
#endif	
	TCntSqlStatementType statementType(ESelect, KSqlContactTableName);
	
	iSelectStatement = TSqlProvider::GetSqlStatementL(statementType);
	
	// also prepare everything in CCntSqlStatement
	// First add columns from contact table
	iSelectStatement->SetParamL(KContactId, KSpace);
	iSelectStatement->SetParamL(KContactTemplateId, KSpace);
	iSelectStatement->SetParamL(KContactTypeFlags, KSpace);
	iSelectStatement->SetParamL(KContactAccessCount, KSpace);
	iSelectStatement->SetParamL(KContactCreationDate, KSpace);	
	iSelectStatement->SetParamL(KContactLastModified, KSpace);
	iSelectStatement->SetParamL(KContactGuidString, KSpace);
	iSelectStatement->SetParamL(KContactFirstName, KSpace);
	iSelectStatement->SetParamL(KContactLastName, KSpace);
	iSelectStatement->SetParamL(KContactCompanyName, KSpace);
	iSelectStatement->SetParamL(KContactFirstNamePrn, KSpace);
	iSelectStatement->SetParamL(KContactLastNamePrn, KSpace);
	iSelectStatement->SetParamL(KContactCompanyNamePrn, KSpace);
		
	HBufC* condition = HBufC::NewLC(KWhereStringEqualsStringFormatText().Size() + KContactId().Size());
	TPtr ptrCondition = condition->Des();
	ptrCondition.Format(KWhereStringEqualsStringFormatText, &KContactId, &KVar);
	
	// Set condition
	iSelectStatement->SetConditionL(ptrCondition);
	
	CleanupStack::PopAndDestroy( condition ); 

	// construct tables
	iContactTable = CPplContactTable::NewL(iDatabase, iContactProperties);
	iCommAddrTable = CPplCommAddrTable::NewL(iDatabase, iContactProperties);
	iGroupTable = CPplGroupsTable::NewL(iDatabase);
	iPreferencePersistor = CPplPreferencesPersistor::NewL(iDatabase);
	// Connect to metadata server
	//User::LeaveIfError(iColSession.Connect());
#if defined(__VERBOSE_DEBUG__)
	RDebug::Print(_L("CPplContactItemManager::ConstructL ends"));
#endif
	}

/**
Cleanup operation. If one of the crud operation fails, this method will be called
to rollback the sql transaction

*/
void CPplContactItemManager::CleanupOperationRollbackL(TAny* aPplContactItemanager)
	{
	CPplContactItemManager* contactItemManager = static_cast<CPplContactItemManager*>(aPplContactItemanager);
	contactItemManager->iTransactionManager.RollbackCurrentTransactionL(contactItemManager->iSessionId);
	}
	
/**
Utility method used to identify if the provided CContactItemField is first name, last name, 
company name, first name pronunciation, last name pronunciation or company name pronunciation 
Method used to fill information when a CContactItem is read from contact database

@param aNameField reference to a constant CContactItemField for which the index will be returned

*/	
TInt CPplContactItemManager::NameFieldIndex(const CContactItemField& aNameField) const
	{
	// For all the name fields...
	for (TInt nameFieldNum=0; nameFieldNum < sizeof(KFastAccessFieldUids)/sizeof(TInt); ++nameFieldNum)
		{
		if (aNameField.ContentType().ContainsFieldType(TUid::Uid(KFastAccessFieldUids[nameFieldNum])))
			{
			return nameFieldNum;
			}
		}
	return KErrNotFound;
	}
	
/**
Utility method used to start a transaction in database

@param aSessionId id of the session
*/
void CPplContactItemManager::StartTransactionL(TUint aSessionId)
	{
	iTransactionManager.StartTransactionL();
	
	iSessionId = aSessionId;
	CleanupStack::PushL(TCleanupItem(CleanupOperationRollbackL, this));		
	}
	
/**
Utility method used to commit a transaction
*/
void CPplContactItemManager::CommitTransactionL()
	{
	iTransactionManager.CommitCurrentTransactionL(iSessionId);
		
	CleanupStack::Pop(); //CleanupOperationRollbackL		
	}
	
/**
Utility method used to create tables in a newly create database
*/	
void CPplContactItemManager::CreateTablesL()
	{
#if defined(__VERBOSE_DEBUG__)
	RDebug::Print(_L("CPplContactItemManager::CreateTablesL"));	
#endif
	TBool controlTransaction = !(iTransactionManager.IsTransactionActive());
	
	if (controlTransaction)
		{
		StartTransactionL(0);
		}
		
	iContactTable->CreateTableL();	
	iGroupTable->CreateTableL();	
	iCommAddrTable->CreateTableL();
	iPreferencePersistor->CreateTableL();
	
	if (controlTransaction)
		{
		CommitTransactionL();
		}			
#if defined(__VERBOSE_DEBUG__)
	RDebug::Print(_L("CPplContactItemManager::CreateTablesL ends"));	
#endif
	}
	
/**
Utility method used to check if there is any record in the contact database

@return ETrue if the contact database is empty and EFalse otherwise
*/	
TBool CPplContactItemManager::IsDatabaseEmptyL()
	{
	return static_cast<CPplContactTable*>(iContactTable)->IsTableEmptyL();
	}


CContactIdArray* CPplContactItemManager::MatchPhoneNumberL(const TDesC& aNumber, TInt aMatchLengthFromRight)
	{
	// Call comm address table
    return  static_cast<CPplCommAddrTable*>(iCommAddrTable)->MatchPhoneNumberL(aNumber, aMatchLengthFromRight);
	}

/**
Utility method used to retrieve an array of card template ids

@return reference to a CContactIdArray containing the card template ids
*/
CContactIdArray& CPplContactItemManager::CardTemplateIdsL()
	{
	// Call contact table
	return  static_cast<CPplContactTable*>(iContactTable)->CardTemplateIdsL();	
	}

/**
Utility method used to retrieve a reference to persistence layer preference persistor
*/
CPplPreferencesPersistor& CPplContactItemManager::PreferencesPersitor()  
	{
	return *iPreferencePersistor;
	}

/**
Utility method used to retrieve own card contact id
*/
TContactItemId CPplContactItemManager::OwnCardIdL()
	{
	// Call contact table
	return  static_cast<CPplContactTable*>(iContactTable)->OwnCardIdL();		
	}
	
/**
Utility method used to set own card id
*/	
void CPplContactItemManager::SetOwnCardIdL(TContactItemId aId, TBool aPersist)
	{	
	// Call contact table
	static_cast<CPplContactTable*>(iContactTable)->SetOwnCardIdL(aId, aPersist);		
	}

/**
Utility class. Returns an array with ids of all groups in contact database
*/
CContactIdArray* CPplContactItemManager::GroupIdListL()
	{
	CContactIdArray* idArray = CContactIdArray::NewLC();

	HBufC* selectString = HBufC::NewLC(KOneTypeField().Length() + KSqlContactTableName().Length() + KContactTypeFlags().Length() + 3); 
	TPtr ptrSelectString = selectString->Des();
	ptrSelectString.Format(KOneTypeField, &KContactId, &KSqlContactTableName, &KContactTypeFlags, EContactType_Shift, EContactTypeFlags_Group);

	RSqlStatement selectStatement;
	CleanupClosePushL(selectStatement);
	
	User::LeaveIfError(selectStatement.Prepare(iDatabase, ptrSelectString));
	const TInt KIdx = iSelectStatement->ParameterIndex(KContactId);
	
	TInt err;
	while ((err = selectStatement.Next()) == KSqlAtRow)
		{
		idArray->AddL(selectStatement.ColumnInt(KIdx));	
		}

	if (err != KSqlAtEnd)
		{
		User::Leave(err);
		}

    CleanupStack::PopAndDestroy(&selectStatement);
	CleanupStack::PopAndDestroy(selectString);
	CleanupStack::Pop(idArray);
	
	return idArray;
	}

/**
Fast access method for retrieving a list of contact details as raw data.
This method can be used for example to fetch the names of all contacts
in a very efficient manner. It is assumed that the first column in
aSearchQuery is 'id' and that the other columns are text.

The returned buffer can be read with RBufReadStream - the first column
of each row is a 32-bit integer (the id), the rest of the columns are
16-bit descriptors. An id of 0 signifies the end of the list.
*/
CBufSeg* CPplContactItemManager::DetailsListL(const TDesC& aSearchQuery) const
    {
    CBufSeg* array = CBufSeg::NewL(4096);
    CleanupStack::PushL(array);

    //Prepare and execute the sql query
    RSqlStatement selectStatement;
    CleanupClosePushL(selectStatement);
    User::LeaveIfError(selectStatement.Prepare(iDatabase, aSearchQuery));

    // Iterate through the results and append the contactIds to idArray
    TInt err;
    RBufWriteStream stream;
    stream.Open(*array);
    TInt columnCount = selectStatement.ColumnCount();
    while ((err = selectStatement.Next()) == KSqlAtRow)
        {
        int contact_id = selectStatement.ColumnInt(0);
        if (contact_id != 0)
            {
            //include only user contacts into search results (template contact is excluded)
            stream.WriteInt32L(contact_id);
            for (TInt i = 1; i < columnCount; ++i)
                stream << selectStatement.ColumnTextL(i);
            }
        }
    stream.WriteInt32L(0);
    stream.Close();

    if (err != KSqlAtEnd)
        {
        User::Leave(err);
        }

    //Cleanup 
    CleanupStack::PopAndDestroy(&selectStatement);
    CleanupStack::Pop(array);
    
    return array;
    }

/**
Utility method used to rthe prefered card template id
*/
TInt CPplContactItemManager::CardTemplatePrefIdL() const
	{
	return iPreferencePersistor->PreferredCardTemplateIdL();
	}

/**
Utility method used to set the prefered card template id
*/
void CPplContactItemManager::SetCardTemplatePrefIdL(TInt aCardTemplatePrefId)
	{
	iPreferencePersistor->SetPreferredCardTemplateIdL(aCardTemplatePrefId);
	}

void CPplContactItemManager::MakeDatabaseCompatibleL()
    {
    //check compatibility
    CCntSqlDbStructure* tblStructure = CCntSqlDbStructure::NewL( iDatabase, *this );   
    CleanupStack::PushL(tblStructure);
    tblStructure->MakeDatabaseCompatibleL();
    CleanupStack::PopAndDestroy(); //tblStructure
    }