-
Notifications
You must be signed in to change notification settings - Fork 0
/
TableCompareQuery.cpp
589 lines (474 loc) · 16.6 KB
/
TableCompareQuery.cpp
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
/*----------------------------------------------------------------------
Copyright (c) Dan Petitt, http://www.coderanger.com
All Rights Reserved.
Please see the file "licence.txt" for licencing details.
File: TableCompareQuery.cpp
Owner: [email protected]
Purpose: Derived table syncronisation class which uses 3 different queries
to find out rows to insert, delete, update
Advantages: It works, its quick and uses low memory
Disadvantages: Lot of work is done on server siding Querying for
hashes
----------------------------------------------------------------------*/
#include "stdafx.h"
#include "TableCompareQuery.h"
CTableCompareQuery::CTableCompareQuery(void)
{
}
CTableCompareQuery::~CTableCompareQuery(void)
{
}
void CTableCompareQuery::OnProcessTable( const XMySQL::CConnection::Table &tbl )
{
const std::string strSourceDB( m_mySource.CurrentDatabase() );
const std::string strTargetDB( m_myTarget.CurrentDatabase() );
const size_t uNumFields = tbl.arrFields.size();
std::string strKeyFields, strAllFields, strKeyFieldsJoinWithDB, strAllFieldsWithSourceDB, strAllFieldsWithTargetDB;
for( size_t uField = 0; uField < uNumFields; uField++ )
{
const XMySQL::CConnection::FieldInfo &fieldInfo = tbl.arrFields.at( uField );
if( fieldInfo.bIsPrimaryKey )
{
if( strKeyFields.length() )
{
strKeyFields += _T(",");
}
strKeyFields += fieldInfo.strName;
if( strKeyFieldsJoinWithDB.length() )
{
strKeyFieldsJoinWithDB += _T(" AND ");
}
strKeyFieldsJoinWithDB += _T("`") + strSourceDB + _T("`.`") + tbl.strName + _T("`.") + fieldInfo.strName;
strKeyFieldsJoinWithDB += _T("=`") + strTargetDB + _T("`.`") + tbl.strName + _T("`.") + fieldInfo.strName;
}
if( strAllFields.length() )
{
strAllFields += _T(",");
}
strAllFields += fieldInfo.strName;
if( strAllFieldsWithSourceDB.length() )
{
strAllFieldsWithSourceDB += _T(",");
}
strAllFieldsWithSourceDB += _T("`") + strSourceDB + _T("`.`") + tbl.strName + _T("`.") + fieldInfo.strName;
if( strAllFieldsWithTargetDB.length() )
{
strAllFieldsWithTargetDB += _T(",");
}
strAllFieldsWithTargetDB += _T("`") + strTargetDB + _T("`.`") + tbl.strName + _T("`.") + fieldInfo.strName;
}
//
// Get total records so we can work out count of identical records by subtracting insert, delete and update records from total
UINT uTotalRecords = 0;
XMySQL::CResultSet rsCount( m_mySource, XMySQL::CResultSet::Client );
rsCount.Executef( _T("SELECT count(*) FROM %s"), tbl.strName.c_str() );
if( !rsCount.IsEOF() )
{
uTotalRecords = atol( rsCount.GetFieldValue( 0 ) );
}
// Find our records to insert first...
// SELECT * FROM `exportpdb_new`.person WHERE nid NOT IN (SELECT nid FROM `exportpdb_live`.person)
std::stringstream dataInsertStream;
dataInsertStream << _T("SELECT ") << strAllFields;
dataInsertStream << _T(" FROM `") << strSourceDB << _T("`.`") << tbl.strName << _T("`");
dataInsertStream << _T(" WHERE (") << strKeyFields << _T(") NOT IN (SELECT ") << strKeyFields << _T(" FROM `") << strTargetDB << _T("`.`") << tbl.strName << _T("`)");
_tprintf( " Querying for records to insert..." );
XMySQL::CResultSet rsInserts( m_mySource, XMySQL::CResultSet::Client );
rsInserts.Execute( dataInsertStream.str().c_str() );
if( !rsInserts.IsEOF() )
{
const std::string bulkInsertStartStatement( _T("INSERT INTO `") + tbl.strName + _T("`(") + strAllFields + _T(") VALUES ") );
static const std::string endStatement( _T(";\n") );
m_arrInsert.push_back( bulkInsertStartStatement );
std::string bulkInsertValuesStatement;
while( !rsInserts.IsEOF() )
{
if( m_bUseBulkInserts )
{
// INSERT INTO programmekeyword(nProgrammeID, nKeywordID) VALUES
// (740044, 37),
// (740044, 42),
// (740044, 560);
{
if( bulkInsertValuesStatement.size() )
bulkInsertValuesStatement += _T(",");
bulkInsertValuesStatement += _T("\n(") + BuildBulkInsertFieldValues( rsInserts ) + _T(")");
}
if( m_uRecordsInserted && m_uRecordsInserted % 200 == 0 )
{
m_arrInsert.push_back( bulkInsertValuesStatement );
m_arrInsert.push_back( endStatement );
m_arrInsert.push_back( bulkInsertStartStatement );
bulkInsertValuesStatement.clear();
}
}
else
{
std::string streamStatement;
streamStatement += _T("INSERT INTO `") + tbl.strName + _T("`");
streamStatement += _T(" SET ") + BuildInsertFieldValues( rsInserts ) + _T(";\n");
m_arrInsert.push_back( streamStatement );
}
m_uRecordsInserted++;
if( m_bDisplayProgress )
{
float nPercent = ( (float)rsInserts.GetCurrentRowNum() / (float)rsInserts.GetRowCount() ) * 100;
_tprintf( _T("\r Analysing inserts: %3.0f%% (%d of %d) "), nPercent, static_cast<UINT>(rsInserts.GetCurrentRowNum()), static_cast<UINT>(rsInserts.GetRowCount()) );
}
rsInserts.MoveNext();
}
if( m_bUseBulkInserts && bulkInsertValuesStatement.size() )
{
// Some left over
m_arrInsert.push_back( bulkInsertValuesStatement );
m_arrInsert.push_back( endStatement );
}
}
else
{
_tprintf( _T("\r Analysed inserts, none found ") );
}
// Next find our records to delete...
// SELECT count(*),nid FROM `exportpdb_live`.person WHERE nid NOT IN (SELECT nid FROM `exportpdb_new`.person)
std::stringstream dataDeleteStream;
dataDeleteStream << _T("SELECT ") << strKeyFields;
dataDeleteStream << _T(" FROM `") << strTargetDB << _T("`.`") << tbl.strName << _T("`");
dataDeleteStream << _T(" WHERE (") << strKeyFields << _T(") NOT IN (SELECT ") << strKeyFields << _T(" FROM `") << strSourceDB << _T("`.`") << tbl.strName << _T("`)");
_tprintf( "\n Querying for records to delete..." );
// _tprintf( "DELETE records: %s\n\n", dataDeleteStream.str().c_str() );
XMySQL::CResultSet rsDeletes( m_mySource, XMySQL::CResultSet::Client );
rsDeletes.Execute( dataDeleteStream.str().c_str() );
if( !rsDeletes.IsEOF() )
{
while( !rsDeletes.IsEOF() )
{
// Target doesnt exist in source, delete it...
std::stringstream deleteStatementStream;
deleteStatementStream << _T("DELETE FROM `") << tbl.strName << _T("`");
deleteStatementStream << BuildDeleteWhereClause( rsDeletes ) << _T(";\n");
m_arrDelete.push_back( deleteStatementStream.str() );
m_uRecordsDeleted++;
if( m_bDisplayProgress )
{
float nPercent = ( (float)rsDeletes.GetCurrentRowNum() / (float)rsDeletes.GetRowCount() ) * 100;
_tprintf( _T("\r Analysing deletes: %3.0f%% (%d of %d) "), nPercent, static_cast<UINT>(rsDeletes.GetCurrentRowNum()), static_cast<UINT>(rsDeletes.GetRowCount()) );
}
rsDeletes.MoveNext();
}
}
else
{
_tprintf( _T("\r Analysed deletes, none found ") );
}
// Next find our records to be updated
// SELECT
// `exportpdb_new`.`schedulepersontypelink`.nscheduleid
// , `exportpdb_new`.`schedulepersontypelink`.nPersonID
// , `exportpdb_new`.`schedulepersontypelink`.nType
// , `exportpdb_new`.`schedulepersontypelink`.nOrder
// , `exportpdb_new`.`schedulepersontypelink`.strRole
//
// , `exportpdb_live`.`schedulepersontypelink`.nscheduleid
// , `exportpdb_live`.`schedulepersontypelink`.nPersonID
// , `exportpdb_live`.`schedulepersontypelink`.nType
// , `exportpdb_live`.`schedulepersontypelink`.nOrder
// , `exportpdb_live`.`schedulepersontypelink`.strRole
//
// FROM `exportpdb_new`.`schedulepersontypelink`
//
// INNER JOIN `exportpdb_live`.`schedulepersontypelink`
// ON (`exportpdb_live`.`schedulepersontypelink`.nscheduleid = `exportpdb_new`.`schedulepersontypelink`.nscheduleid
// AND `exportpdb_live`.`schedulepersontypelink`.nPersonID = `exportpdb_new`.`schedulepersontypelink`.nPersonID
// AND `exportpdb_live`.`schedulepersontypelink`.nType = `exportpdb_new`.`schedulepersontypelink`.nType )
//
// WHERE
// SHA1
// (
// CONCAT_WS( '-', `exportpdb_new`.`schedulepersontypelink`.nscheduleid, `exportpdb_new`.`schedulepersontypelink`.nPersonID, `exportpdb_new`.`schedulepersontypelink`.nType, `exportpdb_new`.`schedulepersontypelink`.nOrder, `exportpdb_new`.`schedulepersontypelink`.strRole )
// )
// <>
// SHA1
// (
// CONCAT_WS( '-', `exportpdb_live`.`schedulepersontypelink`.nscheduleid, `exportpdb_live`.`schedulepersontypelink`.nPersonID, `exportpdb_live`.`schedulepersontypelink`.nType, `exportpdb_live`.`schedulepersontypelink`.nOrder, `exportpdb_live`.`schedulepersontypelink`.strRole )
// );
if( !_tcsicmp( tbl.strName.c_str(), _T("programmepersontype") ) )
{
_tprintf( "\n here..." );
}
std::stringstream dataUpdateStream;
dataUpdateStream << _T("SELECT ") << strAllFieldsWithSourceDB << _T(",") << strAllFieldsWithTargetDB;
dataUpdateStream << _T(" FROM `") << strSourceDB << _T("`.`") << tbl.strName << _T("`");
dataUpdateStream << _T(" INNER JOIN `") << strTargetDB << _T("`.`") << tbl.strName << _T("`");
dataUpdateStream << _T(" ON (") << strKeyFieldsJoinWithDB << _T(")");
dataUpdateStream << _T(" WHERE SHA1( CONCAT_WS( '-', ") << strAllFieldsWithSourceDB << _T(" ) ) <> SHA1( CONCAT_WS( '-', ") << strAllFieldsWithTargetDB << _T(" ) )");
_tprintf( "\n Querying for records to update..." );
_tprintf( "UPDATE records: %s\n\n", dataUpdateStream.str().c_str() );
//
// Build up our update statements for fields that are different
XMySQL::CResultSet rsSource( m_mySource, XMySQL::CResultSet::Client );
rsSource.Execute( dataUpdateStream.str().c_str() );
if( !rsSource.IsEOF() )
{
while( !rsSource.IsEOF() )
{
std::vector< CTableCompareABC::Field > arrKeyValues;
std::vector< CTableCompareABC::Field > arrDifferentFields;
for( UINT u = 0; u < uNumFields; u++ )
{
const char * pszSourceFieldName = rsSource.GetFieldName( u );
const char * pszSourceFieldValue = rsSource.GetFieldValue( u );
const char * pszTargetFieldName = rsSource.GetFieldName( u + (UINT)uNumFields );
const char * pszTargetFieldValue = rsSource.GetFieldValue( u + (UINT)uNumFields );
if( _tcsicmp( pszSourceFieldName, pszTargetFieldName ) )
{
// fields out of order, should never happen
break;
}
bool bFieldDifferent = false;
if( pszSourceFieldValue == NULL && pszTargetFieldValue == NULL )
{
// Both same, no compare
}
else if( ( pszSourceFieldValue == NULL && pszTargetFieldValue != NULL ) || ( pszSourceFieldValue != NULL && pszTargetFieldValue == NULL ) )
{
// One is a null, the other is not, so different
bFieldDifferent = true;
}
else
{
// Both same and not null so compare values, case sensitive
if( strcmp( pszSourceFieldValue, pszTargetFieldValue ) )
{
bFieldDifferent = true;
}
}
if( bFieldDifferent )
{
CTableCompareABC::Field fld;
fld.bIsDifferent = true;
fld.bIsNull = ( pszSourceFieldValue == NULL ) ? true : false;
fld.uType = rsSource.GetFieldType( u );
fld.strName = std::string( pszSourceFieldName );
if( !fld.bIsNull )
{
fld.strValue = std::string( pszSourceFieldValue );
}
arrDifferentFields.push_back( fld );
}
if( rsSource.IsFieldPrimaryKey( u ) || rsSource.IsFieldUniqueKey( u ) )
{
CTableCompareABC::Field fldKey;
fldKey.bIsNull = ( pszTargetFieldValue == NULL ) ? true : false;
fldKey.uType = rsSource.GetFieldType( u );
fldKey.strName = std::string( pszTargetFieldName );
if( !fldKey.bIsNull )
{
fldKey.strValue = std::string( pszTargetFieldValue );
}
arrKeyValues.push_back( fldKey );
}
}
{
std::stringstream updateStatementStream;
updateStatementStream << _T("UPDATE `") << tbl.strName << _T("`");
updateStatementStream << _T(" SET ") << BuildUpdateValues( arrDifferentFields ) << BuildUpdateWhereClause( arrKeyValues ) << _T(";\n");
m_arrUpdate.push_back( updateStatementStream.str() );
m_uRecordsDifferent++;
}
if( m_bDisplayProgress )
{
float nPercent = ( (float)rsSource.GetCurrentRowNum() / (float)rsSource.GetRowCount() ) * 100;
_tprintf( _T("\r Analysing updates: %3.0f%% (%d of %d) "), nPercent, static_cast<UINT>(rsSource.GetCurrentRowNum()), static_cast<UINT>(rsSource.GetRowCount()) );
}
rsSource.MoveNext();
}
}
else
{
_tprintf( _T("\r Analysed updates, none found ") );
}
m_uRecordsIdentical = uTotalRecords - m_uRecordsDifferent - m_uRecordsInserted;
}
std::string CTableCompareQuery::BuildUpdateValues( const std::vector< CTableCompareABC::Field > &arrFields )
{
// Build a stream of all our name=value column value pairs
std::stringstream streamFields;
for( UINT u = 0; u < arrFields.size(); u++ )
{
const CTableCompareABC::Field &fld = arrFields.at( u );
if( streamFields.str().size() )
{
streamFields << _T(",");
}
streamFields << fld.strName;
streamFields << _T("=");
if( fld.bIsNull )
{
streamFields << _T("NULL");
}
else
{
if( FieldIsQuoted( fld.uType ) )
{
streamFields << _T("'");
std::string sValue( fld.strValue );
m_mySource.EscapeString( sValue );
streamFields << sValue;
streamFields << _T("'");
}
else
{
streamFields << fld.strValue;
}
}
}
return streamFields.str();
}
std::string CTableCompareQuery::BuildUpdateWhereClause( const std::vector< CTableCompareABC::Field > &arrFields )
{
// Build a stream of all our keyed name=value column value pairs
std::stringstream streamFields;
streamFields << _T(" WHERE ");
UINT uFieldAddedCount = 0;
for( UINT u = 0; u < arrFields.size(); u++ )
{
const CTableCompareABC::Field &fld = arrFields.at( u );
if( uFieldAddedCount )
{
streamFields << _T(" AND ");
}
streamFields << fld.strName;
streamFields << _T("=");
if( FieldIsQuoted( fld.uType ) )
{
streamFields << _T("'");
std::string sValue( fld.strValue );
m_mySource.EscapeString( sValue );
streamFields << sValue;
streamFields << _T("'");
}
else
{
streamFields << fld.strValue;
}
uFieldAddedCount++;
}
return streamFields.str();
}
std::string CTableCompareQuery::BuildInsertFieldValues( const XMySQL::CResultSet &rs )
{
// Build a stream of all our keyed name=value column value pairs
std::stringstream streamFields;
const UINT uFieldCount = rs.GetFieldCount();
for( UINT u = 0; u < uFieldCount; u++ )
{
const UINT uFieldType = rs.GetFieldType( u );
if( streamFields.str().size() )
{
streamFields << _T(",");
}
streamFields << rs.GetFieldName( u );
streamFields << _T("=");
if( rs.IsNull( u ) )
{
streamFields << _T("NULL");
}
else
{
const char * pcszFieldValue = rs.GetFieldValue( u );
if( FieldIsQuoted( uFieldType ) )
{
streamFields << _T("'");
std::string sValue( pcszFieldValue );
m_mySource.EscapeString( sValue );
streamFields << sValue;
streamFields << _T("'");
}
else
{
streamFields << pcszFieldValue;
}
}
}
return streamFields.str();
}
std::string CTableCompareQuery::BuildBulkInsertFieldValues( const XMySQL::CResultSet &rs )
{
// Build a stream of all our keyed name=value column value pairs
std::stringstream streamFields;
const UINT uFieldCount = rs.GetFieldCount();
for( UINT u = 0; u < uFieldCount; u++ )
{
const UINT uFieldType = rs.GetFieldType( u );
if( streamFields.str().size() )
{
streamFields << _T(",");
}
if( rs.IsNull( u ) )
{
streamFields << _T("NULL");
}
else
{
const char * pcszFieldValue = rs.GetFieldValue( u );
if( FieldIsQuoted( uFieldType ) )
{
streamFields << _T("'");
std::string sValue( pcszFieldValue );
m_mySource.EscapeString( sValue );
streamFields << sValue;
streamFields << _T("'");
}
else
{
streamFields << pcszFieldValue;
}
}
}
return streamFields.str();
}
std::string CTableCompareQuery::BuildDeleteWhereClause( const XMySQL::CResultSet &rs )
{
// Build a stream of all our keyed name=value column value pairs
std::stringstream streamFields;
streamFields << _T(" WHERE ");
UINT uFieldAddedCount = 0;
const UINT uFieldCount = rs.GetFieldCount();
for( UINT u = 0; u < uFieldCount; u++ )
{
const bool bIsPrimaryKey = rs.IsFieldPrimaryKey( u );
const bool bIsUniqueKey = rs.IsFieldUniqueKey( u );
if( bIsPrimaryKey || bIsUniqueKey )
{
const UINT uFieldType = rs.GetFieldType( u );
if( uFieldAddedCount )
{
streamFields << _T(" AND ");
}
streamFields << rs.GetFieldName( u );
streamFields << _T("=");
if( rs.IsNull( u ) )
{
streamFields << _T("NULL");
}
else
{
const char * pcszFieldValue = rs.GetFieldValue( u );
if( FieldIsQuoted( uFieldType ) )
{
streamFields << _T("'");
std::string sValue( pcszFieldValue );
m_mySource.EscapeString( sValue );
streamFields << sValue;
streamFields << _T("'");
}
else
{
streamFields << pcszFieldValue;
}
}
uFieldAddedCount++;
}
}
return streamFields.str();
}