summaryrefslogtreecommitdiffstats
path: root/plugins/contacts/symbian/contactsmodel/cntdbdumper/src/dbsqldumper.cpp
blob: c338e871df74d014c98c29744cdc0385278ba0de (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
/*
* Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
* Contact: http://www.qt-project.org/legal
* 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 "dbsqldumper.h"
#include "dbhtmltags.h"
#include "dbsqlconstants.h"
#include <e32test.h>
#include <s32mem.h>

_LIT(KErrorMessage, "DBSqlDumper Failed");	
const TInt KMaxPathLength = 100;
const TInt KBufferLength = 80;


/**
Class constructor
*/
CDbStructure::CDbStructure()
	{
	Init();	
	}
	
/**
Class destructor
*/
CDbStructure::~CDbStructure()	
	{
	iColumnsIndex.Reset();
	iNumColumns.Reset();	
	}

/**
Initialize table structure (number of tables, number of column in each table)

*/
void CDbStructure::Init()
	{	
	iTablesIndex = KInitialValue;
	iNumTables = KNumOfTables;
	iColumnsIndex.Reset();
	iNumColumns.Reset();
	//columns in pref table
	iColumnsIndex.Append(KInitialValue);
	iNumColumns.Append(KNumColInPrefTable);
	//columns in contact table
	iColumnsIndex.Append(KInitialValue);
	iNumColumns.Append(KNumColInContactTable);
	//columns in group table
	iColumnsIndex.Append(KInitialValue);
	iNumColumns.Append(KNumColInGroupTable);
	//columns in comm-address table
	iColumnsIndex.Append(KInitialValue);
	iNumColumns.Append(KNumColInCommTable);
	}
		
/**
Moves the cursor forward to the next table

@return ETrue if the cursor can be moved to the next index or EFalse if the cursor
		is already at the end
*/		
TBool CDbStructure::NextTable()
	{
	++iTablesIndex;
	return iTablesIndex < iNumTables;
	}
	
/**
Return current table name in the cursor

*/	
const TDesC& CDbStructure::TableName()
	{
	return TableName(iTablesIndex);
	}
	
/**
Returns name of the table located at specified position in the table array

*/
const TDesC& CDbStructure::TableName(TInt aTableIndex)
	{
	switch(aTableIndex)
		{
		case EContactPrefTableName:
			{
			return KSqlContactPrefTableName;	
			}
		case EContactTableName:
			{
			return KSqlContactTableName;
			}
		case EContactGroupTableName:
			{
			return KSqlContactGroupTableName;	
			}
		case EContactCommAddressTableName:
			{
			return KSqlContactCommAddrTableName;		
			}
		default:
			{
			return KNullText;
			} 
		}
	}
	
/**
Moves the cursor forward to the next column in the specified table

@return ETrue if the cursor can be moved to the next index or EFalse if the cursor
		is already at the end
*/
TBool CDbStructure::NextColumn(TInt aTableIndex)
	{
	++iColumnsIndex[aTableIndex];
	return iColumnsIndex[aTableIndex] < iNumColumns[aTableIndex];
	}

/**
Return current column name for the specified table

@param	aTableIndex table index for which column name has to be returned
*/	
const TDesC& CDbStructure::Column(TInt aTableIndex)
	{
	return Column(aTableIndex, iColumnsIndex[aTableIndex]);	
	}
	
/**	
Return name of the column located at specified pozition in the specified table

*/
const TDesC& CDbStructure::Column(TInt aTableIndex, TInt aColumnIndex)
	{
	switch(aTableIndex)
		{
		case EContactPrefTableName: //columns in preference table
			switch(aColumnIndex)
				{
				case 0:
					{
					return KPrefPrefId;	
					}
				case 1:
					{
					return KPrefSchemaVersion;	
					}
				case 2:
					{
					return KPrefDatabaseUid;	
					}
				case 3:
					{
					return KPrefPrefCreationDate;	
					}
				case 4:
					{
					return KPrefMachineId;	
					}
				case 5:
					{
					return KPrefPreferredOrder;	
					}
				case 6:
					{
					return KPrefferredTemplateId;
					}
				}
			break;	
		case EContactTableName: //columns in contact table
			switch(aColumnIndex)
				{
				case 0:
					{
					return KContactId;
					}
				case 1:
					{
					return KContactTemplateId;
					}
				case 2:
					{
					return KContactTypeFlags;
					}
				case 3:
					{
					return KContactAccessCount;
					}
				case 4:
					{
					return KContactLastModified;
					}
				case 5:
					{
					return KContactGuidString;
					}
				case 6:
					{
					return KContactFirstName;
					}
				case 7:
					{
					return KContactLastName;
					}
				case 8:
					{
					return KContactCompanyName;
					}
				case 9:
					{
					return KContactFirstNamePrn;
					}
				case 10:
					{
					return KContactLastNamePrn;
					}
				case 11:
					{
					return KContactCompanyNamePrn;
					}
                case 12:
                    {
                    return KContactFavoriteIndex;
                    }					
				case 13:
					{
					return KContactTextFieldHeader;
					}
				case 14:
					{
					return KContactBinaryFieldHeader;
					}
				case 15:
					{
					return KContactTextFields;
					}
				case 16:
					{
					return KContactBinaryFields;
					}
				}
			break;	
		case EContactGroupTableName: //columns in group table
			switch(aColumnIndex)
				{
				case 0:
					{
					return KGroupContactGroupId;
					}
				case 1:
					{
					return KGroupContactGroupId;
					}
				case 2:
					{
					return KGroupContactGroupMemberId;
					}
				}
			break;				
		case EContactCommAddressTableName: //columns in comm-address table
			switch(aColumnIndex)
				{
				case 0: 
					{
					return KCommAddrId;
					}
				case 1:
					{
					return KCommAddrType;
					}
				case 2:
					{
					return KCommAddrValue;
					}
				case 3:
					{
					return KCommAddrExtraValue;
					}
				case 4:
					{
					return KCommAddrContactId;
					}
				case 5:
                    {
                    return KCommAddrExtraTypeInfo;
                    }
				}
			break;
		}
		return KNullText;
	}
	
/**
Check if current column is the last column

*/	
TBool CDbStructure::IsLastColumn(TInt aTableIndex)
	{
	return iColumnsIndex[aTableIndex] == (iNumColumns[aTableIndex]-1);
	}
	
/**
Return number of columns specified table has

*/
TInt CDbStructure::ColumnNo(TInt aTableIndex)
	{
	return 	iNumColumns[aTableIndex];
	}

/**
Class destructor

*/	
CDbSqlDumper::~CDbSqlDumper()
	{
	delete iBuffer;
	iTableNames.Reset();
	iFile.Close();
	iDatabase.Close();
	iFsSession.Close();
	delete iDbStructure;
	}

/**
Second phase constructor for CDbSqlDumper class

@param  aDbName name of the database to be dumped.
@param	aOutputDir directory where html file will be generated		
*/	
void CDbSqlDumper::ConstructL(const TDesC& aDbName, const TDesC& aOutputDir)
	{
	// Output File Name	
	_LIT(KOutputFile,"DbDump.html");
	TBuf<KMaxPathLength> path(aOutputDir);
	path.Append(KOutputFile);
	
	User::LeaveIfError(iFsSession.Connect() );
	iDatabase.OpenL(aDbName);

	User::LeaveIfError(iFile.Replace(iFsSession, path, EFileWrite) );

	iBuffer = HBufC8::NewL(KBufferLength);
	iDbStructure = new (ELeave) CDbStructure();
	while(iDbStructure->NextTable())
		{
		iTableNames.AppendL(&(iDbStructure->TableName()));		
		}	
	}

/**
Return a concrete CDbSqlDumper object

@param  aDbName name of the database to be dumped.
@param	aOutputDir directory where html file will be generated		
*/	
CDbSqlDumper* CDbSqlDumper::NewLC(const TDesC& aDbName, const TDesC& aOutputDir)
	{
	CDbSqlDumper* self = new (ELeave) CDbSqlDumper();
	CleanupStack::PushL(self);
	self->ConstructL(aDbName, aOutputDir);
	return self;
	}
	
/**
Utility method used to build sql string. The result sql string will be
used to select from specified table

@param	aTableIndex	table index in the table array
*/	
void CDbSqlDumper::PrepareSQLStatementL(TInt aTableIndex)
	{
	//calculate the space needed to build the saq string
	iDbStructure->Init();
	TInt size = KSQLSelect().Size();
	while(iDbStructure->NextColumn(aTableIndex))
		{
		size += iDbStructure->Column(aTableIndex).Size() + 1;
		}
	size += KFrom().Size() + iDbStructure->TableName(aTableIndex).Size();	

	HBufC* sqlString = HBufC::NewLC( size );
	
	TPtr buffer = sqlString->Des();
	
	iDbStructure->Init();
	buffer.Append(KSQLSelect);
	while(iDbStructure->NextColumn(aTableIndex))
		{
		buffer.Append(iDbStructure->Column(aTableIndex));
		if(!iDbStructure->IsLastColumn(aTableIndex))	
			{
			buffer.Append(KComma);	
			}
		else	
			{
			buffer.Append(KSpace);	
			}		
		}
	buffer.Append(KFrom);	
	buffer.Append(iDbStructure->TableName(aTableIndex) );
	User::LeaveIfError(iSqlStatement.Prepare(iDatabase, buffer));
	
	CleanupStack::PopAndDestroy(sqlString);
	}

/**
Outputs one table values. Fetch all selected rows and output them in the
html file

@param	aTableIndex	table index in the table array
@leave  if there is an error at sql level, it will be forwarded
*/	
void CDbSqlDumper::OutputTableToFileL(TInt aTableIndex) 
	{
	TInt err;
	iFile.Write(KTable);
	OutputTableNameToFile(aTableIndex);
	OutputTableColHeadingsToFile(aTableIndex);
	PrepareSQLStatementL(aTableIndex);
	
	// output the table's rows
	while ((err =iSqlStatement.Next()) == KSqlAtRow )
		{
		iFile.Write(KRow);
		OutputTableColDataToFileL(aTableIndex);
		iFile.Write(KRowEnd);	
		}

	// check if there were any error
	if(err != KSqlAtEnd) 
		{
		iSqlStatement.Close();
		User::Leave(err);	
		}
	
	iSqlStatement.Close();
	iFile.Write(KTableEnd);
	}

/**
Outputs the table name in the html file

@param	aTableIndex	table index in the table array

*/	
void CDbSqlDumper::OutputTableNameToFile(TInt aTableIndex)
	{
	iFile.Write(KBold);	
	iBuffer->Des().Copy( *(iTableNames[aTableIndex]) ); // write iTableNames[aTableIndex] to the file.
	iFile.Write(*iBuffer);
	iFile.Write(KBoldEnd);
	}

/**
Outputs the header of the tables created in the html file. 
Header will contain column names

@param	aTableIndex	table index in the table array

*/
void CDbSqlDumper::OutputTableColHeadingsToFile(TInt aTableIndex)
	{
	iFile.Write(KHdRow);

	iDbStructure->Init();
	while(iDbStructure->NextColumn(aTableIndex))
		{
		iFile.Write(KCell);
		iBuffer->Des().Copy(iDbStructure->Column(aTableIndex));
		iFile.Write(*iBuffer);
		iFile.Write(KCellEnd);
		}

    iFile.Write(KRowEnd);
	}

/**
Outputs one row of a tables data.

@param	aTableIndex	table index in the table array

*/
void CDbSqlDumper::OutputTableColDataToFileL(TInt aTableIndex)
	{
	TInt counter = 0;
	const TInt KNumberOfCols( iDbStructure->ColumnNo(aTableIndex) );  

    // cols are from 1, to maxCols. not from 0 to KNumberOfCols-1.
	for (counter = 0; counter < KNumberOfCols; ++counter)   // for each column value in this row 
		{
		iFile.Write(KCell);

		if (iSqlStatement.IsNull(counter) )
			{
			iBuffer->Des().Format(KNullCol); // write out 'NULL' to the file
			}
		else
			{
			switch ( iSqlStatement.ColumnType(counter) )
				{
				case ESqlInt:
					{
					TInt32 val = iSqlStatement.ColumnInt(counter); 
					iBuffer->Des().Format(KInt32String, val);
					}
				break;
				case ESqlInt64:
					{
					TInt64 val = iSqlStatement.ColumnInt64(counter);
					iBuffer->Des().Format(KUInt64String, I64HIGH(val), I64LOW(val) );
					}
				break;
				case ESqlReal:
					{
					TReal32 val = iSqlStatement.ColumnReal(counter);
					iBuffer->Des().Format(KRealString, val);
					}
				break;
				case ESqlText:
					{
					iBuffer->Des().Copy(iSqlStatement.ColumnTextL(counter));
					}
				break;
				case ESqlBinary:
					if ((iDbStructure->Column(aTableIndex, counter) == KContactTextFieldHeader) ||
						(iDbStructure->Column(aTableIndex, counter) == KContactBinaryFieldHeader))
						{
						FieldHeaderColL(counter);
						}
					else 
						{
						LongBinaryL(counter);
						}
				break;
				default:
					iBuffer->Des().Format(KUnknownMessage);
				break;
				} // switch
			} // if

		iFile.Write(*iBuffer);
		iFile.Write(KCellEnd);
		
		} // for
	}

/**
Outputs a binary column/value representing header fields

@param	aFieldIndex	column index in the curently executed sql statement

*/
void CDbSqlDumper::FieldHeaderColL(TInt aFieldIndex)
	{
	TAutoClose<RSqlColumnReadStream> headerBlob;
	TAutoClose<RStoreReadStream> stream;

	headerBlob.iObj.ColumnBinary(iSqlStatement, aFieldIndex);
	CEmbeddedStore* headerStore = CEmbeddedStore::FromLC(headerBlob.iObj);
	stream.iObj.OpenLC(*headerStore, headerStore->Root());

	DumpStreamL(stream.iObj);

	CleanupStack::PopAndDestroy(&stream.iObj); //OpenLC
	CleanupStack::PopAndDestroy(headerStore);
	}

/**
Outputs a binary column/value representing binaryfields

@param	aFieldIndex	column index in the curently executed sql statement

*/
void CDbSqlDumper::LongBinaryL(TInt aFieldIndex)
	{
	TAutoClose<RSqlColumnReadStream> rdStream;
	rdStream.iObj.ColumnBinary(iSqlStatement,aFieldIndex);
	
	DumpStreamL(rdStream.iObj);
	}

/**
Utility method used to read from a read stream and write to file

@param	stream RReadStream from which information will be read

*/
void CDbSqlDumper::DumpStreamL(RReadStream& stream)
	{
	const TInt KStreamSize = stream.Source()->SizeL();

	iFile.Write(KDumpFont);

	_LIT8(KSizeMessage, "size is %d <BR>");
	_LIT8(KEightSpaces, "        ");
	_LIT8(KByteFormat, "%02x&nbsp;");
	_LIT8(KFormatString, "%S&nbsp;<BR>\r\n");
	
	iBuffer->Des().Format(KSizeMessage, KStreamSize);
	iFile.Write(*iBuffer);

	TBuf8<8> str(KEightSpaces); //Reserve 8 symbols

	TInt counter(0);
	while (counter < KStreamSize)
		{
		for(TInt i=0; i < 8; ++i)
			{
			if (counter >= KStreamSize)
				{
				break;	
				}
			//format the bynary value to a printable char	
			TInt8 byte( stream.ReadInt8L() );
			iBuffer->Des().Format(KByteFormat, byte);
			iFile.Write(*iBuffer);
			
			str[i] = (byte>32 ? byte : '.');
			++counter;
			}
		iBuffer->Des().Format(KFormatString, &str);
		iFile.Write(*iBuffer);
		}

	iFile.Write(KDumpFontEnd);
	}

/**
Output database content to a file

*/
void CDbSqlDumper::OutputDBContentsL()    
	{
	// Output Title
	_LIT8(KHdr,"<H2>Contacts Model DB Dump:</H2>");
	iFile.Write(KHdr);
		
	TInt counter = 0;
	const TInt KNumTables( iTableNames.Count() ); 
	
	// for each table - output all tables 
	for (counter = 0; counter < KNumTables; ++counter)
		{
		OutputTableToFileL(counter);
		}			
	}

void RunDumpL()
	{
// Location of Output Directory. (File will be called DbDump.html). Final "\" required on path.
_LIT(KOutputDir, "?:\\");
TBuf<sizeof(KOutputDir)> outputDir(KOutputDir);
outputDir[0] = (TUint8) RFs::GetSystemDriveChar();

// Location of Contacts DB
_LIT(KDBName, "?:\\private\\10003A73\\SQLite__contacts.cdb");
TBuf<sizeof(KDBName)> fileDBName(KDBName);
fileDBName[0] = (TUint8) RFs::GetSystemDriveChar();

	// dump sql database
	CDbSqlDumper* sqlDumper = CDbSqlDumper::NewLC(fileDBName, outputDir);   
    sqlDumper->OutputDBContentsL();   
	CleanupStack::PopAndDestroy(sqlDumper);   
	}

GLDEF_C TInt E32Main()
	{
	__UHEAP_MARK;
	CActiveScheduler* scheduler = new CActiveScheduler;
	if (scheduler)
		{
		CActiveScheduler::Install(scheduler);
		CTrapCleanup* cleanup = CTrapCleanup::New();
		if (cleanup)
			{
			TRAPD(err,RunDumpL() );	
			__ASSERT_ALWAYS(err == KErrNone, User::Panic(KErrorMessage,err) ); 
			delete cleanup;
			}
		delete scheduler;
		}
	__UHEAP_MARKEND;
	return KErrNone;
    }