-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmyisampack.c
3235 lines (2940 loc) · 101 KB
/
myisampack.c
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
/* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
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; version 2 of the License.
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, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/* Pack MyISAM file */
#ifndef USE_MY_FUNC
#define USE_MY_FUNC /* We need at least my_malloc */
#endif
#include "myisamdef.h"
#include "my_default.h"
#include <queues.h>
#include <my_tree.h>
#include "mysys_err.h"
#ifndef __GNU_LIBRARY__
#define __GNU_LIBRARY__ /* Skip warnings in getopt.h */
#endif
#include <my_getopt.h>
#include <assert.h>
#if SIZEOF_LONG_LONG > 4
#define BITS_SAVED 64
#else
#define BITS_SAVED 32
#endif
#define IS_OFFSET ((uint) 32768) /* Bit if offset or char in tree */
#define HEAD_LENGTH 32
#define ALLOWED_JOIN_DIFF 256 /* Diff allowed to join trees */
#define DATA_TMP_EXT ".TMD"
#define OLD_EXT ".OLD"
#define FRM_EXT ".frm"
#define WRITE_COUNT MY_HOW_OFTEN_TO_WRITE
struct st_file_buffer {
File file;
uchar *buffer,*pos,*end;
my_off_t pos_in_file;
int bits;
ulonglong bitbucket;
};
struct st_huff_tree;
struct st_huff_element;
typedef struct st_huff_counts {
uint field_length,max_zero_fill;
uint pack_type;
uint max_end_space,max_pre_space,length_bits,min_space;
ulong max_length;
enum en_fieldtype field_type;
struct st_huff_tree *tree; /* Tree for field */
my_off_t counts[256];
my_off_t end_space[8];
my_off_t pre_space[8];
my_off_t tot_end_space,tot_pre_space,zero_fields,empty_fields,bytes_packed;
TREE int_tree; /* Tree for detecting distinct column values. */
uchar *tree_buff; /* Column values, 'field_length' each. */
uchar *tree_pos; /* Points to end of column values in 'tree_buff'. */
} HUFF_COUNTS;
typedef struct st_huff_element HUFF_ELEMENT;
/*
WARNING: It is crucial for the optimizations in calc_packed_length()
that 'count' is the first element of 'HUFF_ELEMENT'.
*/
struct st_huff_element {
my_off_t count;
union un_element {
struct st_nod {
HUFF_ELEMENT *left,*right;
} nod;
struct st_leaf {
HUFF_ELEMENT *null;
uint element_nr; /* Number of element */
} leaf;
} a;
};
typedef struct st_huff_tree {
HUFF_ELEMENT *root,*element_buffer;
HUFF_COUNTS *counts;
uint tree_number;
uint elements;
my_off_t bytes_packed;
uint tree_pack_length;
uint min_chr,max_chr,char_bits,offset_bits,max_offset,height;
ulonglong *code;
uchar *code_len;
} HUFF_TREE;
typedef struct st_isam_mrg {
MI_INFO **file,**current,**end;
uint free_file;
uint count;
uint min_pack_length; /* Theese is used by packed data */
uint max_pack_length;
uint ref_length;
uint max_blob_length;
my_off_t records;
/* true if at least one source file has at least one disabled index */
my_bool src_file_has_indexes_disabled;
} PACK_MRG_INFO;
extern int main(int argc,char * *argv);
static void get_options(int *argc,char ***argv);
static MI_INFO *open_isam_file(char *name,int mode);
static my_bool open_isam_files(PACK_MRG_INFO *mrg,char **names,uint count);
static int compress(PACK_MRG_INFO *file,char *join_name);
static int create_dest_frm(char *source_table, char *dest_table);
static HUFF_COUNTS *init_huff_count(MI_INFO *info,my_off_t records);
static void free_counts_and_tree_and_queue(HUFF_TREE *huff_trees,
uint trees,
HUFF_COUNTS *huff_counts,
uint fields);
static int compare_tree(void* cmp_arg __attribute__((unused)),
const uchar *s,const uchar *t);
static int get_statistic(PACK_MRG_INFO *mrg,HUFF_COUNTS *huff_counts);
static void check_counts(HUFF_COUNTS *huff_counts,uint trees,
my_off_t records);
static int test_space_compress(HUFF_COUNTS *huff_counts,my_off_t records,
uint max_space_length,my_off_t *space_counts,
my_off_t tot_space_count,
enum en_fieldtype field_type);
static HUFF_TREE* make_huff_trees(HUFF_COUNTS *huff_counts,uint trees);
static int make_huff_tree(HUFF_TREE *tree,HUFF_COUNTS *huff_counts);
static int compare_huff_elements(void *not_used, uchar *a,uchar *b);
static int save_counts_in_queue(uchar *key,element_count count,
HUFF_TREE *tree);
static my_off_t calc_packed_length(HUFF_COUNTS *huff_counts,uint flag);
static uint join_same_trees(HUFF_COUNTS *huff_counts,uint trees);
static int make_huff_decode_table(HUFF_TREE *huff_tree,uint trees);
static void make_traverse_code_tree(HUFF_TREE *huff_tree,
HUFF_ELEMENT *element,uint size,
ulonglong code);
static int write_header(PACK_MRG_INFO *isam_file, uint header_length,uint trees,
my_off_t tot_elements,my_off_t filelength);
static void write_field_info(HUFF_COUNTS *counts, uint fields,uint trees);
static my_off_t write_huff_tree(HUFF_TREE *huff_tree,uint trees);
static uint *make_offset_code_tree(HUFF_TREE *huff_tree,
HUFF_ELEMENT *element,
uint *offset);
static uint max_bit(uint value);
static int compress_isam_file(PACK_MRG_INFO *file,HUFF_COUNTS *huff_counts);
static char *make_new_name(char *new_name,char *old_name);
static char *make_old_name(char *new_name,char *old_name);
static void init_file_buffer(File file,pbool read_buffer);
static int flush_buffer(ulong neaded_length);
static void end_file_buffer(void);
static void write_bits(ulonglong value, uint bits);
static void flush_bits(void);
static int save_state(MI_INFO *isam_file,PACK_MRG_INFO *mrg,my_off_t new_length,
ha_checksum crc);
static int save_state_mrg(File file,PACK_MRG_INFO *isam_file,my_off_t new_length,
ha_checksum crc);
static int mrg_close(PACK_MRG_INFO *mrg);
static int mrg_rrnd(PACK_MRG_INFO *info,uchar *buf);
static void mrg_reset(PACK_MRG_INFO *mrg);
#if !defined(DBUG_OFF)
static void fakebigcodes(HUFF_COUNTS *huff_counts, HUFF_COUNTS *end_count);
static int fakecmp(my_off_t **count1, my_off_t **count2);
#endif
static int error_on_write=0,test_only=0,verbose=0,silent=0,
write_loop=0,force_pack=0, isamchk_neaded=0;
static int tmpfile_createflag=O_RDWR | O_TRUNC | O_EXCL;
static my_bool backup, opt_wait;
/*
tree_buff_length is somewhat arbitrary. The bigger it is the better
the chance to win in terms of compression factor. On the other hand,
this table becomes part of the compressed file header. And its length
is coded with 16 bits in the header. Hence the limit is 2**16 - 1.
*/
static uint tree_buff_length= 65536 - MALLOC_OVERHEAD;
static char tmp_dir[FN_REFLEN]={0},*join_table;
static my_off_t intervall_length;
static ha_checksum glob_crc;
static struct st_file_buffer file_buffer;
static QUEUE queue;
static HUFF_COUNTS *global_count;
static char zero_string[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
static const char *load_default_groups[]= { "myisampack",0 };
/* The main program */
int main(int argc, char **argv)
{
int error,ok;
PACK_MRG_INFO merge;
char **default_argv;
MY_INIT(argv[0]);
if (load_defaults("my",load_default_groups,&argc,&argv))
exit(1);
default_argv= argv;
get_options(&argc,&argv);
error=ok=isamchk_neaded=0;
if (join_table)
{
/*
Join files into one and create FRM file for the compressed table only if
the compression succeeds
*/
if (open_isam_files(&merge,argv,(uint) argc) ||
compress(&merge, join_table) || create_dest_frm(argv[0], join_table))
error=1;
}
else while (argc--)
{
MI_INFO *isam_file;
if (!(isam_file=open_isam_file(*argv++,O_RDWR)))
error=1;
else
{
merge.file= &isam_file;
merge.current=0;
merge.free_file=0;
merge.count=1;
if (compress(&merge,0))
error=1;
else
ok=1;
}
}
if (ok && isamchk_neaded && !silent)
puts("Remember to run myisamchk -rq on compressed tables");
(void) fflush(stdout);
(void) fflush(stderr);
free_defaults(default_argv);
my_end(verbose ? MY_CHECK_ERROR | MY_GIVE_INFO : MY_CHECK_ERROR);
exit(error ? 2 : 0);
#ifndef _lint
return 0; /* No compiler warning */
#endif
}
enum options_mp {OPT_CHARSETS_DIR_MP=256};
static struct my_option my_long_options[] =
{
{"backup", 'b', "Make a backup of the table as table_name.OLD.",
&backup, &backup, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"character-sets-dir", OPT_CHARSETS_DIR_MP,
"Directory where character sets are.", &charsets_dir,
&charsets_dir, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"debug", '#', "Output debug log. Often this is 'd:t:o,filename'.",
0, 0, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
{"force", 'f',
"Force packing of table even if it gets bigger or if tempfile exists.",
0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
{"join", 'j',
"Join all given tables into 'new_table_name'. All tables MUST have identical layouts.",
&join_table, &join_table, 0, GET_STR, REQUIRED_ARG, 0, 0, 0,
0, 0, 0},
{"help", '?', "Display this help and exit.",
0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
{"silent", 's', "Be more silent.",
0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
{"tmpdir", 'T', "Use temporary directory to store temporary table.",
0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"test", 't', "Don't pack table, only test packing it.",
0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
{"verbose", 'v', "Write info about progress and packing result. Use many -v for more verbosity!",
0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
{"version", 'V', "Output version information and exit.",
0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
{"wait", 'w', "Wait and retry if table is in use.", &opt_wait,
&opt_wait, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}
};
static void print_version(void)
{
printf("%s Ver 1.23 for %s on %s\n",
my_progname, SYSTEM_TYPE, MACHINE_TYPE);
}
static void usage(void)
{
print_version();
puts("Copyright 2002-2008 MySQL AB, 2008 Sun Microsystems, Inc.");
puts("This software comes with ABSOLUTELY NO WARRANTY. This is free software,");
puts("and you are welcome to modify and redistribute it under the GPL license\n");
puts("Pack a MyISAM-table to take much less space.");
puts("Keys are not updated, you must run myisamchk -rq on the datafile");
puts("afterwards to update the keys.");
puts("You should give the .MYI file as the filename argument.");
printf("\nUsage: %s [OPTIONS] filename...\n", my_progname);
my_print_help(my_long_options);
print_defaults("my", load_default_groups);
my_print_variables(my_long_options);
}
static my_bool
get_one_option(int optid, const struct my_option *opt __attribute__((unused)),
char *argument)
{
uint length;
switch(optid) {
case 'f':
force_pack= 1;
tmpfile_createflag= O_RDWR | O_TRUNC;
break;
case 's':
write_loop= verbose= 0;
silent= 1;
break;
case 't':
test_only= 1;
/* Avoid to reset 'verbose' if it was already set > 1. */
if (! verbose)
verbose= 1;
break;
case 'T':
length= (uint) (strmov(tmp_dir, argument) - tmp_dir);
if (length != dirname_length(tmp_dir))
{
tmp_dir[length]=FN_LIBCHAR;
tmp_dir[length+1]=0;
}
break;
case 'v':
verbose++; /* Allow for selecting the level of verbosity. */
silent= 0;
break;
case '#':
DBUG_PUSH(argument ? argument : "d:t:o");
break;
case 'V':
print_version();
exit(0);
case 'I':
case '?':
usage();
exit(0);
}
return 0;
}
/* reads options */
/* Initiates DEBUG - but no debugging here ! */
static void get_options(int *argc,char ***argv)
{
int ho_error;
my_progname= argv[0][0];
if (isatty(fileno(stdout)))
write_loop=1;
if ((ho_error=handle_options(argc, argv, my_long_options, get_one_option)))
exit(ho_error);
if (!*argc)
{
usage();
exit(1);
}
if (join_table)
{
backup=0; /* Not needed */
tmp_dir[0]=0;
}
return;
}
static MI_INFO *open_isam_file(char *name,int mode)
{
MI_INFO *isam_file;
MYISAM_SHARE *share;
DBUG_ENTER("open_isam_file");
if (!(isam_file=mi_open(name,mode,
(opt_wait ? HA_OPEN_WAIT_IF_LOCKED :
HA_OPEN_ABORT_IF_LOCKED))))
{
(void) fprintf(stderr, "%s gave error %d on open\n", name, my_errno);
DBUG_RETURN(0);
}
share=isam_file->s;
if (share->options & HA_OPTION_COMPRESS_RECORD && !join_table)
{
if (!force_pack)
{
(void) fprintf(stderr, "%s is already compressed\n", name);
(void) mi_close(isam_file);
DBUG_RETURN(0);
}
if (verbose)
puts("Recompressing already compressed table");
share->options&= ~HA_OPTION_READ_ONLY_DATA; /* We are modifing it */
}
if (! force_pack && share->state.state.records != 0 &&
(share->state.state.records <= 1 ||
share->state.state.data_file_length < 1024))
{
(void) fprintf(stderr, "%s is too small to compress\n", name);
(void) mi_close(isam_file);
DBUG_RETURN(0);
}
(void) mi_lock_database(isam_file,F_WRLCK);
DBUG_RETURN(isam_file);
}
static my_bool open_isam_files(PACK_MRG_INFO *mrg, char **names, uint count)
{
uint i,j;
mrg->count=0;
mrg->current=0;
mrg->file=(MI_INFO**) my_malloc(sizeof(MI_INFO*)*count,MYF(MY_FAE));
mrg->free_file=1;
mrg->src_file_has_indexes_disabled= 0;
for (i=0; i < count ; i++)
{
if (!(mrg->file[i]=open_isam_file(names[i],O_RDONLY)))
goto error;
mrg->src_file_has_indexes_disabled|=
! mi_is_all_keys_active(mrg->file[i]->s->state.key_map,
mrg->file[i]->s->base.keys);
}
/* Check that files are identical */
for (j=0 ; j < count-1 ; j++)
{
MI_COLUMNDEF *m1,*m2,*end;
if (mrg->file[j]->s->base.reclength != mrg->file[j+1]->s->base.reclength ||
mrg->file[j]->s->base.fields != mrg->file[j+1]->s->base.fields)
goto diff_file;
m1=mrg->file[j]->s->rec;
end=m1+mrg->file[j]->s->base.fields;
m2=mrg->file[j+1]->s->rec;
for ( ; m1 != end ; m1++,m2++)
{
if (m1->type != m2->type || m1->length != m2->length)
goto diff_file;
}
}
mrg->count=count;
return 0;
diff_file:
(void) fprintf(stderr, "%s: Tables '%s' and '%s' are not identical\n",
my_progname, names[j], names[j+1]);
error:
while (i--)
mi_close(mrg->file[i]);
my_free(mrg->file);
return 1;
}
static int compress(PACK_MRG_INFO *mrg,char *result_table)
{
int error;
File new_file,join_isam_file;
MI_INFO *isam_file;
MYISAM_SHARE *share;
char org_name[FN_REFLEN],new_name[FN_REFLEN],temp_name[FN_REFLEN];
uint i,header_length,fields,trees,used_trees;
my_off_t old_length,new_length,tot_elements;
HUFF_COUNTS *huff_counts;
HUFF_TREE *huff_trees;
DBUG_ENTER("compress");
isam_file=mrg->file[0]; /* Take this as an example */
share=isam_file->s;
new_file=join_isam_file= -1;
trees=fields=0;
huff_trees=0;
huff_counts=0;
/* Create temporary or join file */
if (backup)
(void) fn_format(org_name,isam_file->filename,"",MI_NAME_DEXT,2);
else
(void) fn_format(org_name,isam_file->filename,"",MI_NAME_DEXT,2+4+16);
if (!test_only && result_table)
{
/* Make a new indexfile based on first file in list */
uint length;
uchar *buff;
strmov(org_name,result_table); /* Fix error messages */
(void) fn_format(new_name,result_table,"",MI_NAME_IEXT,2);
if ((join_isam_file=my_create(new_name,0,tmpfile_createflag,MYF(MY_WME)))
< 0)
goto err;
length=(uint) share->base.keystart;
if (!(buff= (uchar*) my_malloc(length,MYF(MY_WME))))
goto err;
if (my_pread(share->kfile,buff,length,0L,MYF(MY_WME | MY_NABP)) ||
my_write(join_isam_file,buff,length,
MYF(MY_WME | MY_NABP | MY_WAIT_IF_FULL)))
{
my_free(buff);
goto err;
}
my_free(buff);
(void) fn_format(new_name,result_table,"",MI_NAME_DEXT,2);
}
else if (!tmp_dir[0])
(void) make_new_name(new_name,org_name);
else
(void) fn_format(new_name,org_name,tmp_dir,DATA_TMP_EXT,1+2+4);
if (!test_only &&
(new_file=my_create(new_name,0,tmpfile_createflag,MYF(MY_WME))) < 0)
goto err;
/* Start calculating statistics */
mrg->records=0;
for (i=0 ; i < mrg->count ; i++)
mrg->records+=mrg->file[i]->s->state.state.records;
DBUG_PRINT("info", ("Compressing %s: (%lu records)",
result_table ? new_name : org_name,
(ulong) mrg->records));
if (write_loop || verbose)
{
printf("Compressing %s: (%lu records)\n",
result_table ? new_name : org_name, (ulong) mrg->records);
}
trees=fields=share->base.fields;
huff_counts=init_huff_count(isam_file,mrg->records);
/*
Read the whole data file(s) for statistics.
*/
DBUG_PRINT("info", ("- Calculating statistics"));
if (write_loop || verbose)
printf("- Calculating statistics\n");
if (get_statistic(mrg,huff_counts))
goto err;
old_length=0;
for (i=0; i < mrg->count ; i++)
old_length+= (mrg->file[i]->s->state.state.data_file_length -
mrg->file[i]->s->state.state.empty);
/*
Create a global priority queue in preparation for making
temporary Huffman trees.
*/
if (init_queue(&queue,256,0,0,compare_huff_elements,0))
goto err;
/*
Check each column if we should use pre-space-compress, end-space-
compress, empty-field-compress or zero-field-compress.
*/
check_counts(huff_counts,fields,mrg->records);
/*
Build a Huffman tree for each column.
*/
huff_trees=make_huff_trees(huff_counts,trees);
/*
If the packed lengths of combined columns is less then the sum of
the non-combined columns, then create common Huffman trees for them.
We do this only for byte compressed columns, not for distinct values
compressed columns.
*/
if ((int) (used_trees=join_same_trees(huff_counts,trees)) < 0)
goto err;
/*
Assign codes to all byte or column values.
*/
if (make_huff_decode_table(huff_trees,fields))
goto err;
/* Prepare a file buffer. */
init_file_buffer(new_file,0);
/*
Reserve space in the target file for the fixed compressed file header.
*/
file_buffer.pos_in_file=HEAD_LENGTH;
if (! test_only)
my_seek(new_file,file_buffer.pos_in_file,MY_SEEK_SET,MYF(0));
/*
Write field infos: field type, pack type, length bits, tree number.
*/
write_field_info(huff_counts,fields,used_trees);
/*
Write decode trees.
*/
if (!(tot_elements=write_huff_tree(huff_trees,trees)))
goto err;
/*
Calculate the total length of the compression info header.
This includes the fixed compressed file header, the column compression
type descriptions, and the decode trees.
*/
header_length=(uint) file_buffer.pos_in_file+
(uint) (file_buffer.pos-file_buffer.buffer);
/*
Compress the source file into the target file.
*/
DBUG_PRINT("info", ("- Compressing file"));
if (write_loop || verbose)
printf("- Compressing file\n");
error=compress_isam_file(mrg,huff_counts);
new_length=file_buffer.pos_in_file;
if (!error && !test_only)
{
uchar buff[MEMMAP_EXTRA_MARGIN]; /* End marginal for memmap */
memset(buff, 0, sizeof(buff));
error=my_write(file_buffer.file,buff,sizeof(buff),
MYF(MY_WME | MY_NABP | MY_WAIT_IF_FULL)) != 0;
}
/*
Write the fixed compressed file header.
*/
if (!error)
error=write_header(mrg,header_length,used_trees,tot_elements,
new_length);
/* Flush the file buffer. */
end_file_buffer();
/* Display statistics. */
DBUG_PRINT("info", ("Min record length: %6d Max length: %6d "
"Mean total length: %6ld\n",
mrg->min_pack_length, mrg->max_pack_length,
(ulong) (mrg->records ? (new_length/mrg->records) : 0)));
if (verbose && mrg->records)
printf("Min record length: %6d Max length: %6d "
"Mean total length: %6ld\n", mrg->min_pack_length,
mrg->max_pack_length, (ulong) (new_length/mrg->records));
/* Close source and target file. */
if (!test_only)
{
error|=my_close(new_file,MYF(MY_WME));
if (!result_table)
{
error|=my_close(isam_file->dfile,MYF(MY_WME));
isam_file->dfile= -1; /* Tell mi_close file is closed */
}
}
/* Cleanup. */
free_counts_and_tree_and_queue(huff_trees,trees,huff_counts,fields);
if (! test_only && ! error)
{
if (result_table)
{
error=save_state_mrg(join_isam_file,mrg,new_length,glob_crc);
}
else
{
if (backup)
{
if (my_rename(org_name,make_old_name(temp_name,isam_file->filename),
MYF(MY_WME)))
error=1;
else
{
if (tmp_dir[0])
error=my_copy(new_name,org_name,MYF(MY_WME));
else
error=my_rename(new_name,org_name,MYF(MY_WME));
if (!error)
{
(void) my_copystat(temp_name,org_name,MYF(MY_COPYTIME));
if (tmp_dir[0])
(void) my_delete(new_name,MYF(MY_WME));
}
}
}
else
{
if (tmp_dir[0])
{
error=my_copy(new_name,org_name,
MYF(MY_WME | MY_HOLD_ORIGINAL_MODES | MY_COPYTIME));
if (!error)
(void) my_delete(new_name,MYF(MY_WME));
}
else
error=my_redel(org_name,new_name,MYF(MY_WME | MY_COPYTIME));
}
if (! error)
error=save_state(isam_file,mrg,new_length,glob_crc);
}
}
error|=mrg_close(mrg);
if (join_isam_file >= 0)
error|=my_close(join_isam_file,MYF(MY_WME));
if (error)
{
(void) fprintf(stderr, "Aborting: %s is not compressed\n", org_name);
(void) my_delete(new_name,MYF(MY_WME));
DBUG_RETURN(-1);
}
if (write_loop || verbose)
{
if (old_length)
printf("%.4g%% \n",
(((longlong) (old_length - new_length)) * 100.0 /
(longlong) old_length));
else
puts("Empty file saved in compressed format");
}
DBUG_RETURN(0);
err:
free_counts_and_tree_and_queue(huff_trees,trees,huff_counts,fields);
if (new_file >= 0)
(void) my_close(new_file,MYF(0));
if (join_isam_file >= 0)
(void) my_close(join_isam_file,MYF(0));
mrg_close(mrg);
(void) fprintf(stderr, "Aborted: %s is not compressed\n", org_name);
DBUG_RETURN(-1);
}
/**
Create FRM for the destination table for --join operation
Copy the first table FRM as the destination table FRM file. Doing so
will help the mysql server to recognize the newly created table.
See Bug#36573.
@param source_table Name of the source table
@param dest_table Name of the destination table
@retval 0 Successful copy operation
@note We always return 0 because we don't want myisampack to report error
even if the copy operation fails.
*/
static int create_dest_frm(char *source_table, char *dest_table)
{
char source_name[FN_REFLEN], dest_name[FN_REFLEN];
DBUG_ENTER("create_dest_frm");
(void) fn_format(source_name, source_table,
"", FRM_EXT, MY_UNPACK_FILENAME | MY_RESOLVE_SYMLINKS);
(void) fn_format(dest_name, dest_table,
"", FRM_EXT, MY_UNPACK_FILENAME | MY_RESOLVE_SYMLINKS);
/*
Error messages produced by my_copy() are suppressed as this
is not vital for --join operation. User shouldn't see any error messages
like "source file frm not found" and "unable to create destination frm
file. So we don't pass the flag MY_WME -Write Message on Error to
my_copy()
*/
(void) my_copy(source_name, dest_name, MYF(MY_DONT_OVERWRITE_FILE));
DBUG_RETURN(0);
}
/* Init a huff_count-struct for each field and init it */
static HUFF_COUNTS *init_huff_count(MI_INFO *info,my_off_t records)
{
reg2 uint i;
reg1 HUFF_COUNTS *count;
if ((count = (HUFF_COUNTS*) my_malloc(info->s->base.fields*
sizeof(HUFF_COUNTS),
MYF(MY_ZEROFILL | MY_WME))))
{
for (i=0 ; i < info->s->base.fields ; i++)
{
enum en_fieldtype type;
count[i].field_length=info->s->rec[i].length;
type= count[i].field_type= (enum en_fieldtype) info->s->rec[i].type;
if (type == FIELD_INTERVALL ||
type == FIELD_CONSTANT ||
type == FIELD_ZERO)
type = FIELD_NORMAL;
if (count[i].field_length <= 8 &&
(type == FIELD_NORMAL ||
type == FIELD_SKIP_ZERO))
count[i].max_zero_fill= count[i].field_length;
/*
For every column initialize a tree, which is used to detect distinct
column values. 'int_tree' works together with 'tree_buff' and
'tree_pos'. It's keys are implemented by pointers into 'tree_buff'.
This is accomplished by '-1' as the element size.
*/
init_tree(&count[i].int_tree,0,0,-1,(qsort_cmp2) compare_tree,0, NULL,
NULL);
if (records && type != FIELD_BLOB && type != FIELD_VARCHAR)
count[i].tree_pos=count[i].tree_buff =
my_malloc(count[i].field_length > 1 ? tree_buff_length : 2,
MYF(MY_WME));
}
}
return count;
}
/* Free memory used by counts and trees */
static void free_counts_and_tree_and_queue(HUFF_TREE *huff_trees, uint trees,
HUFF_COUNTS *huff_counts,
uint fields)
{
register uint i;
if (huff_trees)
{
for (i=0 ; i < trees ; i++)
{
if (huff_trees[i].element_buffer)
my_free(huff_trees[i].element_buffer);
if (huff_trees[i].code)
my_free(huff_trees[i].code);
}
my_free(huff_trees);
}
if (huff_counts)
{
for (i=0 ; i < fields ; i++)
{
if (huff_counts[i].tree_buff)
{
my_free(huff_counts[i].tree_buff);
delete_tree(&huff_counts[i].int_tree);
}
}
my_free(huff_counts);
}
delete_queue(&queue); /* This is safe to free */
return;
}
/* Read through old file and gather some statistics */
static int get_statistic(PACK_MRG_INFO *mrg,HUFF_COUNTS *huff_counts)
{
int error;
uint length;
ulong reclength,max_blob_length;
uchar *record,*pos,*next_pos,*end_pos,*start_pos;
ha_rows record_count;
my_bool static_row_size;
HUFF_COUNTS *count,*end_count;
TREE_ELEMENT *element;
DBUG_ENTER("get_statistic");
reclength=mrg->file[0]->s->base.reclength;
record=(uchar*) my_alloca(reclength);
end_count=huff_counts+mrg->file[0]->s->base.fields;
record_count=0; glob_crc=0;
max_blob_length=0;
/* Check how to calculate checksum */
static_row_size=1;
for (count=huff_counts ; count < end_count ; count++)
{
if (count->field_type == FIELD_BLOB ||
count->field_type == FIELD_VARCHAR)
{
static_row_size=0;
break;
}
}
mrg_reset(mrg);
while ((error=mrg_rrnd(mrg,record)) != HA_ERR_END_OF_FILE)
{
ulong tot_blob_length=0;
if (! error)
{
/* glob_crc is a checksum over all bytes of all records. */
if (static_row_size)
glob_crc+=mi_static_checksum(mrg->file[0],record);
else
glob_crc+=mi_checksum(mrg->file[0],record);
/* Count the incidence of values separately for every column. */
for (pos=record,count=huff_counts ;
count < end_count ;
count++,
pos=next_pos)
{
next_pos=end_pos=(start_pos=pos)+count->field_length;
/*
Put the whole column value in a tree if there is room for it.
'int_tree' is used to quickly check for duplicate values.
'tree_buff' collects as many distinct column values as
possible. If the field length is > 1, it is tree_buff_length,
else 2 bytes. Each value is 'field_length' bytes big. If there
are more distinct column values than fit into the buffer, we
give up with this tree. BLOBs and VARCHARs do not have a
tree_buff as it can only be used with fixed length columns.
For the special case of field length == 1, we handle only the
case that there is only one distinct value in the table(s).
Otherwise, we can have a maximum of 256 distinct values. This
is then handled by the normal Huffman tree build.
Another limit for collecting distinct column values is the
number of values itself. Since we would need to build a
Huffman tree for the values, we are limited by the 'IS_OFFSET'
constant. This constant expresses a bit which is used to
determine if a tree element holds a final value or an offset
to a child element. Hence, all values and offsets need to be
smaller than 'IS_OFFSET'. A tree element is implemented with
two integer values, one for the left branch and one for the
right branch. For the extreme case that the first element
points to the last element, the number of integers in the tree
must be less or equal to IS_OFFSET. So the number of elements
must be less or equal to IS_OFFSET / 2.
WARNING: At first, we insert a pointer into the record buffer
as the key for the tree. If we got a new distinct value, which
is really inserted into the tree, instead of being counted
only, we will copy the column value from the record buffer to
'tree_buff' and adjust the key pointer of the tree accordingly.
*/
if (count->tree_buff)
{
global_count=count;
if (!(element=tree_insert(&count->int_tree,pos, 0,
count->int_tree.custom_arg)) ||
(element->count == 1 &&
(count->tree_buff + tree_buff_length <
count->tree_pos + count->field_length)) ||
(count->int_tree.elements_in_tree > IS_OFFSET / 2) ||
(count->field_length == 1 &&
count->int_tree.elements_in_tree > 1))
{
delete_tree(&count->int_tree);
my_free(count->tree_buff);
count->tree_buff=0;
}
else
{
/*
If tree_insert() succeeds, it either creates a new element
or increments the counter of an existing element.
*/
if (element->count == 1)
{
/* Copy the new column value into 'tree_buff'. */
memcpy(count->tree_pos,pos,(size_t) count->field_length);
/* Adjust the key pointer in the tree. */
tree_set_pointer(element,count->tree_pos);
/* Point behind the last column value so far. */
count->tree_pos+=count->field_length;
}
}
}
/* Save character counters and space-counts and zero-field-counts */
if (count->field_type == FIELD_NORMAL ||
count->field_type == FIELD_SKIP_ENDSPACE)
{
/* Ignore trailing space. */
for ( ; end_pos > pos ; end_pos--)
if (end_pos[-1] != ' ')
break;
/* Empty fields are just counted. Go to the next record. */
if (end_pos == pos)
{
count->empty_fields++;
count->max_zero_fill=0;
continue;
}