forked from ceardach/dbscripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdbscripts.module
More file actions
2608 lines (2181 loc) · 95.9 KB
/
Copy pathdbscripts.module
File metadata and controls
2608 lines (2181 loc) · 95.9 KB
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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* Global locked function so db scripts can be locked from restore at various input gathering parts
*/
function dbscripts_locked($in_locked = NULL) {
static $locked = 0;
if (isset($in_locked)) $locked = $in_locked;
return $locked;
}
/**
* Dump the database
*
* @param $options
* An array containing various options for the merge. Most contain a configure_file, filter_option, branch_primary, branch_last_merge, branch_production
*/
function dbscripts_dump($options) {
$options = _dbscripts_get_options($options,'dump');
require($options['configure_file']);
extract($options); // any options should override ones set in configure files
// we do it this way so that if a configure file sets what it's corresponding reference is the corresponding reference will be included instead of the default.
if (!$reference_file) $reference_file = 'config.references.inc';
require($reference_file);
// Ensure required files are loaded
if (!isset($dump_path)) return dbscripts_errors('missing_config');
if (!isset($tables_referenced)) return dbscripts_errors('missing_config_references');
$db_connection_settings = _dbscripts_db_connect();
if (($error = dbscripts_errors())) return $error;
elseif (!$db_connection_settings) {
return dbscripts_errors('bad_database_connection');
}
// Define paths
$dump_location = "$dump_path/$branch_primary";
$lastmerge_location = "$dump_path/$branch_last_merge";
$temp_branch = "tmp";
$temp_location = "$dump_path/$temp_branch";
$workspace_branch = "workspace/last-dump";
$workspace_location = "$dump_path/$workspace_branch";
// Creating required folders
if (file_exists($temp_location) && exec("ls $temp_location")) exec("rm -rf $temp_location/*");
exec("mkdir -p $temp_location/data");
exec("mkdir -p $temp_location/tables");
if (!file_exists("$dump_location/data")) exec("mkdir -p $dump_location/data");
if (!file_exists("$dump_location/tables")) exec("mkdir -p $dump_location/tables");
$lastmerge_exists = FALSE;
if (file_exists("$lastmerge_location") && file_exists("$dump_location/table_list.txt") && $branch_primary != $branch_last_merge) {
$lastmerge_exists = TRUE;
}
// Set the filtering options and message to be presented to the user
$tables_cleared = array();
$fix_user_table = FALSE;
switch($filter_option){
case 'none':
$message = "Performed a full database dump to $branch_primary.";
break;
case 'min':
$tables_cleared = array_merge($tables_filtered, $tables_filtered_l1);
$message = "Dumped the database to $branch_primary with minimal filtering.";
break;
default:
$tables_cleared = array_merge($tables_filtered, $tables_filtered_l1, $tables_filtered_l2);
$fix_user_table = $lastmerge_exists ? TRUE : FALSE;
$message = "Dumped the database to $branch_primary with full filtering options.";
break;
}
// Create an array of all tables in the database and store it
exec("$mysqldump --add-drop-table --no-data $db_connection_settings | grep 'DROP TABLE' | sed -e \"s/DROP TABLE IF EXISTS .//g\" -e \"s/.;//g\" > $temp_location/table_list.txt");
$table_list = file("$temp_location/table_list.txt", FILE_IGNORE_NEW_LINES);
// These are all the special dump options that make the database diffable
// and preserve character set
$dump_options = "--skip-opt --add-drop-table --add-locks --create-options --quick --lock-tables --disable-keys --order-by-primary --skip-comments --comments=FALSE --set-charset --default-character-set=utf8 --character-sets-dir=$charsets --hex-blob";
// Some versions of MySQL do not set character encoding for column names
// which can cause unnessisary changes in the version control system
// Enable this in config.inc
$charset_filter = '';
if ($remove_column_charset) {
$charset_filter .= "| sed ";
$charset_filter .= "-e '/SET @saved_cs_client = @@character_set_client;/d' ";
$charset_filter .= "-e '/SET character_set_client = utf8;/d' ";
$charset_filter .= "-e '/SET character_set_client = @saved_cs_client;/d' ";
}
// Dump the structure of all tables
foreach ($table_list as $table) {
exec("$mysqldump $dump_options --no-data $db_connection_settings --tables $table $charset_filter > $temp_location/tables/$table.sql");
}
// Check that a file actually has data, and stop if it doesn't
if (file_get_contents("$temp_location/tables/{$table_list[0]}.sql") == '') {
exec("rm -r $temp_location/*");
return dbscripts_errors('empty_data');
}
// Remove all AUTO_INCREMENT values of the filtered tables
$tables_to_filter = _dbscripts_process_tables($temp_branch, $tables_cleared, FALSE);
foreach ($tables_to_filter as $table) {
$filtered_increment = dbscripts_get_table_increment($table, $temp_branch);
exec("sed 's/ AUTO_INCREMENT={$filtered_increment['num']}//g' $temp_location/tables/$table.sql > $temp_location/$table.sql");
exec("mv $temp_location/$table.sql $temp_location/tables/$table.sql");
}
// Find out which tables contain new data, and potentially new data
if ($branch_primary != $branch_last_merge && $lastmerge_exists) {
// Get all tables that have content that would need to be merged
$tables_to_merge = _dbscripts_process_tables($temp_branch, $tables_merge, FALSE);
// Find references for each table
foreach ($tables_to_merge as $table) {
// Get the current and lastmerge increments of the table
$increment = dbscripts_get_table_increment($table, $temp_branch);
$increment_lastmerge = dbscripts_get_table_increment($table, $branch_last_merge);
if (is_numeric($increment['num']) && !is_numeric($increment_lastmerge['num'])) {
$increment_lastmerge['num'] = '0';
}
// Continue only if there is a possibility of new data or a reference
if (isset($increment['num']) && isset($increment_lastmerge['num']) && $increment['num'] > $increment_lastmerge['num']) {
// Not error checking when finding references because it takes too long
$references = dbscripts_get_table_references($table, $workspace_branch, $filter_option, FALSE);
// Compare the primary keys of the referencing table with
// the foreign keys of the referenced table
if (is_array($references['references'])) {
foreach ($references['references'] as $referenced_table => $columns) {
// Don't continue if this table is production-only
if (!in_array($referenced_table, $tables_override)) {
$primary_keys = dbscripts_get_table_primary_keys($referenced_table, $branch_primary);
if (is_array($primary_keys)) {
foreach ($columns as $column) {
if (in_array($column, $primary_keys)) {
// Record the table/column pair along with the lastmerge increment value
$tables_with_new_data[$referenced_table][$column] = $increment_lastmerge['num'];
}
}
}
}
}
}
}
}
} // woa, thats a lot of end brackets in a row
// Get tables to be dumped by removing $tables_cleared from the list of all tables
$tables_dumped = _dbscripts_process_tables($temp_branch, $tables_cleared);
if (($error = dbscripts_errors())) return $error;
elseif (!is_array($tables_dumped)) {
return dbscripts_errors('unknown');
}
// Dump the data of all tables we're tracking
foreach ($tables_dumped as $table) {
if (isset($tables_with_new_data[$table])) {
// Create the where statements
$where_clause_new = '';
$where_clause_old = '';
$where_clause_new_data = array();
$where_clause_old_data = array();
foreach ($tables_with_new_data[$table] as $column => $increment) {
$where_clause_new_data[] = "$column>=$increment";
$where_clause_old_data[] = "$column<$increment";
}
// Where statement for new data
$where_clause_new = "--where='";
foreach ($where_clause_new_data as $key => $query) {
if ($key != 0) {
$where_clause_new .= " OR ";
}
$where_clause_new .= $query;
}
$where_clause_new .= "'";
// Where statement for old data
$where_clause_old .= "--where='";
foreach ($where_clause_old_data as $key => $query) {
if ($key != 0) {
$where_clause_old .= " AND ";
}
$where_clause_old .= $query;
}
$where_clause_old .= "'";
exec("$mysqldump $dump_options --no-create-info $db_connection_settings $where_clause_old --tables $table > $temp_location/data/$table.sql");
exec("$mysqldump $dump_options --no-create-info $db_connection_settings $where_clause_new --tables $table > $temp_location/data/$table-new.sql");
} else {
exec("$mysqldump $dump_options --no-create-info $db_connection_settings --tables $table > $temp_location/data/$table.sql");
}
// If there's no data, then delete the file
if (!exec("grep 'INSERT INTO' $temp_location/data/$table.sql")) {exec("rm $temp_location/data/$table.sql");}
if (file_exists("$temp_location/data/$table-new.sql")) {
if (!exec("grep 'INSERT INTO' $temp_location/data/$table-new.sql")) exec("rm $temp_location/data/$table-new.sql");
}
}
// Move the dump files to the working space's last dump
if (file_exists($workspace_location) && exec("ls $workspace_location")) exec("rm -rf $workspace_location/*");
if (!file_exists($workspace_location)) exec("mkdir -p $workspace_location");
exec("mv $temp_location/* $workspace_location");
// Fix the users table issue with conflicting timestamps
// Just use the last-merge timestamp
if ($fix_user_table) {
// Define paths
$dumped_version = "$workspace_location/data/users.sql";
$lastmerge_version = "$lastmerge_location/data/users.sql";
$dumped_converted_version = "$temp_location/users-dumped.txt";
$lastmerge_converted_version = "$temp_location/users-lastmerge.txt";
$rewritten_version = "$temp_location/users.csv";
$new_version = "$temp_location/users.sql";
// Columns to work with (minus 1 for arrays)
$columns = _dbscripts_get_table_columns('users',$branch_primary);
$override_column = array('access','login');
if (is_array($user_override_columns)) $override_column = array_merge($override_column, $user_override_columns); // let config add other columns to override
foreach($override_column as $r) {
$cols[$r] = array_search($r,$columns) +1;
}
// Create a converted version of the user table
exec("
grep 'INSERT INTO' $dumped_version \\
|sed -e 's/^INSERT INTO `users` VALUES (//g' -e 's/);$//g' \\
|sed -e 's/#/#PND#/g' -e \"s/\\\\\'/#SQ#/g\" -e \"s/\\\\\\\"/#DQ#/g\" \\
| awk -f $script_path/helpers/csv.awk -f $script_path/helpers/convert.awk \\
|sed -e 's/#CM#$//g' \\
> $dumped_converted_version
");
exec("
grep 'INSERT INTO' $lastmerge_version \\
|sed -e 's/^INSERT INTO `users` VALUES (//g' -e 's/);$//g' \\
|sed -e 's/#/#PND#/g' -e \"s/\\\\\'/#SQ#/g\" -e \"s/\\\\\\\"/#DQ#/g\" \\
| awk -f $script_path/helpers/csv.awk -f $script_path/helpers/convert.awk \\
|sed -e 's/#CM#$//g' \\
> $lastmerge_converted_version
");
// Convert to arrays
$dumped_converted_file = file("$dumped_converted_version", FILE_IGNORE_NEW_LINES);
$lastmerge_converted_file = file("$lastmerge_converted_version", FILE_IGNORE_NEW_LINES);
// Put the UID as the array key, with an array of columns
foreach ($dumped_converted_file as $line) {
$line_parts = explode('#CM#', $line);
$dumped_converted[$line_parts[0]] = $line_parts;
}
foreach ($lastmerge_converted_file as $line) {
$line_parts = explode('#CM#', $line);
$lastmerge_converted[$line_parts[0]] = $line_parts;
}
// Rewrite the timestamps
foreach ($dumped_converted as $uid => $columns) {
$rewritten_timestamps[$uid] = $columns;
foreach($cols as $pos) {
$rewritten_timestamps[$uid][$pos] = $lastmerge_converted[$uid][$pos];
}
}
// Write the rewritten version to file
foreach ($rewritten_timestamps as $columns) {
$line = '';
foreach ($columns as $key => $column) {
if ($key == 0) {
$line = $column;
} else {
$line .= ",$column";
}
}
exec("echo \"$line\" >> $rewritten_version");
}
// Convert the file back to SQL
// Get an array of the last-merge sql file
$sql = file("$lastmerge_version", FILE_IGNORE_NEW_LINES);
// Get the top sql comments
$data_start = '';
foreach ($sql as $key => $line) {
if (!$data_start) {
if (preg_match("/^INSERT INTO/", $line)) {
$data_start = $key;
} else {
$line = str_replace("'", "#SQ#", $line); // issues with quotes
if ($key == 0) {
exec("echo '$line' > $temp_location/top.sql");
} else {
exec("echo '$line' >> $temp_location/top.sql");
}
}
}
}
exec("sed \"s/#SQ#/\\'/g\" $temp_location/top.sql > $new_version"); // reverting quotes
// Insert the data
exec("
cat $rewritten_version \\
|sed -e \"s/#DQ#/\\\\\\\"/g\" -e \"s/#SQ#/\\\\\'/g\" -e 's/#PND#/#/g' \\
|sed -e 's/^/INSERT INTO `users` VALUES (/g' -e 's/$/);/g' \\
>> $new_version
");
// Insert the bottom sql comments
foreach ($sql as $key => $line) {
if ($key > $data_start && !preg_match("/^INSERT INTO/", $line)) {
$line = str_replace("'", "#SQ#", $line); // issues with quotes
exec("echo '$line' >> $temp_location/bottom.sql");
}
}
exec("sed \"s/#SQ#/\\'/g\" $temp_location/bottom.sql >> $new_version"); // reverting quotes
// Copy the results over to the new dump
exec("mv $new_version $dumped_version");
// Delete files that are no longer required
exec("rm $temp_location/top.sql $temp_location/bottom.sql $dumped_converted_version $lastmerge_converted_version $rewritten_version");
}
// For now we're just going to directly copy everything to $dump_location
// Eventually we'll actually perform a merge
// Erasing directory without erasing folders for svn support
if (exec("ls $dump_location/tables")) exec("rm $dump_location/tables/*");
if (exec("ls $dump_location/data")) exec("rm $dump_location/data/*");
exec("cp $workspace_location/table_list.txt $dump_location");
exec("cp $workspace_location/tables/* $dump_location/tables");
exec("cp $workspace_location/data/* $dump_location/data");
// Let the user know what happened
return "\n$message\n\n";
}
/**
* Erase the database
*
* @param $options
* Must contain filter_option and configure_file
* Choose what level of filtering should be performed while erasing the
* database. Filter levels are configured in config.inc. Any options set to
* be filtered will be subsequently PRESERVED in the database, and not
* erased.
* 'full' - Default option. Preserves the full option of data from the dump.
* Most useful for keeping user, sessions and cache data. Use this when
* erasing a development database.
* 'min' - Preserves only a select minimum of data from the dump. Most
* useful for keeping sessions data so you don't get logged out. Use
* this when erasing a production database.
* 'none' - NO filtering is performed whatsoever. The entire database will
* be erased.
*/
function dbscripts_erase($options) {
if (!$options['options_processed']) $options = _dbscripts_get_options($options,'erase');
require($options['configure_file']);
extract($options);
// Ensure required files are loaded
if (!isset($dump_path)) return dbscripts_errors('missing_config');
$db_connection_settings = _dbscripts_db_connect();
if (($error = dbscripts_errors())) return $error;
elseif (!$db_connection_settings) {
return dbscripts_errors('bad_database_connection');
}
// Set the filtering options and message to be presented to the user
$tables_preserved = array();
switch ($filter_option) {
case 'none';
$message = "Erased the entire database.";
break;
case 'min':
$tables_preserved = $tables_filtered_l1;
$message = "Erased the database, except for minimal preserved tables.";
break;
default:
$tables_preserved = array_merge($tables_filtered_l1,$tables_filtered_l2);
$message = "Erased the database, except for preserved tables.";
break;
}
$filter = '';
foreach($tables_preserved as $preserved_data) {
$filter .= "|grep -v 'DROP TABLE IF EXISTS .$preserved_data.;'";
}
// Dump options to make it easy to erase the database
$dump_options = "--add-drop-table --no-data";
// We'll dump the database, perform some changes to it, then pipe it back into
// MySQL so it will drop the given tables
exec("$mysqldump $dump_options $db_connection_settings | grep 'DROP TABLE' $filter | $mysql $db_connection_settings");
return "\n$message\n\n";
}
/**
* Restore the database
*
* @param $branch
* File the database should be restored from. Defaults to 'development'.
* Alternative options that are supported by default are 'production' and
* 'last-merge'. Other filename patterns may be used if you wish to restore
* the database from an alternate location.
* @param $filter_option
* Choose what level of filtering should be performed during the restoration.
* Filter levels are configured in config.inc
* 'full' - Default option. Preserves the full option of data currently
* residing within MySQL. Most useful for preserving user, sessions and
* cache data. Use this when restoring within a development environment.
* 'min' - Preserves only a select minimum of data currently residing within
* MySQL. Most useful for preserving sessions and cache data. Use this
* when restoring within a production environment.
* 'none' - NO filtering is performed whatsoever. The entire database is
* erased from MySQL and restored with the data from the given file.
*/
function dbscripts_restore($options) {
$options = _dbscripts_get_options($options,'restore');
require($options['configure_file']);
extract($options);
//create a pre-restore dump based on option from command line or setting in cofiguration file
if (($options['paranoia'] || $paranoia ) && !$options['not_paranoid']) {
$fake_options[1] = $options['paranoia']? $options['paranoia'] : $paranoia ;
dbscripts_dump($fake_options);
}
// Ensure required files are loaded
if (!isset($dump_path)) return dbscripts_errors('missing_config');
$db_connection_settings = _dbscripts_db_connect();
if (dbscripts_locked()) {
dbscripts_errors('locked');
}
elseif (($error = dbscripts_errors())) return $error;
elseif (!$db_connection_settings) {
return dbscripts_errors('bad_database_connection');
}
// Set locations
$dump_location = "$dump_path/$branch_primary";
$workspace_location = "$dump_path/workspace/last-restore";
// Check that the requested location exists
if (!file_exists($dump_location)) {
return dbscripts_errors('path_missing',array($dump_location));
}
if (!file_exists($workspace_location)) {
exec("mkdir -p $workspace_location");
}
// Set behavior depending on filter
$tables_preserved = array();
switch($filter_option){
case 'none':
$message = "Restored the full database";
break;
case 'min':
$tables_preserved = array_merge($tables_filtered_l1);
$message = "Restored the database perserving minimal tables";
break;
default:
$tables_preserved = array_merge($tables_filtered_l1,$tables_filtered_l2);
$message = "Restored the database preserving the full option of tables";
break;
}
// Erase the database so any tables that were removed stay removed
dbscripts_erase($options);
// Get a list of tables to restore by removing $tables_preserved from the list of all tables
$tables_restored = _dbscripts_process_tables($branch_primary, $tables_preserved);
if (($error = dbscripts_errors())) return $error;
elseif (!is_array($tables_restored)) {
return dbscripts_errors('restore_paths');
}
// Restore each database file
foreach ($tables_restored as $table) {
print $debugging ? "\nrestoring $table\n" : '';
if (file_exists("$dump_location/tables/$table.sql")) exec("$mysql $db_connection_settings < $dump_location/tables/$table.sql");
if (file_exists("$dump_location/data/$table.sql")) exec("$mysql $db_connection_settings < $dump_location/data/$table.sql");
if (file_exists("$dump_location/data/$table-new.sql")) exec("$mysql $db_connection_settings < $dump_location/data/$table-new.sql");
}
// Copy what was restored to the working space
// Careful to preserve directories for SVN support
if (exec("ls $workspace_location")) {exec("rm -r $workspace_location/*");}
exec("mkdir $workspace_location/tables $workspace_location/data");
exec("cp $dump_location/table_list.txt $workspace_location");
exec("cp $dump_location/data/* $workspace_location/data");
exec("cp $dump_location/tables/* $workspace_location/tables");
return "\n$message\n\n";
}
/**
* Merge databases
*
* You really only need to set the following parameters for expert use.
* Otherwise this function can be run with no options.
*
* @param $options
* An array containing various options for the merge. Most contain a configure_file.
*/
function dbscripts_merge($options) {
$options = _dbscripts_get_options($options,'merge');
require($options['configure_file']);
extract($options);
// Ensure required files are loaded
if (!isset($dump_path)) return dbscripts_errors('missing_config');
// Set all locations
$temp_location = "$dump_path/tmp";
$dev_location = "$dump_path/$branch_primary";
$lastmerge_location = "$dump_path/$branch_last_merge";
$prod_location = "$dump_path/$branch_production";
$merge_location = "$temp_location/merge";
$tmpdev_branch = "tmp/dev";
$tmpdev_location = "$dump_path/$tmpdev_branch";
$conflict_file = "$temp_location/conflict.txt";
// Ensure all the branches exist
$missing_branch = '';
if (!file_exists($dev_location)) $missing_branch .= $branch_primary.' ';
if (!file_exists($lastmerge_location)) $missing_branch .= $branch_last_merge.' ';
if (!file_exists($prod_location)) $missing_branch .= $branch_production.' ';
// Cancel merge if all branches do not exist
if ($missing_branch) {
return dbscripts_errors('missing_merge_files',array($missing_branch));
}
// Ensure tmp folder exists
if (!file_exists($temp_location)) exec("mkdir -p $temp_location");
//
// CONTINUE MERGE
//
// If a previous merge had a conflict, it'll be picked up and continued here
if ($continue) {
if (file_exists($conflict_file)) {
$conflicted_tables = file($conflict_file, FILE_IGNORE_NEW_LINES);
foreach ($conflicted_tables as $table) {
// Set the location of the merge files for existing and new data
$existing_version = "$merge_location/data/$table.sql";
$new_version = "$temp_location/$table.sql";
$temp_version = "$temp_location/$table-tmp.sql";
// Ensure the file exists
if (!file_exists($existing_version)) {
return dbscripts_errors('missing_merge_table',array($table));
}
// Ensure that the merge was actually resolved
$check_conflict = exec("grep '^<<<<<<<' $existing_version");
if ($check_conflict) {
return dbscripts_errors('still_conflicted',array($table));
}
// If there was any new data to this table, we'll have to merge the two
if (file_exists($new_version)) {
$sql = file("$existing_version", FILE_IGNORE_NEW_LINES);
// Get the top sql comments
$data_start = '';
foreach ($sql as $key => $line) {
if (!$data_start) {
if (preg_match("/^INSERT INTO/", $line)) {
$data_start = $key;
} else {
$line = str_replace("'", "#SQ#", $line); // issues with quotes
if ($key == 0) {
exec("echo '$line' > $temp_location/top.sql");
} else {
exec("echo '$line' >> $temp_location/top.sql");
}
}
}
}
exec("sed \"s/#SQ#/\\'/g\" $temp_location/top.sql > $temp_version"); // reverting quotes
// Insert the data
exec("grep '^INSERT INTO' $existing_version >> $temp_version");
exec("grep '^INSERT INTO' $new_version >> $temp_version");
// Insert the bottom sql comments
foreach ($sql as $key => $line) {
if ($key > $data_start && !preg_match("/^INSERT INTO/", $line)) {
$line = str_replace("'", "#SQ#", $line); // issues with quotes
exec("echo '$line' >> $temp_location/bottom.sql");
}
}
exec("sed \"s/#SQ#/\\'/g\" $temp_location/bottom.sql >> $temp_version"); // reverting quotes
// Copy the results over to where we're storing data
exec("mv $temp_version $existing_version");
// Delete files that are no longer required
exec("rm $temp_location/top.sql $temp_location/bottom.sql $new_version");
}
}
// Delete the conflict file
exec("rm $conflict_file");
} else {
return dbscripts_errors('missing_merge_file',array($conflict_file));
}
} else {
//
// NEW MERGE
//
// After a conflict, the temp files would still exist, so delete everything and start over
if (exec("ls $temp_location")) exec("rm -rf $temp_location/*");
// Creating merge folders
if (!file_exists($merge_location)) exec("mkdir -p $merge_location/tables $merge_location/data");
exec("cp -R $merge_location $tmpdev_location");
exec("cp $dev_location/table_list.txt $tmpdev_location");
exec("cp $dev_location/tables/* $tmpdev_location/tables");
exec("cp $dev_location/data/* $tmpdev_location/data");
// Define the tables, fail if they don't return arrays
$tables_content = _dbscripts_process_tables($branch_primary, $tables_merge, FALSE);
$tables_prod = _dbscripts_process_tables($branch_production, $tables_override, FALSE);
$tables_dev = _dbscripts_process_tables($branch_primary, array_merge($tables_merge, $tables_override));
if (($error = dbscripts_errors())) return $error;
// Raise all the increments of the content tables of development to above be production values
if ($raise_increments_on_merge) {
print "\nRaising increments of the '$branch_primary' branch ";
foreach ($tables_content as $table) {
print "."; // gheto status messages
// Find the last-merge value
$lastmerge_increment = dbscripts_get_table_increment($table, $branch_last_merge);
$start_at = $lastmerge_increment['num'];
// Find the production value
$production_increment = dbscripts_get_table_increment($table, $branch_production);
$change_to = $production_increment['num'];
if ($start_at < $change_to) {
// Raise the increments
$action = dbscripts_raise_table_increments($table, $start_at, $change_to, $tmpdev_branch);
if (!$action) {
return dbscripts_errors('missing_config');
}
}
}
print "\n"; // gheto status messages
}
// Move all tables to the temp merge location
foreach (array_merge($tables_dev, $tables_content, $tables_prod) as $table) {
if (file_exists("$tmpdev_location/tables/$table.sql")) {
$dev_increment = dbscripts_get_table_increment($table, $tmpdev_branch);
$prod_increment = dbscripts_get_table_increment($table, $branch_production);
if ($dev_increment['num'] >= $prod_increment) {
exec("cp $tmpdev_location/tables/$table.sql $merge_location/tables");
} else {
// If the production increment is higher than development, must rewrite increment
exec("sed 's/ AUTO_INCREMENT={$dev_increment['num']} / AUTO_INCREMENT={$prod_increment['num']} /g' $tmpdev_location/tables/$table.sql > $temp_location/$table.sql");
exec("mv $temp_location/$table.sql $merge_location/tables/$table.sql");
}
}
}
// Move the data files to be preserved wholly to the merge location
foreach ($tables_dev as $table) {
if (file_exists("$tmpdev_location/data/$table.sql")) exec("cp $tmpdev_location/data/$table.sql $merge_location/data");
}
foreach ($tables_prod as $table) {
if (file_exists("$prod_location/data/$table.sql")) exec("cp $prod_location/data/$table.sql $merge_location/data");
}
// DATA MERGING
// Merge the data from development into the production values
print "\nMerging content ";
$conflict = array();
exec("echo '' > $conflict_file");
foreach ($tables_content as $table) {
print "."; // gheto status messages
// Ensure there is actually some data to work with
$known_data_file = file_exists("$tmpdev_location/data/$table.sql") ? "$tmpdev_location/data/$table.sql" : (file_exists("$lastmerge_location/data/$table.sql") ? "$lastmerge_location/data/$table.sql" : (file_exists("$prod_location/data/$table.sql") ? "$prod_location/data/$table.sql" : FALSE));
$known_data_file = $known_data_file ? $known_data_file : (file_exists("$tmpdev_location/data/$table-new.sql") ? "$tmpdev_location/data/$table-new.sql" : (file_exists("$prod_location/data/$table-new.sql") ? "$prod_location/data/$table-new.sql" : FALSE));
// Set data paths
$blank_version = "$temp_location/blank.sql";
$dev_version = file_exists("$tmpdev_location/data/$table.sql") ? "$tmpdev_location/data/$table.sql" : $blank_version;
$lastmerge_version = file_exists("$lastmerge_location/data/$table.sql") ? "$lastmerge_location/data/$table.sql" : $blank_version;
$prod_version = file_exists("$prod_location/data/$table.sql") ? "$prod_location/data/$table.sql" : $blank_version;
$dev_version_new = file_exists("$tmpdev_location/data/$table-new.sql") ? "$tmpdev_location/data/$table-new.sql" : '';
$prod_version_new = file_exists("$prod_location/data/$table-new.sql") ? "$prod_location/data/$table-new.sql" : '';
$merge_version = "$merge_location/data/$table.sql";
$temp_version = "$temp_location/$table.sql";
// Only go through with the merge if there is any data to work with
if ($known_data_file || $dev_version_new || $prod_version_new) {
// Create a blank version for merge with diff3 purposes
exec("grep -v '^INSERT INTO' $known_data_file > $blank_version");
// Merge the existing data
exec("diff3 -E --merge $dev_version $lastmerge_version $prod_version > $merge_version");
$check_conflict = exec("grep '^<<<<<<<' $merge_version");
if ($check_conflict) {
$conflict[] = $table;
}
// Merge the new data
if (($dev_version_new || $prod_version_new)) {
$sql = file("$known_data_file", FILE_IGNORE_NEW_LINES);
// Get the top sql comments
$data_start = '';
foreach ($sql as $key => $line) {
if (!$data_start) {
if (preg_match("/^INSERT INTO/", $line)) {
$data_start = $key;
} else {
$line = str_replace("'", "#SQ#", $line); // issues with quotes
if ($key == 0) {
exec("echo '$line' > $temp_location/top.sql");
} else {
exec("echo '$line' >> $temp_location/top.sql");
}
}
}
}
exec("sed \"s/#SQ#/\\'/g\" $temp_location/top.sql > $temp_version"); // reverting quotes
// Insert the data
if (!in_array($table, $conflict) && file_exists($merge_version)) exec("grep '^INSERT INTO' $merge_version >> $temp_version");
if ($prod_version_new) exec("grep '^INSERT INTO' $prod_version_new >> $temp_version");
if ($dev_version_new) exec("grep '^INSERT INTO' $dev_version_new >> $temp_version");
// Insert the bottom sql comments
foreach ($sql as $key => $line) {
if ($key > $data_start && !preg_match("/^INSERT INTO/", $line)) {
$line = str_replace("'", "#SQ#", $line); // issues with quotes
exec("echo '$line' >> $temp_location/bottom.sql");
}
}
exec("sed \"s/#SQ#/\\'/g\" $temp_location/bottom.sql >> $temp_version"); // reverting quotes
// Delete temp files
exec("rm $temp_location/top.sql $temp_location/bottom.sql $blank_version");
// If there isn't a conflict with this table, then move it to the merge location
if (!in_array($table, $conflict)) {
exec("mv $temp_version $merge_version");
}
}
// Delete temp file
if (file_exists("$blank_version")) exec("rm $blank_version");
}
}
print "\n";
// If there were conflicts, fail
if (isset($conflict[0])) {
// Store the conflicted tables in a file
foreach ($conflict as $key => $table) {
if ($key > 0) {
exec("echo '$table' >> $conflict_file");
} else {
exec("echo '$table' > $conflict_file");
}
}
print "\nDON'T PANIC! But, I'm afraid I have to inform you that the following tables\nfailed to merge:\n\n";
print_r($conflict);
print "\nPlease correct the conflicts in '$merge_location/data' (look for '<<<<<<<').\n";
print "Afterwards, run '$script_path/merge.php continue' to finish the merge.\n\n";
return;
}
}
// MERGE COMPLETE
// Copy this new merged version to all three branches
// Deleting originals, while preserving original directories for svn support
exec("rm $dev_location/table_list.txt $lastmerge_location/table_list.txt $prod_location/table_list.txt");
exec("rm $dev_location/tables/* $lastmerge_location/tables/* $prod_location/tables/*");
exec("rm $dev_location/data/* $lastmerge_location/data/* $prod_location/data/*");
exec("cp $tmpdev_location/table_list.txt $merge_location");
// Copy new merge to development
exec("cp $merge_location/table_list.txt $dev_location");
exec("cp $merge_location/tables/* $dev_location/tables");
exec("cp $merge_location/data/* $dev_location/data");
// Copy new merge to last-merge
exec("cp $merge_location/table_list.txt $lastmerge_location");
exec("cp $merge_location/tables/* $lastmerge_location/tables");
exec("cp $merge_location/data/* $lastmerge_location/data");
// Copy new merge to production
exec("cp $merge_location/table_list.txt $prod_location");
exec("cp $merge_location/tables/* $prod_location/tables");
exec("cp $merge_location/data/* $prod_location/data");
// Dev and last-merge do not need to be bothered with all the data
$tables_cleared = _dbscripts_process_tables($tmpdev_branch, array_merge($tables_filtered, $tables_filtered_l1, $tables_filtered_l2), FALSE);
foreach ($tables_cleared as $table) {
// Erase the data file
if (file_exists("$dev_location/data/$table.sql")) exec("rm $dev_location/data/$table.sql");
if (file_exists("$lastmerge_location/data/$table.sql")) exec("rm $lastmerge_location/data/$table.sql");
// Copy over the dev version of the table
exec("cp $tmpdev_location/tables/$table.sql $dev_location/tables/$table.sql");
exec("cp $tmpdev_location/tables/$table.sql $lastmerge_location/tables/$table.sql");
}
// Clear temp
exec("rm -r $temp_location/*");
return "\nMerge was successfull.\n\n";
}
/**
* Raise the increments, and its foreign keys, of the given table within the
* given branch
*
* @param $table
* Table to raise the increments of
* @param $column
* Column to raise the increments of
* @param $start_at
* Range of increments within the table to start rewriting
* @param $change_to
* Range to change rewrite the increments to. Must be higher than both
* $start_at, and the table's current increment value. If it is not, then it
* will be recalculated to be the highest value.
* @param $branch
* Branch to make the changes on.
*/
function dbscripts_raise_table_increments($table, $start_at, $change_to, $branch = 'development', $filter_option = 'full') {
$options = _dbscripts_get_options();
require($options['configure_file']);
if (!$reference_file) $reference_file = 'config.references.inc';
require($reference_file);
// Ensure required files are loaded
if (!isset($dump_path)) return dbscripts_errors('missing_config');
if (!isset($tables_referenced)) return dbscripts_errors('missing_config_references');
// Set locations
$branch_location = "$dump_path/$branch";
$temp_location = "$dump_path/tmp";
// Ensure tmp directory exists
if (!file_exists($temp_location)) {
exec("mkdir -p $temp_location");
}
// Check if the branch exists, otherwise fail
if (!file_exists($branch_location)){
return dbscripts_errors('missing_branch',array($branch));
}
// Check if the table exists, otherwise fail
if (!file_exists("$branch_location/tables/$table.sql")) {
return dbscripts_errors('missing_table',array($table));
}
// Find all tables that use the increment as a foreign key
$table_references = dbscripts_get_table_references($table, $branch, $filter_option);
if (!is_array($table_references)) {
print "\n\nERROR: ".$table_references."\n\n";
return FALSE;
}
// Fail if there are any found possible references
if (array_key_exists('found', $table_references)) {
print "\n\nFAILED: Possible references found for table '$table'\n\n";
print_r($table_references['found']);
print "\nUpdate '$script_path/config.reference.inc' with this reference\n\n";
return FALSE;
}
// Add system path patterns as references
if (isset($system_paths[$table]['tables'])) {
foreach ($system_paths[$table]['tables'] as $system_path_table => $system_path_columns) {
foreach ($system_path_columns as $system_path_column) {
$table_references['references'][$system_path_table][] = $system_path_column;
}
}
}
// Find the largest increment value between $change_to and the current
// increment. Use the highest increment
$current_inc = dbscripts_get_table_increment($table, $branch);
if (is_array($current_inc) && $current_inc['num'] > $change_to) {
$change_to = $current_inc['num'];
}
// Get an array of the range of increments to work with
if ($start_at < $current_inc['num']) {
$increment_range = range($start_at, ($current_inc['num'] - 1));
} else {
// There is nothing to do then. Likely there are no new records.
return TRUE;
}
// Create a key=>value array of increment pairs
$increment_pairs = array();
$increment_change = $change_to;
foreach ($increment_range as $increment) {
$increment_pairs[$increment] = $increment_change;
$increment_change++;
}
// If there is a system paths reference, also add the pairs
$pattern_pair_old = array();
$pattern_pair_new = array();
$fuzzy_pattern_pair_old = array();
$fuzzy_pattern_pair_new = array();
if (isset($system_paths[$table])) {
// Exact patterns
if (array_key_exists('patterns', $system_paths[$table])) {
$i = 0;
foreach ($system_paths[$table]['patterns'] as $key => $pattern) {
foreach ($increment_pairs as $old_increment => $new_increment) {
$pattern_pair_old[$i] = str_replace('*', $old_increment, $pattern);
$pattern_pair_new[$i] = str_replace('*', $new_increment, $pattern);
$i++;
}
}
}
// Fuzzy patterns
if (array_key_exists('fuzzy', $system_paths[$table])) {
$i = 0;
foreach($system_paths[$table]['fuzzy'] as $key => $pattern) {
$pattern_parts = explode('#', $pattern);
$strlen_pattern = FALSE;
foreach ($pattern_parts as $part) {
if (strstr($part, 'NUMLEN+')) {
$strlen_pattern = $part;
}
}
$strlen = isset($strlen_pattern) ? str_replace('NUMLEN+', '', $strlen_pattern) : FALSE;
$pattern = str_replace(array('"', '\\'), array('#DQ#', '#BS#'), $pattern);
//$pattern = str_replace('\\', '#BS', $pattern);
foreach ($increment_pairs as $old_increment => $new_increment) {
$search = array();
$replace_old = array();
$replace_new = array();
$idlen_old = strlen($old_increment);
$idlen_new = strlen($new_increment);