File: TableSyncNibble.t

package info (click to toggle)
percona-toolkit 3.2.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 68,916 kB
  • sloc: perl: 241,287; sql: 22,868; sh: 19,746; javascript: 6,799; makefile: 353; awk: 38; python: 30; sed: 1
file content (629 lines) | stat: -rw-r--r-- 21,894 bytes parent folder | download | duplicates (2)
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
#!/usr/bin/perl

BEGIN {
   die "The PERCONA_TOOLKIT_BRANCH environment variable is not set.\n"
      unless $ENV{PERCONA_TOOLKIT_BRANCH} && -d $ENV{PERCONA_TOOLKIT_BRANCH};
   unshift @INC, "$ENV{PERCONA_TOOLKIT_BRANCH}/lib";
};

use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use Test::More;

use DSNParser;
use Sandbox;
use TableSyncNibble;
use Quoter;
use ChangeHandler;
use TableChecksum;
use TableChunker;
use TableNibbler;
use TableParser;
use VersionParser;
use MasterSlave;
use Retry;
use TableSyncer;
use PerconaTest;

my $dp  = new DSNParser(opts=>$dsn_opts);
my $sb  = new Sandbox(basedir => '/tmp', DSNParser => $dp);
my $dbh = $sb->get_dbh_for('master');

if ( !$dbh ) {
   plan skip_all => 'Cannot connect to sandbox master';
}
else {
   plan tests => 37;
}

my $mysql = $sb->_use_for('master');

my $q  = new Quoter();
my $ms = new MasterSlave(OptionParser=>1,DSNParser=>1,Quoter=>1);
my $tp = new TableParser(Quoter=>$q);
my $rr = new Retry();

my $nibbler = new TableNibbler(
   TableParser => $tp,
   Quoter      => $q,
);
my $checksum = new TableChecksum(
   Quoter        => $q,
);
my $chunker = new TableChunker(
   TableParser => $tp,
   Quoter      => $q
);
my $t = new TableSyncNibble(
   TableNibbler  => $nibbler,
   TableParser   => $tp,
   TableChunker  => $chunker,
   Quoter        => $q,
);

my @rows;
my $ch = new ChangeHandler(
   Quoter    => $q,
   right_db  => 'test',
   right_tbl => 'test1',
   left_db   => 'test',
   left_tbl  => 'test1',
   replace   => 0,
   actions   => [ sub { push @rows, $_[0] }, ],
   queue     => 0,
);

my $syncer = new TableSyncer(
   MasterSlave   => $ms,
   TableChecksum => $checksum,
   Quoter        => $q,
   Retry         => $rr,
);

$sb->create_dbs($dbh, ['test']);
diag(`$mysql < $trunk/t/lib/samples/before-TableSyncNibble.sql`);
my $ddl        = $tp->get_create_table($dbh, 'test', 'test1');
my $tbl_struct = $tp->parse($ddl);
my $src = {
   db  => 'test',
   tbl => 'test1',
   dbh => $dbh,
};
my $dst = {
   db  => 'test',
   tbl => 'test1',
   dbh => $dbh,
};
my %args       = (
   src           => $src,
   dst           => $dst,
   dbh           => $dbh,
   db            => 'test',
   tbl           => 'test1',
   tbl_struct    => $tbl_struct,
   cols          => $tbl_struct->{cols},
   chunk_size    => 1,
   chunk_index   => 'PRIMARY',
   key_cols      => $tbl_struct->{keys}->{PRIMARY}->{cols},
   crc_col       => '__crc',
   index_hint    => 'USE INDEX (`PRIMARY`)',
   ChangeHandler => $ch,
);

$t->prepare_to_sync(%args);
# Test with FNV_64 just to make sure there are no errors
eval { $dbh->do('select fnv_64(1)') };
SKIP: {
   skip 'No FNV_64 function installed', 1 if $EVAL_ERROR;

   $t->set_checksum_queries(
      $syncer->make_checksum_queries(%args, function => 'FNV_64')
   );
   is(
      $t->get_sql(
         database => 'test',
         table    => 'test1',
      ),
      q{SELECT /*test.test1:1/1*/ 0 AS chunk_num, COUNT(*) AS }
      . q{cnt, COALESCE(LOWER(CONV(BIT_XOR(CAST(FNV_64(`a`, `b`, `c`) AS UNSIGNED)), }
      . q{10, 16)), 0) AS crc FROM `test`.`test1` USE INDEX (`PRIMARY`) WHERE (((`a` < '1') OR (`a` = '1' }
      . q{AND `b` <= 'en')))},
      'First nibble SQL with FNV_64',
   );
}

$t->set_checksum_queries(
   $syncer->make_checksum_queries(%args, function => 'SHA1')
);
is(
   $t->get_sql(
      database => 'test',
      table    => 'test1',
   ),
   ($sandbox_version gt '4.0' ?
   q{SELECT /*test.test1:1/1*/ 0 AS chunk_num, COUNT(*) AS cnt, }
   . q{COALESCE(LOWER(CONCAT(LPAD(CONV(BIT_XOR(CAST(CONV(SUBSTRING(@crc, 1, 16), 16, }
   . q{10) AS UNSIGNED)), 10, 16), 16, '0'), LPAD(CONV(BIT_XOR(CAST(CONV(}
   . q{SUBSTRING(@crc, 17, 16), 16, 10) AS UNSIGNED)), 10, 16), 16, '0'), }
   . q{LPAD(CONV(BIT_XOR(CAST(CONV(SUBSTRING(@crc := SHA1(CONCAT_WS('#', `a`, }
   . q{`b`, `c`)), 33, 8), 16, 10) AS UNSIGNED)), 10, 16), 8, '0'))), 0) AS crc FROM }
   . q{`test`.`test1` USE INDEX (`PRIMARY`) WHERE (((`a` < '1') OR (`a` = '1' AND `b` <= 'en')))} :
   q{SELECT /*test.test1:1/1*/ 0 AS chunk_num, COUNT(*) AS cnt, }
   . q{COALESCE(RIGHT(MAX(@crc := CONCAT(LPAD(@cnt := @cnt + 1, 16, '0'), }
   . q{SHA1(CONCAT(@crc, SHA1(CONCAT_WS('#', `a`, `b`, `c`)))))), 40), 0) AS crc FROM }
   . q{`test`.`test1` USE INDEX (`PRIMARY`) WHERE (((`a` < '1') OR (`a` = '1' AND `b` <= 'en')))}
   ),
   'First nibble SQL',
);

is(
   $t->get_sql(
      database => 'test',
      table    => 'test1',
   ),
   ($sandbox_version gt '4.0' ?
   q{SELECT /*test.test1:1/1*/ 0 AS chunk_num, COUNT(*) AS cnt, }
   . q{COALESCE(LOWER(CONCAT(LPAD(CONV(BIT_XOR(CAST(CONV(SUBSTRING(@crc, 1, 16), 16, }
   . q{10) AS UNSIGNED)), 10, 16), 16, '0'), LPAD(CONV(BIT_XOR(CAST(CONV(}
   . q{SUBSTRING(@crc, 17, 16), 16, 10) AS UNSIGNED)), 10, 16), 16, '0'), }
   . q{LPAD(CONV(BIT_XOR(CAST(CONV(SUBSTRING(@crc := SHA1(CONCAT_WS('#', `a`, }
   . q{`b`, `c`)), 33, 8), 16, 10) AS UNSIGNED)), 10, 16), 8, '0'))), 0) AS crc FROM }
   . q{`test`.`test1` USE INDEX (`PRIMARY`) WHERE (((`a` < '1') OR (`a` = '1' AND `b` <= 'en')))} :
   q{SELECT /*test.test1:1/1*/ 0 AS chunk_num, COUNT(*) AS cnt, }
   . q{COALESCE(RIGHT(MAX(@crc := CONCAT(LPAD(@cnt := @cnt + 1, 16, '0'), }
   . q{SHA1(CONCAT(@crc, SHA1(CONCAT_WS('#', `a`, `b`, `c`)))))), 40), 0) AS crc FROM }
   . q{`test`.`test1` USE INDEX (`PRIMARY`) WHERE (((`a` < '1') OR (`a` = '1' AND `b` <= 'en')))}
   ),
   'First nibble SQL, again',
);

$t->{nibble} = 1;
delete $t->{cached_boundaries};

is(
   $t->get_sql(
      database => 'test',
      table    => 'test1',
   ),
   ($sandbox_version gt '4.0' ?
   q{SELECT /*test.test1:1/1*/ 0 AS chunk_num, COUNT(*) AS cnt, }
   . q{COALESCE(LOWER(CONCAT(LPAD(CONV(BIT_XOR(CAST(CONV(SUBSTRING(@crc, 1, 16), 16, }
   . q{10) AS UNSIGNED)), 10, 16), 16, '0'), LPAD(CONV(BIT_XOR(CAST(CONV(}
   . q{SUBSTRING(@crc, 17, 16), 16, 10) AS UNSIGNED)), 10, 16), 16, '0'), }
   . q{LPAD(CONV(BIT_XOR(CAST(CONV(SUBSTRING(@crc := SHA1(CONCAT_WS('#', `a`, }
   . q{`b`, `c`)), 33, 8), 16, 10) AS UNSIGNED)), 10, 16), 8, '0'))), 0) AS crc FROM }
   . q{`test`.`test1` USE INDEX (`PRIMARY`) WHERE ((((`a` > '1') OR (`a` = '1' AND `b` > 'en')) AND }
   . q{((`a` < '2') OR (`a` = '2' AND `b` <= 'ca'))))} :
   q{SELECT /*test.test1:1/1*/ 0 AS chunk_num, COUNT(*) AS cnt, }
   . q{COALESCE(RIGHT(MAX(@crc := CONCAT(LPAD(@cnt := @cnt + 1, 16, '0'), }
   . q{SHA1(CONCAT(@crc, SHA1(CONCAT_WS('#', `a`, `b`, `c`)))))), 40), 0) AS crc FROM }
   . q{`test`.`test1` USE INDEX (`PRIMARY`) WHERE ((((`a` > '1') OR (`a` = '1' AND `b` > 'en')) AND }
   . q{((`a` < '2') OR (`a` = '2' AND `b` <= 'ca'))))}
   ),
   'Second nibble SQL',
);

# Bump the nibble boundaries ahead until we run off the end of the table.
$t->done_with_rows();
$t->get_sql(
      database => 'test',
      table    => 'test1',
   );
$t->done_with_rows();
$t->get_sql(
      database => 'test',
      table    => 'test1',
   );
$t->done_with_rows();
$t->get_sql(
      database => 'test',
      table    => 'test1',
   );

is(
   $t->get_sql(
      database => 'test',
      table    => 'test1',
   ),
   ($sandbox_version gt '4.0' ?
   q{SELECT /*test.test1:1/1*/ 0 AS chunk_num, COUNT(*) AS cnt, }
   . q{COALESCE(LOWER(CONCAT(LPAD(CONV(BIT_XOR(CAST(CONV(SUBSTRING(@crc, 1, 16), 16, }
   . q{10) AS UNSIGNED)), 10, 16), 16, '0'), LPAD(CONV(BIT_XOR(CAST(CONV(}
   . q{SUBSTRING(@crc, 17, 16), 16, 10) AS UNSIGNED)), 10, 16), 16, '0'), }
   . q{LPAD(CONV(BIT_XOR(CAST(CONV(SUBSTRING(@crc := SHA1(CONCAT_WS('#', `a`, }
   . q{`b`, `c`)), 33, 8), 16, 10) AS UNSIGNED)), 10, 16), 8, '0'))), 0) AS crc FROM }
   . q{`test`.`test1` USE INDEX (`PRIMARY`) WHERE ((((`a` > '4') OR (`a` = '4' AND `b` > 'bz')) AND }
   . q{1=1))} :
   q{SELECT /*test.test1:1/1*/ 0 AS chunk_num, COUNT(*) AS cnt, }
   . q{COALESCE(RIGHT(MAX(@crc := CONCAT(LPAD(@cnt := @cnt + 1, 16, '0'), }
   . q{SHA1(CONCAT(@crc, SHA1(CONCAT_WS('#', `a`, `b`, `c`)))))), 40), 0) AS crc FROM }
   . q{`test`.`test1` USE INDEX (`PRIMARY`) WHERE ((((`a` > '4') OR (`a` = '4' AND `b` > 'bz')) AND }
   . q{1=1))}
   ),
   'End-of-table nibble SQL',
);

$t->done_with_rows();
ok($t->done(), 'Now done');

# Throw away and start anew, because it's off the end of the table
$t->{nibble} = 0;
delete $t->{cached_boundaries};
delete $t->{cached_nibble};
delete $t->{cached_row};

is_deeply($t->key_cols(), [qw(chunk_num)], 'Key cols in state 0');
$t->get_sql(
      database => 'test',
      table    => 'test1',
   );
$t->done_with_rows();

is($t->done(), '', 'Not done, because not reached end-of-table');

throws_ok(
   sub { $t->not_in_left() },
   qr/in state 0/,
   'not_in_(side) illegal in state 0',
);

# Now "find some bad chunks," as it were.

# "find a bad row"
$t->same_row(
   lr => { chunk_num => 0, cnt => 0, crc => 'abc' },
   rr => { chunk_num => 0, cnt => 1, crc => 'abc' },
);
ok($t->pending_changes(), 'Pending changes found');
is($t->{state}, 1, 'Working inside nibble');
$t->done_with_rows();
is($t->{state}, 2, 'Now in state to fetch individual rows');
ok($t->pending_changes(), 'Pending changes not done yet');
is($t->get_sql(database => 'test', table => 'test1'),
   q{SELECT /*rows in nibble*/ `a`, `b`, `c`, SHA1(CONCAT_WS('#', `a`, `b`, `c`)) AS __crc FROM }
   . q{`test`.`test1` USE INDEX (`PRIMARY`) WHERE ((((`a` > '1') OR (`a` = '1' AND `b` > 'en')) }
   . q{AND ((`a` < '2') OR (`a` = '2' AND `b` <= 'ca'))))}
   . q{ ORDER BY `a`, `b`},
   'SQL now working inside nibble'
);
ok($t->{state}, 'Still working inside nibble');
is(scalar(@rows), 0, 'No bad row triggered');

$t->not_in_left(rr => {a => 1, b => 'en'});

is_deeply(\@rows,
   ["DELETE FROM `test`.`test1` WHERE `a`='1' AND `b`='en' LIMIT 1"],
   'Working inside nibble, got a bad row',
);

# Shouldn't cause anything to happen
$t->same_row(
   lr => {a => 1, b => 'en', __crc => 'foo'},
   rr => {a => 1, b => 'en', __crc => 'foo'} );

is_deeply(\@rows,
   ["DELETE FROM `test`.`test1` WHERE `a`='1' AND `b`='en' LIMIT 1"],
   'No more rows added',
);

$t->same_row(
   lr => {a => 1, b => 'en', __crc => 'foo'},
   rr => {a => 1, b => 'en', __crc => 'bar'} );

is_deeply(\@rows,
   [
      "DELETE FROM `test`.`test1` WHERE `a`='1' AND `b`='en' LIMIT 1",
      "UPDATE `test`.`test1` SET `c`='a' WHERE `a`='1' AND `b`='en' LIMIT 1",
   ],
   'Row added to update differing row',
);

$t->done_with_rows();
is($t->{state}, 0, 'Now not working inside nibble');
is($t->pending_changes(), 0, 'No pending changes');

# Now test that SQL_BUFFER_RESULT is in the queries OK
$t->prepare_to_sync(%args, buffer_in_mysql=>1);
$t->{state} = 1;
like(
   $t->get_sql(
      database => 'test',
      table    => 'test1',
      buffer_in_mysql => 1,
   ),
   qr/SELECT ..rows in nibble.. SQL_BUFFER_RESULT/,
   'Buffering in first nibble',
);

# "find a bad row"
$t->same_row(
   lr => { chunk_num => 0, cnt => 0, __crc => 'abc' },
   rr => { chunk_num => 0, cnt => 1, __crc => 'abc' },
);

like(
   $t->get_sql(
      database => 'test',
      table    => 'test1',
      buffer_in_mysql => 1,
   ),
   qr/SELECT ..rows in nibble.. SQL_BUFFER_RESULT/,
   'Buffering in next nibble',
);

# #########################################################################
# Issue 96: mk-table-sync: Nibbler infinite loop
# #########################################################################
$sb->load_file('master', 't/lib/samples/issue_96.sql');
$tbl_struct = $tp->parse($tp->get_create_table($dbh, 'issue_96', 't'));
$t->prepare_to_sync(
   ChangeHandler  => $ch,
   cols           => $tbl_struct->{cols},
   dbh            => $dbh,
   db             => 'issue_96',
   tbl            => 't',
   tbl_struct     => $tbl_struct,
   chunk_size     => 2,
   chunk_index    => 'package_id',
   crc_col        => '__crc_col',
   index_hint     => 'FORCE INDEX(`package_id`)',
   key_cols       => $tbl_struct->{keys}->{package_id}->{cols},
);

# Test that we die if MySQL isn't using the chosen index (package_id)
# for the boundary sql.

my $sql = "SELECT /*nibble boundary 0*/ `package_id`,`location`,`from_city` FROM `issue_96`.`t` FORCE INDEX(`package_id`) ORDER BY `package_id`,`location` LIMIT 1, 1";
is(
   $t->__get_explain_index($sql),
   'package_id',
   '__get_explain_index()'
);

diag(`/tmp/12345/use -e 'ALTER TABLE issue_96.t DROP INDEX package_id'`);

is(
   $t->__get_explain_index($sql),
   undef,
   '__get_explain_index() for nonexistent index'
);

my %args2 = ( database=>'issue_96', table=>'t' );
eval {
   $t->get_sql(database=>'issue_96', tbl=>'t', %args2);
};
like(
   $EVAL_ERROR,
   qr/^Cannot nibble table `issue_96`.`t` because MySQL chose no index instead of the `package_id` index/,
   "Die if MySQL doesn't choose our index (issue 96)"
);

# Restore the index, get the first sql boundary and check that it
# has the proper ORDER BY clause which makes MySQL use the index.
diag(`/tmp/12345/use -e 'ALTER TABLE issue_96.t ADD UNIQUE INDEX package_id (package_id,location);'`);
eval {
   ($sql,undef) = $t->__make_boundary_sql(%args2);
};
is(
   $sql,
   "SELECT /*nibble boundary 0*/ `package_id`,`location`,`from_city` FROM `issue_96`.`t` FORCE INDEX(`package_id`) ORDER BY `package_id`,`location` LIMIT 1, 1",
   'Boundary SQL has ORDER BY key columns'
);

# If small_table is true, the index check should be skipped.
diag(`/tmp/12345/use -e 'create table issue_96.t3 (i int, unique index (i))'`);
diag(`/tmp/12345/use -e 'insert into issue_96.t3 values (1)'`);
$tbl_struct = $tp->parse($tp->get_create_table($dbh, 'issue_96', 't3'));
$t->prepare_to_sync(
   ChangeHandler  => $ch,
   cols           => $tbl_struct->{cols},
   dbh            => $dbh,
   db             => 'issue_96',
   tbl            => 't3',
   tbl_struct     => $tbl_struct,
   chunk_size     => 2,
   chunk_index    => 'i',
   crc_col        => '__crc_col',
   index_hint     => 'FORCE INDEX(`i`)',
   key_cols       => $tbl_struct->{keys}->{i}->{cols},
   small_table    => 1,
);
eval {
   $t->get_sql(database=>'issue_96', table=>'t3');
};
is(
   $EVAL_ERROR,
   '',
   "Skips index check when small table (issue 634)"
);

my ($can_sync, %plugin_args);
SKIP: {
   skip "Not tested on MySQL $sandbox_version", 5
      unless $sandbox_version gt '4.0';

# #############################################################################
# Issue 560: mk-table-sync generates impossible WHERE
# Issue 996: might not chunk inside of mk-table-checksum's boundaries
# #############################################################################
# Due to issue 996 this test has changed.  Now it *should* use the replicate
# boundary provided via the where arg and nibble just inside this boundary.
# If it does, then it will prevent the impossible WHERE of issue 560.

# The buddy_list table has 500 rows, so when it's chunk into 100 rows this is
# chunk 2:
my $where = '`player_id` >= 201 AND `player_id` < 301';

$sb->load_file('master', 't/pt-table-sync/samples/issue_560.sql');
$tbl_struct = $tp->parse($tp->get_create_table($dbh, 'issue_560', 'buddy_list'));
(undef, %plugin_args) = $t->can_sync(tbl_struct => $tbl_struct);
$t->prepare_to_sync(
   ChangeHandler  => $ch,
   cols           => $tbl_struct->{cols},
   dbh            => $dbh,
   db             => 'issue_560',
   tbl            => 'buddy_list',
   tbl_struct     => $tbl_struct,
   chunk_size     => 100,
   crc_col        => '__crc_col',
   %plugin_args,
   replicate      => 'issue_560.checksum',
   where          => $where,  # not used in sub but normally passed so we
                              # do the same to simulate a real run
);

# Must call this else $row_sql will have values from previous test.
$t->set_checksum_queries(
   $syncer->make_checksum_queries(
      src        => $src,
      dst        => $dst,
      tbl_struct => $tbl_struct,
   )
);

is(
   $t->get_sql(
      where    => $where,
      database => 'issue_560',
      table    => 'buddy_list', 
   ),
   "SELECT /*issue_560.buddy_list:1/1*/ 0 AS chunk_num, COUNT(*) AS cnt, COALESCE(LOWER(CONV(BIT_XOR(CAST(CRC32(CONCAT_WS('#', `player_id`, `buddy_id`)) AS UNSIGNED)), 10, 16)), 0) AS crc FROM `issue_560`.`buddy_list`  WHERE (((`player_id` < '300') OR (`player_id` = '300' AND `buddy_id` <= '2085'))) AND (($where))",
   'Nibble with chunk boundary (chunk sql)'
);

$t->{state} = 2;
is(
   $t->get_sql(
      where    => $where,
      database => 'issue_560',
      table    => 'buddy_list', 
   ),
   "SELECT /*rows in nibble*/ `player_id`, `buddy_id`, CRC32(CONCAT_WS('#', `player_id`, `buddy_id`)) AS __crc_col FROM `issue_560`.`buddy_list`  WHERE (((`player_id` < '300') OR (`player_id` = '300' AND `buddy_id` <= '2085'))) AND ($where) ORDER BY `player_id`, `buddy_id`",
   'Nibble with chunk boundary (row sql)'
);

$t->{state} = 0;
$t->done_with_rows();
is(
   $t->get_sql(
      where    => $where,
      database => 'issue_560',
      table    => 'buddy_list', 
   ),
   "SELECT /*issue_560.buddy_list:1/1*/ 0 AS chunk_num, COUNT(*) AS cnt, COALESCE(LOWER(CONV(BIT_XOR(CAST(CRC32(CONCAT_WS('#', `player_id`, `buddy_id`)) AS UNSIGNED)), 10, 16)), 0) AS crc FROM `issue_560`.`buddy_list`  WHERE ((((`player_id` > '300') OR (`player_id` = '300' AND `buddy_id` > '2085')) AND 1=1)) AND (($where))",
   "Next sub-nibble",
);

# Just like the previous tests but this time the chunk size is 50 so we
# should nibble two chunks within the larger range ($where).
$t->prepare_to_sync(
   ChangeHandler  => $ch,
   cols           => $tbl_struct->{cols},
   dbh            => $dbh,
   db             => 'issue_560',
   tbl            => 'buddy_list',
   tbl_struct     => $tbl_struct,
   chunk_size     => 50,              # 2 sub-nibbles
   crc_col        => '__crc_col',
   %plugin_args,
   replicate      => 'issue_560.checksum',
   where          => $where,  # not used in sub but normally passed so we
                              # do the same to simulate a real run
);

# Must call this else $row_sql will have values from previous test.
$t->set_checksum_queries(
   $syncer->make_checksum_queries(
      src        => $src,
      dst        => $dst,
      tbl_struct => $tbl_struct,
   )
);

is(
   $t->get_sql(
      where    => $where,
      database => 'issue_560',
      table    => 'buddy_list', 
   ),
   "SELECT /*issue_560.buddy_list:1/1*/ 0 AS chunk_num, COUNT(*) AS cnt, COALESCE(LOWER(CONV(BIT_XOR(CAST(CRC32(CONCAT_WS('#', `player_id`, `buddy_id`)) AS UNSIGNED)), 10, 16)), 0) AS crc FROM `issue_560`.`buddy_list`  WHERE (((`player_id` < '250') OR (`player_id` = '250' AND `buddy_id` <= '809'))) AND ((`player_id` >= 201 AND `player_id` < 301))",
   "Sub-nibble 1"
);

$t->done_with_rows();
is(
   $t->get_sql(
      where    => $where,
      database => 'issue_560',
      table    => 'buddy_list', 
   ),
   "SELECT /*issue_560.buddy_list:1/1*/ 0 AS chunk_num, COUNT(*) AS cnt, COALESCE(LOWER(CONV(BIT_XOR(CAST(CRC32(CONCAT_WS('#', `player_id`, `buddy_id`)) AS UNSIGNED)), 10, 16)), 0) AS crc FROM `issue_560`.`buddy_list`  WHERE ((((`player_id` > '250') OR (`player_id` = '250' AND `buddy_id` > '809')) AND ((`player_id` < '300') OR (`player_id` = '300' AND `buddy_id` <= '2085')))) AND ((`player_id` >= 201 AND `player_id` < 301))",
   "Sub-nibble 2"
);
}

# #############################################################################
# Issue 804: mk-table-sync: can't nibble because index name isn't lower case?
# #############################################################################
$sb->load_file('master', 't/lib/samples/issue_804.sql');
$tbl_struct = $tp->parse($tp->get_create_table($dbh, 'issue_804', 't'));
($can_sync, %plugin_args) = $t->can_sync(tbl_struct => $tbl_struct);
is(
   $can_sync,
   1,
   'Can sync issue_804 table'
);
is_deeply(
   \%plugin_args,
   {
      chunk_index => 'purchases_accountid_purchaseid',
      key_cols    => [qw(accountid purchaseid)],
      small_table => 0,
   },
   'Plugin args for issue_804 table'
);

$t->prepare_to_sync(
   ChangeHandler  => $ch,
   cols           => $tbl_struct->{cols},
   dbh            => $dbh,
   db             => 'issue_804',
   tbl            => 't',
   tbl_struct     => $tbl_struct,
   chunk_size     => 50,
   chunk_index    => $plugin_args{chunk_index},
   crc_col        => '__crc_col',
   index_hint     => 'FORCE INDEX(`'.$plugin_args{chunk_index}.'`)',
   key_cols       => $tbl_struct->{keys}->{$plugin_args{chunk_index}}->{cols},
);

# Must call this else $row_sql will have values from previous test.
$t->set_checksum_queries(
   $syncer->make_checksum_queries(
      src        => $src,
      dst        => $dst,
      tbl_struct => $tbl_struct,
   )
);

# Before fixing issue 804, the code would die during this call, saying:
# Cannot nibble table `issue_804`.`t` because MySQL chose the
# `purchases_accountId_purchaseId` index instead of the
# `purchases_accountid_purchaseid` index at TableSyncNibble.pm line 284.
$sql = $t->get_sql(database=>'issue_804', table=>'t');
is(
   $sql,
   ($sandbox_version gt '4.0' ?
   "SELECT /*issue_804.t:1/1*/ 0 AS chunk_num, COUNT(*) AS cnt, COALESCE(LOWER(CONV(BIT_XOR(CAST(CRC32(CONCAT_WS('#', `accountid`, `purchaseid`)) AS UNSIGNED)), 10, 16)), 0) AS crc FROM `issue_804`.`t` FORCE INDEX(`purchases_accountid_purchaseid`) WHERE (((`accountid` < '49') OR (`accountid` = '49' AND `purchaseid` <= '50')))" :
   "SELECT /*issue_804.t:1/1*/ 0 AS chunk_num, COUNT(*) AS cnt, COALESCE(RIGHT(MAX(\@crc := CONCAT(LPAD(\@cnt := \@cnt + 1, 16, '0'), MD5(CONCAT(\@crc, MD5(CONCAT_WS('#', `accountid`, `purchaseid`)))))), 32), 0) AS crc FROM `issue_804`.`t` FORCE INDEX(`purchases_accountid_purchaseid`) WHERE (((`accountid` < '49') OR (`accountid` = '49' AND `purchaseid` <= '50')))"
   ),
   'SQL nibble for issue_804 table'
);

# #############################################################################
# Done.
# #############################################################################
$sb->wipe_clean($dbh);
ok($sb->ok(), "Sandbox servers") or BAIL_OUT(__FILE__ . " broke the sandbox");
exit;