File: mydumper.c

package info (click to toggle)
mydumper 0.6.1-1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 336 kB
  • ctags: 234
  • sloc: ansic: 2,362; makefile: 3; cpp: 3
file content (1853 lines) | stat: -rw-r--r-- 58,784 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
/*
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

	Authors: 	Domas Mituzas, Facebook ( domas at fb dot com )
			Mark Leith, Oracle Corporation (mark dot leith at oracle dot com)
			Andrew Hutchings, SkySQL (andrew at skysql dot com)
			Max Bubenick, Percona RDBA (max dot bubenick at percona dot com)
*/

#define _LARGEFILE64_SOURCE
#define _FILE_OFFSET_BITS 64

#include <mysql.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <glib.h>
#include <stdlib.h>
#include <stdarg.h>
#include <errno.h>
#include <time.h>
#include <zlib.h>
#include <pcre.h>
#include <signal.h>
#include <glib/gstdio.h>
#include "binlog.h"
#include "server_detect.h"
#include "common.h"
#include "g_unix_signal.h"
#include "config.h"
#include <math.h>

char *regexstring=NULL;

const char DIRECTORY[]= "export";
const char BINLOG_DIRECTORY[]= "binlog_snapshot";
const char DAEMON_BINLOGS[]= "binlogs";

static GMutex * init_mutex = NULL;

/* Program options */
gchar *output_directory= NULL;
guint statement_size= 1000000;
guint rows_per_file= 0;
guint chunk_filesize = 0;
int longquery= 60;
int build_empty_files= 0;
int skip_tz= 0;
int need_dummy_read= 0;
int compress_output= 0;
int killqueries= 0;
int detected_server= 0;
guint snapshot_interval= 60;
gboolean daemon_mode= FALSE;

gchar *ignore_engines= NULL;
char **ignore= NULL;

gchar *tables_list= NULL;
char **tables= NULL;

gboolean need_binlogs= FALSE;
gchar *binlog_directory= NULL;
gchar *daemon_binlog_directory= NULL;

gchar *logfile= NULL;
FILE *logoutfile= NULL;

gboolean no_schemas= FALSE;
gboolean no_locks= FALSE;
gboolean less_locking = FALSE;
gboolean use_savepoints = FALSE;
gboolean success_on_1146 = FALSE;

GList *innodb_tables= NULL;
GList *non_innodb_table= NULL;
GList *table_schemas= NULL;
gint non_innodb_table_counter= 0;
gint non_innodb_done= 0;
guint less_locking_threads = 0;

// For daemon mode, 0 or 1
guint dump_number= 0;
guint binlog_connect_id= 0;
gboolean shutdown_triggered= FALSE;
GAsyncQueue *start_scheduled_dump;
GMainLoop *m1;
static GCond * ll_cond = NULL; 
static GMutex * ll_mutex = NULL;

int errors;

static GOptionEntry entries[] =
{
	{ "database", 'B', 0, G_OPTION_ARG_STRING, &db, "Database to dump", NULL },
	{ "tables-list", 'T', 0, G_OPTION_ARG_STRING, &tables_list, "Comma delimited table list to dump (does not exclude regex option)", NULL },
	{ "outputdir", 'o', 0, G_OPTION_ARG_FILENAME, &output_directory, "Directory to output files to",  NULL },
	{ "statement-size", 's', 0, G_OPTION_ARG_INT, &statement_size, "Attempted size of INSERT statement in bytes, default 1000000", NULL},
	{ "rows", 'r', 0, G_OPTION_ARG_INT, &rows_per_file, "Try to split tables into chunks of this many rows. This option turns off --chunk-filesize", NULL},
	{ "chunk-filesize", 'F', 0, G_OPTION_ARG_INT, &chunk_filesize, "Split tables into chunks of this output file size. This value is in MB", NULL },
	{ "compress", 'c', 0, G_OPTION_ARG_NONE, &compress_output, "Compress output files", NULL},
	{ "build-empty-files", 'e', 0, G_OPTION_ARG_NONE, &build_empty_files, "Build dump files even if no data available from table", NULL},
	{ "regex", 'x', 0, G_OPTION_ARG_STRING, &regexstring, "Regular expression for 'db.table' matching", NULL},
	{ "ignore-engines", 'i', 0, G_OPTION_ARG_STRING, &ignore_engines, "Comma delimited list of storage engines to ignore", NULL },
	{ "no-schemas", 'm', 0, G_OPTION_ARG_NONE, &no_schemas, "Do not dump table schemas with the data", NULL },
	{ "no-locks", 'k', 0, G_OPTION_ARG_NONE, &no_locks, "Do not execute the temporary shared read lock.  WARNING: This will cause inconsistent backups", NULL },
	{ "less-locking", 0, 0, G_OPTION_ARG_NONE, &less_locking, "Minimize locking time on InnoDB tables.", NULL},
	{ "long-query-guard", 'l', 0, G_OPTION_ARG_INT, &longquery, "Set long query timer in seconds, default 60", NULL },
	{ "kill-long-queries", 'k', 0, G_OPTION_ARG_NONE, &killqueries, "Kill long running queries (instead of aborting)", NULL },
	{ "binlogs", 'b', 0, G_OPTION_ARG_NONE, &need_binlogs, "Get a snapshot of the binary logs as well as dump data",  NULL },
	{ "daemon", 'D', 0, G_OPTION_ARG_NONE, &daemon_mode, "Enable daemon mode", NULL },
	{ "snapshot-interval", 'I', 0, G_OPTION_ARG_INT, &snapshot_interval, "Interval between each dump snapshot (in minutes), requires --daemon, default 60", NULL },
	{ "logfile", 'L', 0, G_OPTION_ARG_FILENAME, &logfile, "Log file name to use, by default stdout is used", NULL },
	{ "tz-utc", 0, 0, G_OPTION_ARG_NONE, NULL, "SET TIME_ZONE='+00:00' at top of dump to allow dumping of TIMESTAMP data when a server has data in different time zones or data is being moved between servers with different time zones, defaults to on use --skip-tz-utc to disable.", NULL },
	{ "skip-tz-utc", 0, 0, G_OPTION_ARG_NONE, &skip_tz, "", NULL },
	{ "use-savepoints", 0, 0, G_OPTION_ARG_NONE, &use_savepoints, "Use savepoints to reduce metadata locking issues, needs SUPER privilege", NULL },
	{ "success-on-1146", 0, 0, G_OPTION_ARG_NONE, &success_on_1146, "Not increment error count and Warning instead of Critical in case of table doesn't exist", NULL},
	{ NULL, 0, 0, G_OPTION_ARG_NONE,   NULL, NULL, NULL }
};

struct tm tval;

void dump_schema_data(MYSQL *conn, char *database, char *table, char *filename);
void dump_schema(char *database, char *table, struct configuration *conf);
void dump_table(MYSQL *conn, char *database, char *table, struct configuration *conf, gboolean is_innodb);
void dump_tables(MYSQL *, GList *, struct configuration *);
guint64 dump_table_data(MYSQL *, FILE *, char *, char *, char *, char *);
void dump_database(MYSQL *, char *);
GList * get_chunks_for_table(MYSQL *, char *, char*,  struct configuration *conf);
guint64 estimate_count(MYSQL *conn, char *database, char *table, char *field, char *from, char *to);
void dump_table_data_file(MYSQL *conn, char *database, char *table, char *where, char *filename);
void create_backup_dir(char *directory);
gboolean write_data(FILE *,GString*);
gboolean check_regex(char *database, char *table);
void no_log(const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data);
void set_verbose(guint verbosity);
MYSQL *reconnect_for_binlog(MYSQL *thrconn);
void start_dump(MYSQL *conn);
MYSQL *create_main_connection();
void *binlog_thread(void *data);
void *exec_thread(void *data);
void write_log_file(const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data);

void no_log(const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data) {
	(void) log_domain;
	(void) log_level;
	(void) message;
	(void) user_data;
}

void set_verbose(guint verbosity) {
	if (logfile) {
		logoutfile = g_fopen(logfile, "w");
		if (!logoutfile) {
			g_critical("Could not open log file '%s' for writing: %d", logfile, errno);
			exit(EXIT_FAILURE);
		}
	}

	switch (verbosity) {
		case 0:
			g_log_set_handler(NULL, (GLogLevelFlags)(G_LOG_LEVEL_MASK), no_log, NULL);
			break;
		case 1:
			g_log_set_handler(NULL, (GLogLevelFlags)(G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE), no_log, NULL);
			if (logfile)
				g_log_set_handler(NULL, (GLogLevelFlags)(G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL), write_log_file, NULL);
			break;
		case 2:
			g_log_set_handler(NULL, (GLogLevelFlags)(G_LOG_LEVEL_MESSAGE), no_log, NULL);
			if (logfile)
				g_log_set_handler(NULL, (GLogLevelFlags)(G_LOG_LEVEL_WARNING | G_LOG_LEVEL_ERROR | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL), write_log_file, NULL);
			break;
		default:
			if (logfile)
				g_log_set_handler(NULL, (GLogLevelFlags)(G_LOG_LEVEL_MASK), write_log_file, NULL);
			break;
	}
}

gboolean sig_triggered(gpointer user_data) {
	(void) user_data;

	g_message("Shutting down gracefully");
	shutdown_triggered= TRUE;
	g_main_loop_quit(m1);
	return FALSE;
}

void clear_dump_directory()
{
	GError *error= NULL;
	char* dump_directory= g_strdup_printf("%s/%d", output_directory, dump_number);
	GDir* dir= g_dir_open(dump_directory, 0, &error);

	if (error) {
		g_critical("cannot open directory %s, %s\n", dump_directory, error->message);
		errors++;
		return;
	}

	const gchar* filename= NULL;

	while((filename= g_dir_read_name(dir))) {
		gchar* path= g_build_filename(dump_directory, filename, NULL);
		if (g_unlink(path) == -1) {
			g_critical("error removing file %s (%d)\n", path, errno);
			errors++;
			return;
		}
		g_free(path);
	}

	g_dir_close(dir);
	g_free(dump_directory);
}

gboolean run_snapshot(gpointer *data)
{
	(void) data;

	g_async_queue_push(start_scheduled_dump,GINT_TO_POINTER(1));

	return (shutdown_triggered) ? FALSE : TRUE;
}

/* Check database.table string against regular expression */

gboolean check_regex(char *database, char *table) {
	/* This is not going to be used in threads */
	static pcre *re = NULL;
	int rc;
	int ovector[9]= {0};
	const char *error;
	int erroroffset;

	char *p;

	/* Let's compile the RE before we do anything */
	if (!re) {
		re = pcre_compile(regexstring,PCRE_CASELESS|PCRE_MULTILINE,&error,&erroroffset,NULL);
		if(!re) {
			g_critical("Regular expression fail: %s", error);
			exit(EXIT_FAILURE);
		}
	}

	p=g_strdup_printf("%s.%s",database,table);
	rc = pcre_exec(re,NULL,p,strlen(p),0,0,ovector,9);
	g_free(p);

	return (rc>0)?TRUE:FALSE;
}

/* Write some stuff we know about snapshot, before it changes */
void write_snapshot_info(MYSQL *conn, FILE *file) {
	MYSQL_RES *master=NULL, *slave=NULL;
	MYSQL_FIELD *fields;
	MYSQL_ROW row;

	char *masterlog=NULL;
	char *masterpos=NULL;

	char *slavehost=NULL;
	char *slavelog=NULL;
	char *slavepos=NULL;

	mysql_query(conn,"SHOW MASTER STATUS");
	master=mysql_store_result(conn);
	if (master && (row=mysql_fetch_row(master))) {
		masterlog=row[0];
		masterpos=row[1];
	}

	mysql_query(conn, "SHOW SLAVE STATUS");
	slave=mysql_store_result(conn);
	guint i;
	if (slave && (row=mysql_fetch_row(slave))) {
		fields=mysql_fetch_fields(slave);
		for (i=0; i<mysql_num_fields(slave);i++) {
			if (!strcasecmp("exec_master_log_pos",fields[i].name)) {
				slavepos=row[i];
			} else if (!strcasecmp("relay_master_log_file", fields[i].name)) {
				slavelog=row[i];
			} else if (!strcasecmp("master_host",fields[i].name)) {
				slavehost=row[i];
			}
		}
	}

	if (masterlog) {
		fprintf(file, "SHOW MASTER STATUS:\n\tLog: %s\n\tPos: %s\n\n", masterlog, masterpos);
		g_message("Written master status");
	}

	if (slavehost) {
		fprintf(file, "SHOW SLAVE STATUS:\n\tHost: %s\n\tLog: %s\n\tPos: %s\n\n",
			slavehost, slavelog, slavepos);
		g_message("Written slave status");
	}

	fflush(file);
	if (master)
		mysql_free_result(master);
	if (slave)
		mysql_free_result(slave);
}

void *process_queue(struct thread_data *td) {
	struct configuration *conf= td->conf;
	// mysql_init is not thread safe, especially in Connector/C
	g_mutex_lock(init_mutex);
	MYSQL *thrconn = mysql_init(NULL);
	g_mutex_unlock(init_mutex);
	
	mysql_options(thrconn,MYSQL_READ_DEFAULT_GROUP,"mydumper");

	if (compress_protocol)
		mysql_options(thrconn,MYSQL_OPT_COMPRESS,NULL);

	if (!mysql_real_connect(thrconn, hostname, username, password, NULL, port, socket_path, 0)) {
		g_critical("Failed to connect to database: %s", mysql_error(thrconn));
		exit(EXIT_FAILURE);
	} else {
		g_message("Thread %d connected using MySQL connection ID %lu", td->thread_id, mysql_thread_id(thrconn));
	}
	
	if(use_savepoints && mysql_query(thrconn, "SET SQL_LOG_BIN = 0")){
		g_critical("Failed to disable binlog for the thread: %s",mysql_error(thrconn));
		exit(EXIT_FAILURE);
	}
	if ((detected_server == SERVER_TYPE_MYSQL) && mysql_query(thrconn, "SET SESSION wait_timeout = 2147483")){
		g_warning("Failed to increase wait_timeout: %s", mysql_error(thrconn));
	}
	if (mysql_query(thrconn, "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ")) {
		g_warning("Failed to set isolation level: %s", mysql_error(thrconn));
	}
	if (mysql_query(thrconn, "START TRANSACTION /*!40108 WITH CONSISTENT SNAPSHOT */")) {
		g_critical("Failed to start consistent snapshot: %s",mysql_error(thrconn));
		errors++;
	}
	if(!skip_tz && mysql_query(thrconn, "/*!40103 SET TIME_ZONE='+00:00' */")){
		g_critical("Failed to set time zone: %s",mysql_error(thrconn));
	}

	/* Unfortunately version before 4.1.8 did not support consistent snapshot transaction starts, so we cheat */
	if (need_dummy_read) {
		mysql_query(thrconn,"SELECT /*!40001 SQL_NO_CACHE */ * FROM mysql.mydumperdummy");
		MYSQL_RES *res=mysql_store_result(thrconn);
		if (res)
			mysql_free_result(res);
	}
	mysql_query(thrconn, "/*!40101 SET NAMES binary*/");

	g_async_queue_push(conf->ready,GINT_TO_POINTER(1));

	struct job* job= NULL;
	struct table_job* tj= NULL;
	struct schema_job* sj= NULL;
	struct binlog_job* bj= NULL;
	
	/* if less locking we need to wait until that threads finish
	    progressively waking up this threads */
	if(less_locking){
		g_mutex_lock(ll_mutex);
		
		while (less_locking_threads >= td->thread_id) {
			g_cond_wait (ll_cond, ll_mutex);
		}
		
		g_mutex_unlock(ll_mutex);
	}
		
	for(;;) {
		
		GTimeVal tv;
		g_get_current_time(&tv);
		g_time_val_add(&tv,1000*1000*1);
		job=(struct job *)g_async_queue_pop(conf->queue);
		if (shutdown_triggered && (job->type != JOB_SHUTDOWN)) {
			continue;
		}

		switch (job->type) {
			case JOB_DUMP:
				tj=(struct table_job *)job->job_data;
				if (tj->where)
					g_message("Thread %d dumping data for `%s`.`%s` where %s", td->thread_id, tj->database, tj->table, tj->where);
				else
					g_message("Thread %d dumping data for `%s`.`%s`", td->thread_id, tj->database, tj->table);
				if(use_savepoints && mysql_query(thrconn, "SAVEPOINT mydumper")){
					g_critical("Savepoint failed: %s",mysql_error(thrconn));
				}
				dump_table_data_file(thrconn, tj->database, tj->table, tj->where, tj->filename);
				if(use_savepoints && mysql_query(thrconn, "ROLLBACK TO SAVEPOINT mydumper")){
					g_critical("Rollback to savepoint failed: %s",mysql_error(thrconn));
				}
				if(tj->database) g_free(tj->database);
				if(tj->table) g_free(tj->table);
				if(tj->where) g_free(tj->where);
				if(tj->filename) g_free(tj->filename);
				g_free(tj);
				g_free(job);
				break;
			case JOB_DUMP_NON_INNODB:
				tj=(struct table_job *)job->job_data;
				if (tj->where)
					g_message("Thread %d dumping data for `%s`.`%s` where %s", td->thread_id, tj->database, tj->table, tj->where);
				else
					g_message("Thread %d dumping data for `%s`.`%s`", td->thread_id, tj->database, tj->table);
				if(use_savepoints && mysql_query(thrconn, "SAVEPOINT mydumper")){
					g_critical("Savepoint failed: %s",mysql_error(thrconn));
				}
				dump_table_data_file(thrconn, tj->database, tj->table, tj->where, tj->filename);
				if(use_savepoints && mysql_query(thrconn, "ROLLBACK TO SAVEPOINT mydumper")){
					g_critical("Rollback to savepoint failed: %s",mysql_error(thrconn));
				}
				if(tj->database) g_free(tj->database);
				if(tj->table) g_free(tj->table);
				if(tj->where) g_free(tj->where);
				if(tj->filename) g_free(tj->filename);
				g_free(tj);
				g_free(job);
				if (g_atomic_int_dec_and_test(&non_innodb_table_counter) && g_atomic_int_get(&non_innodb_done)) {
					g_async_queue_push(conf->unlock_tables, GINT_TO_POINTER(1));
				}
				break;
			case JOB_SCHEMA:
				sj=(struct schema_job *)job->job_data;
				g_message("Thread %d dumping schema for `%s`.`%s`", td->thread_id, sj->database, sj->table);
				dump_schema_data(thrconn, sj->database, sj->table, sj->filename);
				if(sj->database) g_free(sj->database);
				if(sj->table) g_free(sj->table);
				if(sj->filename) g_free(sj->filename);
				g_free(sj);
				g_free(job);
				break;
			case JOB_BINLOG:
				thrconn= reconnect_for_binlog(thrconn);
				g_message("Thread %d connected using MySQL connection ID %lu (in binlog mode)", td->thread_id, mysql_thread_id(thrconn));
				bj=(struct binlog_job *)job->job_data;
				g_message("Thread %d dumping binary log file %s", td->thread_id, bj->filename);
				get_binlog_file(thrconn, bj->filename, binlog_directory, bj->start_position, bj->stop_position, FALSE);
				if(bj->filename)
					g_free(bj->filename);
				g_free(bj);
				g_free(job);
				break;
			case JOB_SHUTDOWN:
				g_message("Thread %d shutting down", td->thread_id);
				if (thrconn)
					mysql_close(thrconn);
				g_free(job);
				mysql_thread_end();
				return NULL;
				break;
			default:
				g_critical("Something very bad happened!");
				exit(EXIT_FAILURE);
		}
	}
	if (thrconn)
		mysql_close(thrconn);
	mysql_thread_end();
	return NULL;
}

void *process_queue_less_locking(struct thread_data *td) {
	struct configuration *conf= td->conf;
	// mysql_init is not thread safe, especially in Connector/C
	g_mutex_lock(init_mutex);
	MYSQL *thrconn = mysql_init(NULL);
	g_mutex_unlock(init_mutex);
	
	mysql_options(thrconn,MYSQL_READ_DEFAULT_GROUP,"mydumper");

	if (compress_protocol)
		mysql_options(thrconn,MYSQL_OPT_COMPRESS,NULL);

	if (!mysql_real_connect(thrconn, hostname, username, password, NULL, port, socket_path, 0)) {
		g_critical("Failed to connect to database: %s", mysql_error(thrconn));
		exit(EXIT_FAILURE);
	} else {
		g_message("Thread %d connected using MySQL connection ID %lu", td->thread_id, mysql_thread_id(thrconn));
	}

	if ((detected_server == SERVER_TYPE_MYSQL) && mysql_query(thrconn, "SET SESSION wait_timeout = 2147483")){
		g_warning("Failed to increase wait_timeout: %s", mysql_error(thrconn));
	}
	if(!skip_tz && mysql_query(thrconn, "/*!40103 SET TIME_ZONE='+00:00' */")){
		g_critical("Failed to set time zone: %s",mysql_error(thrconn));
	}
	mysql_query(thrconn, "/*!40101 SET NAMES binary*/");

	g_async_queue_push(conf->ready_less_locking,GINT_TO_POINTER(1));

	struct job* job= NULL;
	struct table_job* tj= NULL;
	struct tables_job* mj=NULL;
	struct schema_job* sj= NULL;
	GList* glj;
	int first = 1;
	GString *query= g_string_sized_new(1024);
	GString *prev_table = g_string_sized_new(100);
	GString *prev_database = g_string_sized_new(100);
	
	for(;;) {
		GTimeVal tv;
		g_get_current_time(&tv);
		g_time_val_add(&tv,1000*1000*1);
		job=(struct job *)g_async_queue_pop(conf->queue_less_locking);
		if (shutdown_triggered && (job->type != JOB_SHUTDOWN)) {
			continue;
		}

		switch (job->type) {
			case JOB_LOCK_DUMP_NON_INNODB:
				mj=(struct tables_job *)job->job_data;
				glj = g_list_copy(mj->table_job_list);
				for (glj= g_list_first(glj); glj; glj= g_list_next(glj)) {
					tj = (struct table_job *)glj->data;
					if(first){
						g_string_printf(query, "LOCK TABLES `%s`.`%s` READ LOCAL",tj->database,tj->table);
						first = 0;
					}else{
						if(g_ascii_strcasecmp(prev_database->str, tj->database) || g_ascii_strcasecmp(prev_table->str, tj->table)){
							g_string_append_printf(query, ", `%s`.`%s` READ LOCAL",tj->database,tj->table);
						}
					}
					g_string_printf(prev_table, "%s", tj->table);
					g_string_printf(prev_database, "%s", tj->database);
				}
				first = 1;
				if(mysql_query(thrconn,query->str)){
					g_critical("Non Innodb lock tables fail: %s", mysql_error(thrconn));
					exit(EXIT_FAILURE);
				}
				if (g_atomic_int_dec_and_test(&non_innodb_table_counter) && g_atomic_int_get(&non_innodb_done)) {
					g_async_queue_push(conf->unlock_tables, GINT_TO_POINTER(1));
				}
				for (mj->table_job_list= g_list_first(mj->table_job_list); mj->table_job_list; mj->table_job_list= g_list_next(mj->table_job_list)) {
					tj = (struct table_job *)mj->table_job_list->data;
					if (tj->where)
						g_message("Thread %d dumping data for `%s`.`%s` where %s", td->thread_id, tj->database, tj->table, tj->where);
					else
						g_message("Thread %d dumping data for `%s`.`%s`", td->thread_id, tj->database, tj->table);
					dump_table_data_file(thrconn, tj->database, tj->table, tj->where, tj->filename);
					if(tj->database) g_free(tj->database);
					if(tj->table) g_free(tj->table);
					if(tj->where) g_free(tj->where);
					if(tj->filename) g_free(tj->filename);
					g_free(tj);
				}
				mysql_query(thrconn, "UNLOCK TABLES /* Non Innodb */");
				g_free(g_list_first(mj->table_job_list));
				g_free(mj);
				g_free(job);
				break;
			case JOB_SCHEMA:
				sj=(struct schema_job *)job->job_data;
				g_message("Thread %d dumping schema for `%s`.`%s`", td->thread_id, sj->database, sj->table);
				dump_schema_data(thrconn, sj->database, sj->table, sj->filename);
				if(sj->database) g_free(sj->database);
				if(sj->table) g_free(sj->table);
				if(sj->filename) g_free(sj->filename);
				g_free(sj);
				g_free(job);
				break;
			case JOB_SHUTDOWN:
				g_message("Thread %d shutting down", td->thread_id);
				g_mutex_lock(ll_mutex);
				less_locking_threads--;
				g_cond_broadcast(ll_cond);
				g_mutex_unlock(ll_mutex);
				if (thrconn)
					mysql_close(thrconn);
				g_free(job);
				mysql_thread_end();
				return NULL;
				break;
			default:
				g_critical("Something very bad happened!");
				exit(EXIT_FAILURE);
		}
	}
	if (thrconn)
		mysql_close(thrconn);
	mysql_thread_end();
	return NULL;
}

MYSQL *reconnect_for_binlog(MYSQL *thrconn) {
	if (thrconn) {
		mysql_close(thrconn);
	}
	g_mutex_lock(init_mutex);
	thrconn= mysql_init(NULL);
	g_mutex_unlock(init_mutex);

	if (compress_protocol)
		mysql_options(thrconn,MYSQL_OPT_COMPRESS,NULL);

	int timeout= 1;
	mysql_options(thrconn, MYSQL_OPT_READ_TIMEOUT, (const char*)&timeout);

	if (!mysql_real_connect(thrconn, hostname, username, password, NULL, port, socket_path, 0)) {
		g_critical("Failed to re-connect to database: %s", mysql_error(thrconn));
		exit(EXIT_FAILURE);
	}
	return thrconn;
}

int main(int argc, char *argv[])
{
	GError *error = NULL;
	GOptionContext *context;

	g_thread_init(NULL);

	init_mutex = g_mutex_new();
	ll_mutex = g_mutex_new();
	ll_cond = g_cond_new();

	context = g_option_context_new("multi-threaded MySQL dumping");
	GOptionGroup *main_group= g_option_group_new("main", "Main Options", "Main Options", NULL, NULL);
	g_option_group_add_entries(main_group, entries);
	g_option_group_add_entries(main_group, common_entries);
	g_option_context_set_main_group(context, main_group);
	if (!g_option_context_parse(context, &argc, &argv, &error)) {
		g_print ("option parsing failed: %s, try --help\n", error->message);
		exit (EXIT_FAILURE);
	}
	g_option_context_free(context);

	if (program_version) {
		g_print("mydumper %s, built against MySQL %s\n", VERSION, MYSQL_SERVER_VERSION);
		exit (EXIT_SUCCESS);
	}

	set_verbose(verbose);

	time_t t;
	time(&t);localtime_r(&t,&tval);
	
	//rows chunks have precedence over chunk_filesize 
	if (rows_per_file > 0 && chunk_filesize > 0){
		chunk_filesize = 0;
		g_warning("--chunk-filesize disabled by --rows option");
	}
	
	//until we have an unique option on lock types we need to ensure this
	if(no_locks)
		less_locking = 0;
	
	/* savepoints workaround to avoid metadata locking issues 
	   doesnt work for chuncks */
	if(rows_per_file && use_savepoints){
		use_savepoints = FALSE;
		g_warning("--use-savepoints disabled by --rows");
	}
	
	if (!output_directory)
		output_directory = g_strdup_printf("%s-%04d%02d%02d-%02d%02d%02d",DIRECTORY,
			tval.tm_year+1900, tval.tm_mon+1, tval.tm_mday,
			tval.tm_hour, tval.tm_min, tval.tm_sec);

	create_backup_dir(output_directory);
	if (daemon_mode) {
		pid_t pid, sid;

		pid= fork();
		if (pid < 0)
			exit(EXIT_FAILURE);
		else if (pid > 0)
			exit(EXIT_SUCCESS);

		umask(0);
		sid= setsid();

		if (sid < 0)
			exit(EXIT_FAILURE);

		char *dump_directory= g_strdup_printf("%s/0", output_directory);
		create_backup_dir(dump_directory);
		g_free(dump_directory);
		dump_directory= g_strdup_printf("%s/1", output_directory);
		create_backup_dir(dump_directory);
		g_free(dump_directory);
		daemon_binlog_directory= g_strdup_printf("%s/%s", output_directory, DAEMON_BINLOGS);
		create_backup_dir(daemon_binlog_directory);
	}

	if (need_binlogs) {
		binlog_directory = g_strdup_printf("%s/%s", output_directory, BINLOG_DIRECTORY);
		create_backup_dir(binlog_directory);
	}

	/* Give ourselves an array of engines to ignore */
	if (ignore_engines)
		ignore = g_strsplit(ignore_engines, ",", 0);

	/* Give ourselves an array of tables to dump */
	if (tables_list)
		tables = g_strsplit(tables_list, ",", 0);

	if (daemon_mode) {
		GError* terror;

		GThread *bthread= g_thread_create(binlog_thread, GINT_TO_POINTER(1), FALSE, &terror);
		if (bthread == NULL) {
			g_critical("Could not create binlog thread: %s", terror->message);
			g_error_free(terror);
			exit(EXIT_FAILURE);
		}

		start_scheduled_dump= g_async_queue_new();
		GThread *ethread= g_thread_create(exec_thread, GINT_TO_POINTER(1), FALSE, &terror);
		if (ethread == NULL) {
			g_critical("Could not create exec thread: %s", terror->message);
			g_error_free(terror);
			exit(EXIT_FAILURE);
		}
		// Run initial snapshot
		run_snapshot(NULL);
		#if GLIB_MINOR_VERSION < 14
		g_timeout_add(snapshot_interval*60*1000, (GSourceFunc) run_snapshot, NULL);
		#else
		g_timeout_add_seconds(snapshot_interval*60, (GSourceFunc) run_snapshot, NULL);
		#endif
		guint sigsource= g_unix_signal_add(SIGINT, sig_triggered, NULL);
		sigsource= g_unix_signal_add(SIGTERM, sig_triggered, NULL);
		m1= g_main_loop_new(NULL, TRUE);
		g_main_loop_run(m1);
		g_source_remove(sigsource);
	} else {
		MYSQL *conn= create_main_connection();
		start_dump(conn);
	}

	sleep(5);
	mysql_thread_end();
	mysql_library_end();
	g_free(output_directory);
	g_strfreev(ignore);
	g_strfreev(tables);

	if (logoutfile) {
		fclose(logoutfile);
	}

	exit(errors ? EXIT_FAILURE : EXIT_SUCCESS);
}

MYSQL *create_main_connection()
{
	MYSQL *conn;
	conn = mysql_init(NULL);
	mysql_options(conn,MYSQL_READ_DEFAULT_GROUP,"mydumper");

	if (!mysql_real_connect(conn, hostname, username, password, db, port, socket_path, 0)) {
		g_critical("Error connecting to database: %s", mysql_error(conn));
		exit(EXIT_FAILURE);
	}

	detected_server= detect_server(conn);

	if ((detected_server == SERVER_TYPE_MYSQL) && mysql_query(conn, "SET SESSION wait_timeout = 2147483")){
		g_warning("Failed to increase wait_timeout: %s", mysql_error(conn));
	}
	if ((detected_server == SERVER_TYPE_MYSQL) && mysql_query(conn, "SET SESSION net_write_timeout = 2147483")){
		g_warning("Failed to increase net_write_timeout: %s", mysql_error(conn));
	}

	switch (detected_server) {
		case SERVER_TYPE_MYSQL:
			g_message("Connected to a MySQL server");
			break;
		case SERVER_TYPE_DRIZZLE:
			g_message("Connected to a Drizzle server");
			break;
		default:
			g_critical("Cannot detect server type");
			exit(EXIT_FAILURE);
			break;
	}

	return conn;
}

void *exec_thread(void *data) {
	(void) data;

	while(1) {
		g_async_queue_pop(start_scheduled_dump);
		clear_dump_directory();
		MYSQL *conn= create_main_connection();
		start_dump(conn);
		mysql_close(conn);
		mysql_thread_end();

		// Don't switch the symlink on shutdown because the dump is probably incomplete.
		if (!shutdown_triggered) {
			const char *dump_symlink_source= (dump_number == 0) ? "0" : "1";
			char *dump_symlink_dest= g_strdup_printf("%s/last_dump", output_directory);

			// We don't care if this fails
			g_unlink(dump_symlink_dest);

			if (symlink(dump_symlink_source, dump_symlink_dest) == -1) {
				g_critical("error setting last good dump symlink %s, %d", dump_symlink_dest, errno);
			}
			g_free(dump_symlink_dest);

			dump_number= (dump_number == 1) ? 0 : 1;
		}
	}
	return NULL;
}

void *binlog_thread(void *data) {
	(void) data;
	MYSQL_RES *master= NULL;
	MYSQL_ROW row;
	MYSQL *conn;
	conn = mysql_init(NULL);
	mysql_options(conn,MYSQL_READ_DEFAULT_GROUP,"mydumper");

	if (!mysql_real_connect(conn, hostname, username, password, db, port, socket_path, 0)) {
		g_critical("Error connecting to database: %s", mysql_error(conn));
		exit(EXIT_FAILURE);
	}

	mysql_query(conn,"SHOW MASTER STATUS");
	master= mysql_store_result(conn);
	if (master && (row= mysql_fetch_row(master))) {
		MYSQL *binlog_connection= NULL;
		binlog_connection= reconnect_for_binlog(binlog_connection);
		binlog_connect_id= mysql_thread_id(binlog_connection);
		guint64 start_position= g_ascii_strtoull(row[1], NULL, 10);
		gchar* filename= g_strdup(row[0]);
		mysql_free_result(master);
		mysql_close(conn);
		g_message("Continuous binlog thread connected using MySQL connection ID %lu", mysql_thread_id(binlog_connection));
		get_binlog_file(binlog_connection, filename, daemon_binlog_directory, start_position, 0, TRUE);
		g_free(filename);
		mysql_close(binlog_connection);
	} else {
		mysql_free_result(master);
		mysql_close(conn);
	}
	g_message("Continuous binlog thread shutdown");
	mysql_thread_end();
	return NULL;
}

void start_dump(MYSQL *conn)
{
	struct configuration conf = { 1, NULL, NULL, NULL, NULL, NULL, NULL, 0 };
	char *p;
	char *p2;
	char *p3;
	guint64 nits[num_threads];
	GList* nitl[num_threads];
	int tn = 0;
	guint64 min = 0;
	time_t t;
	struct db_table *dbt;
	guint n;
	
	for(n=0;n<num_threads;n++){
		nits[n] = 0;
		nitl[n] = NULL;
	}
	
	if (daemon_mode)
		p= g_strdup_printf("%s/%d/metadata.partial", output_directory, dump_number);
	else
		p= g_strdup_printf("%s/metadata.partial", output_directory);
	p2 = g_strndup(p, (unsigned)strlen(p)-8);

	FILE* mdfile=g_fopen(p,"w");
	if(!mdfile) {
		g_critical("Couldn't write metadata file (%d)",errno);
		exit(EXIT_FAILURE);
	}

	/* We check SHOW PROCESSLIST, and if there're queries
	   larger than preset value, we terminate the process.

	   This avoids stalling whole server with flush */

	if (mysql_query(conn, "SHOW PROCESSLIST")) {
		g_warning("Could not check PROCESSLIST, no long query guard enabled: %s", mysql_error(conn));
	} else {
		MYSQL_RES *res = mysql_store_result(conn);
		MYSQL_ROW row;

		/* Just in case PROCESSLIST output column order changes */
		MYSQL_FIELD *fields = mysql_fetch_fields(res);
		guint i;
		int tcol=-1, ccol=-1, icol=-1;
		for(i=0; i<mysql_num_fields(res); i++) {
			if (!strcasecmp(fields[i].name,"Command")) ccol=i;
			else if (!strcasecmp(fields[i].name,"Time")) tcol=i;
			else if (!strcasecmp(fields[i].name,"Id")) icol=i;
		}
		if ((tcol < 0) || (ccol < 0) || (icol < 0)) {
			g_critical("Error obtaining information from processlist");
			exit(EXIT_FAILURE);
		}
		while ((row=mysql_fetch_row(res))) {
			if (row[ccol] && strcmp(row[ccol],"Query"))
				continue;
			if (row[tcol] && atoi(row[tcol])>longquery) {
				if (killqueries) {
					if (mysql_query(conn,p3=g_strdup_printf("KILL %lu",atol(row[icol]))))
						g_warning("Could not KILL slow query: %s",mysql_error(conn));
					else
						g_warning("Killed a query that was running for %ss",row[tcol]);
					g_free(p3);
				} else {
					g_critical("There are queries in PROCESSLIST running longer than %us, aborting dump,\n\t"
						"use --long-query-guard to change the guard value, kill queries (--kill-long-queries) or use \n\tdifferent server for dump", longquery);
					exit(EXIT_FAILURE);
				}
			}
		}
		mysql_free_result(res);
	}

	if (!no_locks) {
		if (mysql_query(conn, "FLUSH TABLES WITH READ LOCK")) {
			g_critical("Couldn't acquire global lock, snapshots will not be consistent: %s",mysql_error(conn));
			errors++;
		}
	} else {
		g_warning("Executing in no-locks mode, snapshot will notbe consistent");
	}
	if (mysql_get_server_version(conn) < 40108) {
		mysql_query(conn, "CREATE TABLE IF NOT EXISTS mysql.mydumperdummy (a INT) ENGINE=INNODB");
		need_dummy_read=1;
	}
	mysql_query(conn, "START TRANSACTION /*!40108 WITH CONSISTENT SNAPSHOT */");
	if (need_dummy_read) {
		mysql_query(conn,"SELECT /*!40001 SQL_NO_CACHE */ * FROM mysql.mydumperdummy");
		MYSQL_RES *res=mysql_store_result(conn);
		if (res)
			mysql_free_result(res);
	}
	time(&t); localtime_r(&t,&tval);
	fprintf(mdfile,"Started dump at: %04d-%02d-%02d %02d:%02d:%02d\n",
		tval.tm_year+1900, tval.tm_mon+1, tval.tm_mday,
		tval.tm_hour, tval.tm_min, tval.tm_sec);

	g_message("Started dump at: %04d-%02d-%02d %02d:%02d:%02d\n",
		tval.tm_year+1900, tval.tm_mon+1, tval.tm_mday,
		tval.tm_hour, tval.tm_min, tval.tm_sec);

	if (detected_server == SERVER_TYPE_MYSQL) {
		mysql_query(conn, "/*!40101 SET NAMES binary*/");

		write_snapshot_info(conn, mdfile);
	}
	
	GThread **threads = g_new(GThread*,num_threads*(less_locking+1));
	struct thread_data *td= g_new(struct thread_data, num_threads*(less_locking+1));
	
	if(less_locking){
		conf.queue_less_locking = g_async_queue_new();
		conf.ready_less_locking = g_async_queue_new();
		less_locking_threads = num_threads;
		for (n=num_threads; n<num_threads*2; n++) {
			td[n].conf= &conf;
			td[n].thread_id= n+1;
			threads[n] = g_thread_create((GThreadFunc)process_queue_less_locking,&td[n],TRUE,NULL);
			g_async_queue_pop(conf.ready_less_locking);
		}
		g_async_queue_unref(conf.ready_less_locking);
	}

	conf.queue = g_async_queue_new();
	conf.ready = g_async_queue_new();
	conf.unlock_tables= g_async_queue_new();
	
	for (n=0; n<num_threads; n++) {
		td[n].conf= &conf;
		td[n].thread_id= n+1;
		threads[n] = g_thread_create((GThreadFunc)process_queue,&td[n],TRUE,NULL);
		g_async_queue_pop(conf.ready);
	}
	
	g_async_queue_unref(conf.ready);
	
	if (db) {
		dump_database(conn, db);
	} else {
		MYSQL_RES *databases;
		MYSQL_ROW row;
		if(mysql_query(conn,"SHOW DATABASES") || !(databases = mysql_store_result(conn))) {
			g_critical("Unable to list databases: %s",mysql_error(conn));
			exit(EXIT_FAILURE);
		}

		while ((row=mysql_fetch_row(databases))) {
			if (!strcasecmp(row[0],"information_schema") || !strcasecmp(row[0], "performance_schema") || (!strcasecmp(row[0], "data_dictionary")))
				continue;
			dump_database(conn, row[0]);
		}
		mysql_free_result(databases);

	}
	
	if (!non_innodb_table){
		g_async_queue_push(conf.unlock_tables, GINT_TO_POINTER(1));
	}
	
	if (less_locking) {

		for (non_innodb_table= g_list_first(non_innodb_table); non_innodb_table; non_innodb_table= g_list_next(non_innodb_table)) {
			dbt= (struct db_table*) non_innodb_table->data;
			tn = 0;
			min = nits[0];
			for (n=1; n<num_threads; n++) {
				if(nits[n] < min){
					min = nits[n];
					tn = n;
				}
			}
			nitl[tn]= g_list_append(nitl[tn], dbt);
			nits[tn] += dbt->datalength;
		}
		
		for (n=0; n<num_threads; n++) {
			if(nits[n] > 0){
				g_atomic_int_inc(&non_innodb_table_counter);
				dump_tables(conn, nitl[n], &conf);
			}
		}
		g_list_free(g_list_first(non_innodb_table));

		
		g_atomic_int_inc(&non_innodb_done);
		
		for (n=0; n<num_threads; n++) {
			struct job *j = g_new0(struct job,1);
			j->type = JOB_SHUTDOWN;
			g_async_queue_push(conf.queue_less_locking,j);
		}
	}else{
		for (non_innodb_table= g_list_first(non_innodb_table); non_innodb_table; non_innodb_table= g_list_next(non_innodb_table)) {
			dbt= (struct db_table*) non_innodb_table->data;
			dump_table(conn, dbt->database, dbt->table, &conf, FALSE);
			g_atomic_int_inc(&non_innodb_table_counter);
		}
		g_list_free(g_list_first(non_innodb_table));
		g_atomic_int_inc(&non_innodb_done);
	}
	
	for (innodb_tables= g_list_first(innodb_tables); innodb_tables; innodb_tables= g_list_next(innodb_tables)) {
		dbt= (struct db_table*) innodb_tables->data;
		dump_table(conn, dbt->database, dbt->table, &conf, TRUE);
	}
	g_list_free(g_list_first(innodb_tables));

	for (table_schemas= g_list_first(table_schemas); table_schemas; table_schemas= g_list_next(table_schemas)) {
		dbt= (struct db_table*) table_schemas->data;
		dump_schema(dbt->database, dbt->table, &conf);
		g_free(dbt->table);
		g_free(dbt->database);
		g_free(dbt);
	}
	g_list_free(g_list_first(table_schemas));

	if (!no_locks) {
		g_async_queue_pop(conf.unlock_tables);
		g_message("Non-InnoDB dump complete, unlocking tables");
		mysql_query(conn, "UNLOCK TABLES /* FTWRL */");
	}
	
	if (need_binlogs) {
		get_binlogs(conn, &conf);
	}
	
	// close main connection 
	mysql_close(conn);
	
	if(less_locking){
		for (n=num_threads; n<num_threads*2; n++) {
			g_thread_join(threads[n]);
		}
		g_async_queue_unref(conf.queue_less_locking);
	}
	
	for (n=0; n<num_threads; n++) {
		struct job *j = g_new0(struct job,1);
		j->type = JOB_SHUTDOWN;
		g_async_queue_push(conf.queue,j);
	}

	for (n=0; n<num_threads; n++) {
		g_thread_join(threads[n]);
	}
	g_async_queue_unref(conf.queue);

	time(&t);localtime_r(&t,&tval);
	fprintf(mdfile,"Finished dump at: %04d-%02d-%02d %02d:%02d:%02d\n",
		tval.tm_year+1900, tval.tm_mon+1, tval.tm_mday,
		tval.tm_hour, tval.tm_min, tval.tm_sec);
	fclose(mdfile);
	g_rename(p, p2);
	g_free(p);
	g_free(p2);
	g_message("Finished dump at: %04d-%02d-%02d %02d:%02d:%02d\n",
		tval.tm_year+1900, tval.tm_mon+1, tval.tm_mday,
		tval.tm_hour, tval.tm_min, tval.tm_sec);

	g_free(td);
	g_free(threads);
}

/* Heuristic chunks building - based on estimates, produces list of ranges for datadumping
   WORK IN PROGRESS
*/
GList * get_chunks_for_table(MYSQL *conn, char *database, char *table, struct configuration *conf) {

	GList *chunks = NULL;
	MYSQL_RES *indexes=NULL, *minmax=NULL, *total=NULL;
	MYSQL_ROW row;
	char *field = NULL;
	int showed_nulls=0;

	/* first have to pick index, in future should be able to preset in configuration too */
	gchar *query = g_strdup_printf("SHOW INDEX FROM `%s`.`%s`",database,table);
	mysql_query(conn,query);
	g_free(query);
	indexes=mysql_store_result(conn);

	while ((row=mysql_fetch_row(indexes))) {
		if (!strcmp(row[2],"PRIMARY") && (!strcmp(row[3],"1"))) {
			/* Pick first column in PK, cardinality doesn't matter */
			field=row[4];
			break;
		}
	}

	/* If no PK found, try using first UNIQUE index */
	if (!field) {
		mysql_data_seek(indexes,0);
		while ((row=mysql_fetch_row(indexes))) {
			if(!strcmp(row[1],"0") && (!strcmp(row[3],"1"))) {
				/* Again, first column of any unique index */
				field=row[4];
				break;
			}
		}
	}

	/* Still unlucky? Pick any high-cardinality index */
	if (!field && conf->use_any_index) {
		guint64 max_cardinality=0;
		guint64 cardinality=0;

		mysql_data_seek(indexes,0);
		while ((row=mysql_fetch_row(indexes))) {
			if(!strcmp(row[3],"1")) {
				if (row[6])
					cardinality = strtoll(row[6],NULL,10);
				if (cardinality>max_cardinality) {
					field=row[4];
					max_cardinality=cardinality;
				}
			}
		}
	}
	/* Oh well, no chunks today - no suitable index */
	if (!field) goto cleanup;

	/* Get minimum/maximum */
	mysql_query(conn, query=g_strdup_printf("SELECT %s MIN(`%s`),MAX(`%s`) FROM `%s`.`%s`", (detected_server == SERVER_TYPE_MYSQL) ? "/*!40001 SQL_NO_CACHE */" : "", field, field, database, table));
	g_free(query);
	minmax=mysql_store_result(conn);

	if (!minmax)
		goto cleanup;

	row=mysql_fetch_row(minmax);
	MYSQL_FIELD * fields=mysql_fetch_fields(minmax);
	char *min=row[0];
	char *max=row[1];

	/* Got total number of rows, skip chunk logic if estimates are low */
	guint64 rows = estimate_count(conn, database, table, field, NULL, NULL);
	if (rows <= rows_per_file)
		goto cleanup;

	/* This is estimate, not to use as guarantee! Every chunk would have eventual adjustments */
	guint64 estimated_chunks = rows / rows_per_file;
	guint64 estimated_step, nmin, nmax, cutoff;

	/* Support just bigger INTs for now, very dumb, no verify approach */
	switch (fields[0].type) {
		case MYSQL_TYPE_LONG:
		case MYSQL_TYPE_LONGLONG:
		case MYSQL_TYPE_INT24:
			/* static stepping */
			nmin = strtoll(min,NULL,10);
			nmax = strtoll(max,NULL,10);
			estimated_step = (nmax-nmin)/estimated_chunks+1;
			cutoff = nmin;
			while(cutoff<=nmax) {
				chunks=g_list_append(chunks,g_strdup_printf("%s%s%s%s(`%s` >= %llu AND `%s` < %llu)",
						!showed_nulls?"`":"",
						!showed_nulls?field:"",
						!showed_nulls?"`":"",
						!showed_nulls?" IS NULL OR ":"",
						field, (unsigned long long)cutoff,
						field, (unsigned long long)(cutoff+estimated_step)));
				cutoff+=estimated_step;
				showed_nulls=1;
			}

		default:
			goto cleanup;
	}


cleanup:
	if (indexes)
		mysql_free_result(indexes);
	if (minmax)
		mysql_free_result(minmax);
	if (total)
		mysql_free_result(total);
	return chunks;
}

/* Try to get EXPLAIN'ed estimates of row in resultset */
guint64 estimate_count(MYSQL *conn, char *database, char *table, char *field, char *from, char *to) {
	char *querybase, *query;
	int ret;

	g_assert(conn && database && table);

	querybase = g_strdup_printf("EXPLAIN SELECT `%s` FROM `%s`.`%s`", (field?field:"*"), database, table);
	if (from || to) {
		g_assert(field != NULL);
		char *fromclause=NULL, *toclause=NULL;
		char *escaped;
		if (from) {
			escaped=g_new(char,strlen(from)*2+1);
			mysql_real_escape_string(conn,escaped,from,strlen(from));
			fromclause = g_strdup_printf(" `%s` >= \"%s\" ", field, escaped);
			g_free(escaped);
		}
		if (to) {
			escaped=g_new(char,strlen(to)*2+1);
			mysql_real_escape_string(conn,escaped,from,strlen(from));
			toclause = g_strdup_printf( " `%s` <= \"%s\"", field, escaped);
			g_free(escaped);
		}
		query = g_strdup_printf("%s WHERE `%s` %s %s", querybase, (from?fromclause:""), ((from&&to)?"AND":""), (to?toclause:""));

		if (toclause) g_free(toclause);
		if (fromclause) g_free(fromclause);
		ret=mysql_query(conn,query);
		g_free(querybase);
		g_free(query);
	} else {
		ret=mysql_query(conn,querybase);
		g_free(querybase);
	}

	if (ret) {
		g_warning("Unable to get estimates for %s.%s: %s",database,table,mysql_error(conn));
	}

	MYSQL_RES * result = mysql_store_result(conn);
	MYSQL_FIELD * fields = mysql_fetch_fields(result);

	guint i;
	for (i=0; i<mysql_num_fields(result); i++)  {
		if (!strcmp(fields[i].name,"rows"))
			break;
	}

	MYSQL_ROW row = NULL;

	guint64 count=0;

	if (result)
		row = mysql_fetch_row(result);

	if (row && row[i])
		count=strtoll(row[i],NULL,10);

	if (result)
		mysql_free_result(result);

	return(count);
}

void create_backup_dir(char *new_directory) {
	if (g_mkdir(new_directory, 0700) == -1)
	{
		if (errno != EEXIST)
		{
			g_critical("Unable to create `%s': %s",
				new_directory,
				g_strerror(errno));
			exit(EXIT_FAILURE);
		}
	}
}

void dump_database(MYSQL * conn, char *database) {

	char *query;
	mysql_select_db(conn,database);
	if (detected_server == SERVER_TYPE_MYSQL)
		query= g_strdup("SHOW TABLE STATUS");
	else
		query= g_strdup_printf("SELECT TABLE_NAME, ENGINE, TABLE_TYPE as COMMENT FROM DATA_DICTIONARY.TABLES WHERE TABLE_SCHEMA='%s'", database);

	if (mysql_query(conn, (query))) {
		g_critical("Error: DB: %s - Could not execute query: %s", database, mysql_error(conn));
		errors++;
		return;
	}

	g_free(query);

	MYSQL_RES *result = mysql_store_result(conn);
	MYSQL_FIELD *fields= mysql_fetch_fields(result);
	guint i;
	int ecol= -1, ccol= -1;
	for (i=0; i<mysql_num_fields(result); i++) {
		if (!strcasecmp(fields[i].name, "Engine")) ecol= i;
		else if (!strcasecmp(fields[i].name, "Comment")) ccol= i;
	}

	if (!result) {
		g_critical("Could not list tables for %s: %s", database, mysql_error(conn));
		errors++;
		return;
	}

	MYSQL_ROW row;
	while ((row = mysql_fetch_row(result))) {

		int dump=1;

		/* We no care about views!
			num_fields>1 kicks in only in case of 5.0 SHOW FULL TABLES or SHOW TABLE STATUS
			row[1] == NULL if it is a view in 5.0 'SHOW TABLE STATUS'
			row[1] == "VIEW" if it is a view in 5.0 'SHOW FULL TABLES'
		*/
		if ((detected_server == SERVER_TYPE_MYSQL) && ( row[ccol] == NULL || !strcmp(row[ccol],"VIEW") ))
			continue;

		/* Skip ignored engines, handy for avoiding Merge, Federated or Blackhole :-) dumps */
		if (ignore) {
			for (i = 0; ignore[i] != NULL; i++) {
				if (g_ascii_strcasecmp(ignore[i], row[ecol]) == 0) {
					dump = 0;
					break;
				}
			}
		}
		if (!dump)
			continue;

		/* In case of table-list option is enabled, check if table is part of the list */
		if (tables) {
			int table_found=0;
			for (i = 0; tables[i] != NULL; i++)
				if (g_ascii_strcasecmp(tables[i], row[0]) == 0)
					table_found = 1;

			if (!table_found)
				dump = 0;
		}
		if (!dump)
			continue;
		
		/* Special tables */
		if(g_ascii_strcasecmp(database, "mysql") == 0 && (g_ascii_strcasecmp(row[0], "general_log") == 0 || g_ascii_strcasecmp(row[0], "slow_log") == 0)){
			dump=0;
			continue;
		}

		/* Checks PCRE expressions on 'database.table' string */
		if (regexstring && !check_regex(database,row[0]))
			continue;

		/* Green light! */
		struct db_table *dbt = g_new(struct db_table, 1);
		dbt->database= g_strdup(database);
		dbt->table= g_strdup(row[0]);
		dbt->datalength = g_ascii_strtoull(row[6], NULL, 10);
		if (!g_ascii_strcasecmp("InnoDB", row[ecol])) {
			innodb_tables= g_list_append(innodb_tables, dbt);

		} else {
			non_innodb_table= g_list_append(non_innodb_table, dbt);
		}
	        if (!no_schemas) {
			table_schemas= g_list_append(table_schemas, dbt);
        	}
	}
	mysql_free_result(result);
}

void dump_schema_data(MYSQL *conn, char *database, char *table, char *filename) {
	void *outfile;
	char *query = NULL;
	MYSQL_RES *result = NULL;
	MYSQL_ROW row;

	if (!compress_output)
		outfile= g_fopen(filename, "w");
	else
		outfile= (void*) gzopen(filename, "w");

	if (!outfile) {
		g_critical("Error: DB: %s Could not create output file %s (%d)", database, filename, errno);
		errors++;
		return;
	}
        GString* statement = g_string_sized_new(statement_size);

	if (detected_server == SERVER_TYPE_MYSQL) {
		g_string_printf(statement,"/*!40101 SET NAMES binary*/;\n");
		g_string_append(statement,"/*!40014 SET FOREIGN_KEY_CHECKS=0*/;\n\n");
	} else {
		g_string_printf(statement, "SET FOREIGN_KEY_CHECKS=0;\n");
	}

	if (!write_data((FILE *)outfile,statement)) {
		g_critical("Could not write schema data for %s.%s", database, table);
		errors++;
		return;
	}

	query= g_strdup_printf("SHOW CREATE TABLE `%s`.`%s`", database, table);
	if (mysql_query(conn, query) || !(result= mysql_use_result(conn))) {
		if(success_on_1146 && mysql_errno(conn) == 1146){
			g_warning("Error dumping schemas (%s.%s): %s", database, table, mysql_error(conn));
		}else{
			g_critical("Error dumping schemas (%s.%s): %s", database, table, mysql_error(conn));
			errors++;
		}
		g_free(query);
		return;
	}


	g_string_set_size(statement, 0);

	/* There should never be more than one row */
	row = mysql_fetch_row(result);
	g_string_append(statement, row[1]);
	g_string_append(statement, ";\n");
	if (!write_data((FILE *)outfile, statement)) {
		g_critical("Could not write schema for %s.%s", database, table);
		errors++;
	}
	g_free(query);

        if (!compress_output)
                fclose((FILE *)outfile);
        else
                gzclose((gzFile)outfile);


	g_string_free(statement, TRUE);
	if (result)
		mysql_free_result(result);

	return;
}

void dump_table_data_file(MYSQL *conn, char *database, char *table, char *where, char *filename) {
	void *outfile;

	if (!compress_output)
		outfile = g_fopen(filename, "w");
	else
		outfile = (void*) gzopen(filename, "w");

	if (!outfile) {
		g_critical("Error: DB: %s TABLE: %s Could not create output file %s (%d)", database, table, filename, errno);
		errors++;
		return;
	}
	guint64 rows_count = dump_table_data(conn, (FILE *)outfile, database, table, where, filename);
	
	if (!rows_count)
		g_message("Empty table %s.%s", database,table);
}

void dump_schema(char *database, char *table, struct configuration *conf) {
	struct job *j = g_new0(struct job,1);
	struct schema_job *sj = g_new0(struct schema_job,1);
	j->job_data=(void*) sj;
	sj->database=g_strdup(database);
	sj->table=g_strdup(table);
	j->conf=conf;
	j->type=JOB_SCHEMA;
	if (daemon_mode)
		sj->filename = g_strdup_printf("%s/%d/%s.%s-schema.sql%s", output_directory, dump_number, database, table, (compress_output?".gz":""));
	else
		sj->filename = g_strdup_printf("%s/%s.%s-schema.sql%s", output_directory, database, table, (compress_output?".gz":""));
	g_async_queue_push(conf->queue,j);
	return;
}

void dump_table(MYSQL *conn, char *database, char *table, struct configuration *conf, gboolean is_innodb) {

	GList * chunks = NULL;
	if (rows_per_file)
		chunks = get_chunks_for_table(conn, database, table, conf);


	if (chunks) {
		int nchunk=0;
		for (chunks = g_list_first(chunks); chunks; chunks=g_list_next(chunks)) {
			struct job *j = g_new0(struct job,1);
			struct table_job *tj = g_new0(struct table_job,1);
			j->job_data=(void*) tj;
			tj->database=g_strdup(database);
			tj->table=g_strdup(table);
			j->conf=conf;
			j->type= is_innodb ? JOB_DUMP : JOB_DUMP_NON_INNODB;
			if (daemon_mode)
				tj->filename=g_strdup_printf("%s/%d/%s.%s.%05d.sql%s", output_directory, dump_number, database, table, nchunk,(compress_output?".gz":""));
			else
				tj->filename=g_strdup_printf("%s/%s.%s.%05d.sql%s", output_directory, database, table, nchunk,(compress_output?".gz":""));
			tj->where=(char *)chunks->data;
			g_async_queue_push(conf->queue,j);
			nchunk++;
		}
		g_list_free(g_list_first(chunks));
	} else {
		struct job *j = g_new0(struct job,1);
		struct table_job *tj = g_new0(struct table_job,1);
		j->job_data=(void*) tj;
		tj->database=g_strdup(database);
		tj->table=g_strdup(table);
		j->conf=conf;
		j->type= is_innodb ? JOB_DUMP : JOB_DUMP_NON_INNODB;
		if (daemon_mode)
			tj->filename = g_strdup_printf("%s/%d/%s.%s%s.sql%s", output_directory, dump_number, database, table,(chunk_filesize?".00001":""),(compress_output?".gz":""));
		else
			tj->filename = g_strdup_printf("%s/%s.%s%s.sql%s", output_directory, database, table,(chunk_filesize?".00001":""),(compress_output?".gz":""));
		g_async_queue_push(conf->queue,j);
		return;
	}
}

void dump_tables(MYSQL *conn, GList *noninnodb_tables_list, struct configuration *conf){
	struct db_table* dbt;
	GList * chunks = NULL;

	struct job *j = g_new0(struct job,1);
	struct tables_job *tjs = g_new0(struct tables_job,1);
	j->conf=conf;
	j->type=JOB_LOCK_DUMP_NON_INNODB;
	j->job_data=(void*) tjs;

	for (noninnodb_tables_list= g_list_first(noninnodb_tables_list); noninnodb_tables_list; noninnodb_tables_list= g_list_next(noninnodb_tables_list)) {
		dbt = (struct db_table*) noninnodb_tables_list->data;

		if (rows_per_file)
			chunks = get_chunks_for_table(conn, dbt->database, dbt->table, conf);

		if(chunks){
			int nchunk=0;
			for (chunks = g_list_first(chunks); chunks; chunks=g_list_next(chunks)) {
				struct table_job *tj = g_new0(struct table_job,1);
				tj->database = g_strdup_printf("%s",dbt->database);
				tj->table = g_strdup_printf("%s",dbt->table);
				if (daemon_mode)
					tj->filename=g_strdup_printf("%s/%d/%s.%s.%05d.sql%s", output_directory, dump_number, dbt->database, dbt->table, nchunk,(compress_output?".gz":""));
				else
					tj->filename=g_strdup_printf("%s/%s.%s.%05d.sql%s", output_directory, dbt->database, dbt->table, nchunk,(compress_output?".gz":""));
				tj->where=(char *)chunks->data;
				tjs->table_job_list= g_list_append(tjs->table_job_list, tj);
				nchunk++;
			}
		}else{
			struct table_job *tj = g_new0(struct table_job,1);
			tj->database = g_strdup_printf("%s",dbt->database);
			tj->table = g_strdup_printf("%s",dbt->table);
			if (daemon_mode)
				tj->filename = g_strdup_printf("%s/%d/%s.%s%s.sql%s", output_directory, dump_number, dbt->database, dbt->table,(chunk_filesize?".00001":""),(compress_output?".gz":""));
			else
				tj->filename = g_strdup_printf("%s/%s.%s%s.sql%s", output_directory, dbt->database, dbt->table,(chunk_filesize?".00001":""),(compress_output?".gz":""));
			tj->where = NULL;
			tjs->table_job_list= g_list_append(tjs->table_job_list, tj);
		}
	}
	g_async_queue_push(conf->queue_less_locking,j);
}

/* Do actual data chunk reading/writing magic */
guint64 dump_table_data(MYSQL * conn, FILE *file, char *database, char *table, char *where, char *filename)
{
	guint i;
	guint fn = 1;
	guint st_in_file = 0;
	guint num_fields = 0;
	guint64 num_rows = 0;
	guint64 num_rows_st = 0;
	MYSQL_RES *result = NULL;
	char *query = NULL;
	gchar *fcfile = NULL;
	gchar* filename_prefix = NULL;
	
	fcfile = g_strdup (filename);
	
	if(chunk_filesize){
		gchar** split_filename= g_strsplit(filename, ".00001.sql", 0);
		filename_prefix= split_filename[0];
		g_free(split_filename);
	}

	
	/* Ghm, not sure if this should be statement_size - but default isn't too big for now */
	GString* statement = g_string_sized_new(statement_size);
	GString* statement_row = g_string_sized_new(0);
	
	/* Poor man's database code */
 	query = g_strdup_printf("SELECT %s * FROM `%s`.`%s` %s %s", (detected_server == SERVER_TYPE_MYSQL) ? "/*!40001 SQL_NO_CACHE */" : "", database, table, where?"WHERE":"",where?where:"");
	if (mysql_query(conn, query) || !(result=mysql_use_result(conn))) {
		//ERROR 1146 
		if(success_on_1146 && mysql_errno(conn) == 1146){
			g_warning("Error dumping table (%s.%s) data: %s ",database, table, mysql_error(conn));
		}else{
			g_critical("Error dumping table (%s.%s) data: %s ",database, table, mysql_error(conn));
			errors++;
		}
		g_free(query);
		return num_rows;
	}

	num_fields = mysql_num_fields(result);
	MYSQL_FIELD *fields = mysql_fetch_fields(result);

	/* Buffer for escaping field values */
	GString *escaped = g_string_sized_new(3000);

	MYSQL_ROW row;

	g_string_set_size(statement,0);

	/* Poor man's data dump code */
	while ((row = mysql_fetch_row(result))) {
		gulong *lengths = mysql_fetch_lengths(result);
		num_rows++;

		if (!statement->len){
			if(!st_in_file){
				if (detected_server == SERVER_TYPE_MYSQL) {
					g_string_printf(statement,"/*!40101 SET NAMES binary*/;\n");
					g_string_append(statement,"/*!40014 SET FOREIGN_KEY_CHECKS=0*/;\n");
					if (!skip_tz) {
					  g_string_append(statement,"/*!40103 SET TIME_ZONE='+00:00' */;\n");
					}
				} else {
					g_string_printf(statement,"SET FOREIGN_KEY_CHECKS=0;\n");
				}

				if (!write_data(file,statement)) {
					g_critical("Could not write out data for %s.%s", database, table);
					return num_rows;
				}
			}
			g_string_printf(statement, "INSERT INTO `%s` VALUES", table);
			num_rows_st = 0;
		}
		
		if (statement_row->len) {
			g_string_append(statement, statement_row->str);
			g_string_set_size(statement_row,0);
			num_rows_st++;
		}
		
		g_string_append(statement_row, "\n(");

		for (i = 0; i < num_fields; i++) {
			/* Don't escape safe formats, saves some time */
			if (!row[i]) {
				g_string_append(statement_row, "NULL");
			} else if (fields[i].flags & NUM_FLAG) {
				g_string_append(statement_row, row[i]);
			} else {
				/* We reuse buffers for string escaping, growing is expensive just at the beginning */
				g_string_set_size(escaped, lengths[i]*2+1);
				mysql_real_escape_string(conn, escaped->str, row[i], lengths[i]);
				g_string_append_c(statement_row,'\"');
				g_string_append(statement_row,escaped->str);
				g_string_append_c(statement_row,'\"');
			}
			if (i < num_fields - 1) {
				g_string_append_c(statement_row,',');
			} else {
				g_string_append_c(statement_row,')');
				/* INSERT statement is closed before over limit */
				if(statement->len+statement_row->len+1 > statement_size) {
					if(num_rows_st == 0){
						g_string_append(statement, statement_row->str);
						g_string_set_size(statement_row,0);
						g_warning("Row bigger than statement_size for %s.%s", database, table);
					}
					g_string_append(statement,";\n");

					if (!write_data(file,statement)) {
						g_critical("Could not write out data for %s.%s", database, table);
						goto cleanup;
					}else{
						st_in_file++;
						if(chunk_filesize && st_in_file*(guint)ceil((float)statement_size/1024/1024) > chunk_filesize){
							fn++;
							fcfile = g_strdup_printf("%s.%05d.sql%s", filename_prefix,fn,(compress_output?".gz":""));
							if (!compress_output){
								fclose((FILE *)file);
								file = g_fopen(fcfile, "w");
                            } else {
								gzclose((gzFile)file);
                                file = (void*) gzopen(fcfile, "w");
                            }
							st_in_file = 0;
						}
					}
					g_string_set_size(statement,0);
				} else {
					if(num_rows_st)
						g_string_append_c(statement,',');
					g_string_append(statement, statement_row->str);
					num_rows_st++;
					g_string_set_size(statement_row,0);
				}
			}
		}
	}
	if (mysql_errno(conn)) {
		g_critical("Could not read data from %s.%s: %s", database, table, mysql_error(conn));
	}

	if (statement->len > 0) {
		g_string_append(statement,";\n");
		if (!write_data(file,statement)) {
			g_critical("Could not write out closing newline for %s.%s, now this is sad!", database, table);
			goto cleanup;
		}
		st_in_file++;
	}

cleanup:
	g_free(query);

	g_string_free(escaped,TRUE);
	g_string_free(statement,TRUE);

	if (result) {
		mysql_free_result(result);
	}
	
	if (!compress_output){
		fclose((FILE *)file);
	} else {
		gzclose((gzFile)file);
	}
	
	if (!st_in_file && !build_empty_files) {
		// dropping the useless file
		if (remove(fcfile)) {
 			g_warning("Failed to remove empty file : %s\n", fcfile);
		}
	}else if(chunk_filesize && fn == 1){
		fcfile = g_strdup_printf("%s.sql%s", filename_prefix,(compress_output?".gz":""));
		g_rename(filename, fcfile);
	}
	
	g_free(filename_prefix);
	g_free(fcfile);
	
	return num_rows;
}

gboolean write_data(FILE* file,GString * data) {
	size_t written= 0;
	ssize_t r= 0;

	while (written < data->len) {
		if (!compress_output)
			r = write(fileno(file), data->str + written, data->len);
		else
			r = gzwrite((gzFile)file, data->str + written, data->len);

		if (r < 0) {
			g_critical("Couldn't write data to a file: %s", strerror(errno));
			errors++;
			return FALSE;
		}
		written += r;
	}

	return TRUE;
}

void write_log_file(const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data) {
	(void) log_domain;
	(void) user_data;

	gchar date[20];
	time_t rawtime;
	struct tm timeinfo;

	time(&rawtime);
	localtime_r(&rawtime, &timeinfo);
	strftime(date, 20, "%Y-%m-%d %H:%M:%S", &timeinfo);

	GString* message_out = g_string_new(date);
	if (log_level & G_LOG_LEVEL_DEBUG) {
		g_string_append(message_out, " [DEBUG] - ");
	} else if ((log_level & G_LOG_LEVEL_INFO)
		|| (log_level & G_LOG_LEVEL_MESSAGE)) {
		g_string_append(message_out, " [INFO] - ");
	} else if (log_level & G_LOG_LEVEL_WARNING) {
		g_string_append(message_out, " [WARNING] - ");
	} else if ((log_level & G_LOG_LEVEL_ERROR)
		|| (log_level & G_LOG_LEVEL_CRITICAL)) {
		g_string_append(message_out, " [ERROR] - ");
	}

	g_string_append_printf(message_out, "%s\n", message);
	if (write(fileno(logoutfile), message_out->str, message_out->len) <= 0) {
		fprintf(stderr, "Cannot write to log file with error %d.  Exiting...", errno);
	}
	g_string_free(message_out, TRUE);
}