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
|
/* Copyright (C) 2003 MySQL AB
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include "drizzled/server_includes.h"
#include "drizzled/field.h"
#include "drizzled/field/blob.h"
#include "drizzled/field/timestamp.h"
#include "plugin/myisam/myisam.h"
#include "drizzled/table.h"
#include "drizzled/session.h"
#include <mysys/my_dir.h>
#include "ha_archive.h"
#include <stdio.h>
#include <string>
#include <map>
using namespace std;
static const string engine_name("ARCHIVE");
/*
First, if you want to understand storage engines you should look at
ha_example.cc and ha_example.h.
This example was written as a test case for a customer who needed
a storage engine without indexes that could compress data very well.
So, welcome to a completely compressed storage engine. This storage
engine only does inserts. No replace, deletes, or updates. All reads are
complete table scans. Compression is done through a combination of packing
and making use of the zlib library
We keep a file pointer open for each instance of ha_archive for each read
but for writes we keep one open file handle just for that. We flush it
only if we have a read occur. azip handles compressing lots of records
at once much better then doing lots of little records between writes.
It is possible to not lock on writes but this would then mean we couldn't
handle bulk inserts as well (that is if someone was trying to read at
the same time since we would want to flush).
A "meta" file is kept alongside the data file. This file serves two purpose.
The first purpose is to track the number of rows in the table. The second
purpose is to determine if the table was closed properly or not. When the
meta file is first opened it is marked as dirty. It is opened when the table
itself is opened for writing. When the table is closed the new count for rows
is written to the meta file and the file is marked as clean. If the meta file
is opened and it is marked as dirty, it is assumed that a crash occured. At
this point an error occurs and the user is told to rebuild the file.
A rebuild scans the rows and rewrites the meta file. If corruption is found
in the data file then the meta file is not repaired.
At some point a recovery method for such a drastic case needs to be divised.
Locks are row level, and you will get a consistant read.
For performance as far as table scans go it is quite fast. I don't have
good numbers but locally it has out performed both Innodb and MyISAM. For
Innodb the question will be if the table can be fit into the buffer
pool. For MyISAM its a question of how much the file system caches the
MyISAM file. With enough free memory MyISAM is faster. Its only when the OS
doesn't have enough memory to cache entire table that archive turns out
to be any faster.
Examples between MyISAM (packed) and Archive.
Table with 76695844 identical rows:
29680807 a_archive.ARZ
920350317 a.MYD
Table with 8991478 rows (all of Slashdot's comments):
1922964506 comment_archive.ARZ
2944970297 comment_text.MYD
TODO:
Allow users to set compression level.
Allow adjustable block size.
Implement versioning, should be easy.
Allow for errors, find a way to mark bad rows.
Add optional feature so that rows can be flushed at interval (which will cause less
compression but may speed up ordered searches).
Checkpoint the meta file to allow for faster rebuilds.
Option to allow for dirty reads, this would lower the sync calls, which would make
inserts a lot faster, but would mean highly arbitrary reads.
-Brian
*/
/* Variables for archive share methods */
pthread_mutex_t archive_mutex= PTHREAD_MUTEX_INITIALIZER;
static unsigned int global_version;
/* The file extension */
#define ARZ ".arz" // The data file
#define ARN ".ARN" // Files used during an optimize call
static bool archive_use_aio= false;
/*
Number of rows that will force a bulk insert.
*/
#define ARCHIVE_MIN_ROWS_TO_USE_BULK_INSERT 2
/*
Size of header used for row
*/
#define ARCHIVE_ROW_HEADER_SIZE 4
/*
We just implement one additional file extension.
*/
static const char *ha_archive_exts[] = {
ARZ,
NULL
};
class ArchiveEngine : public drizzled::plugin::StorageEngine
{
typedef std::map<string, ArchiveShare*> ArchiveMap;
ArchiveMap archive_open_tables;
public:
ArchiveEngine(const string &name_arg)
: drizzled::plugin::StorageEngine(name_arg,
HTON_FILE_BASED |
HTON_STATS_RECORDS_IS_EXACT |
HTON_HAS_RECORDS |
HTON_HAS_DATA_DICTIONARY)
{
table_definition_ext= ARZ;
}
virtual Cursor *create(TableShare &table,
MEM_ROOT *mem_root)
{
return new (mem_root) ha_archive(*this, table);
}
const char **bas_ext() const {
return ha_archive_exts;
}
int doCreateTable(Session *session, const char *table_name,
Table& table_arg,
drizzled::message::Table& proto);
int doGetTableDefinition(Session& session,
const char* path,
const char *db,
const char *table_name,
const bool is_tmp,
drizzled::message::Table *table_proto);
void doGetTableNames(CachedDirectory &directory, string& , set<string>& set_of_names);
int doDropTable(Session&, const string table_path);
ArchiveShare *findOpenTable(const string table_name);
void addOpenTable(const string &table_name, ArchiveShare *);
void deleteOpenTable(const string &table_name);
uint32_t max_supported_keys() const { return 1; }
uint32_t max_supported_key_length() const { return sizeof(uint64_t); }
uint32_t max_supported_key_part_length() const { return sizeof(uint64_t); }
};
ArchiveShare *ArchiveEngine::findOpenTable(const string table_name)
{
ArchiveMap::iterator find_iter=
archive_open_tables.find(table_name);
if (find_iter != archive_open_tables.end())
return (*find_iter).second;
else
return NULL;
}
void ArchiveEngine::addOpenTable(const string &table_name, ArchiveShare *share)
{
archive_open_tables[table_name]= share;
}
void ArchiveEngine::deleteOpenTable(const string &table_name)
{
archive_open_tables.erase(table_name);
}
void ArchiveEngine::doGetTableNames(CachedDirectory &directory,
string&,
set<string>& set_of_names)
{
CachedDirectory::Entries entries= directory.getEntries();
for (CachedDirectory::Entries::iterator entry_iter= entries.begin();
entry_iter != entries.end(); ++entry_iter)
{
CachedDirectory::Entry *entry= *entry_iter;
string *filename= &entry->filename;
assert(filename->size());
const char *ext= strchr(filename->c_str(), '.');
if (ext == NULL || my_strcasecmp(system_charset_info, ext, ARZ) ||
is_prefix(filename->c_str(), TMP_FILE_PREFIX))
{ }
else
{
char uname[NAME_LEN + 1];
uint32_t file_name_len;
file_name_len= filename_to_tablename(filename->c_str(), uname, sizeof(uname));
// TODO: Remove need for memory copy here
uname[file_name_len - sizeof(ARZ) + 1]= '\0'; // Subtract ending, place NULL
set_of_names.insert(uname);
}
}
}
int ArchiveEngine::doDropTable(Session&,
const string table_path)
{
string new_path(table_path);
new_path+= ARZ;
int error= unlink(new_path.c_str());
if (error != 0)
{
error= my_errno= errno;
}
return error;
}
int ArchiveEngine::doGetTableDefinition(Session&,
const char* path,
const char *,
const char *,
const bool,
drizzled::message::Table *table_proto)
{
struct stat stat_info;
int error= ENOENT;
string proto_path;
proto_path.reserve(FN_REFLEN);
proto_path.assign(path);
proto_path.append(ARZ);
if (stat(proto_path.c_str(),&stat_info))
return errno;
else
error= EEXIST;
if (table_proto)
{
azio_stream proto_stream;
char* proto_string;
if (azopen(&proto_stream, proto_path.c_str(), O_RDONLY, AZ_METHOD_BLOCK) == 0)
return HA_ERR_CRASHED_ON_USAGE;
proto_string= (char*)malloc(sizeof(char) * proto_stream.frm_length);
if (proto_string == NULL)
{
azclose(&proto_stream);
return ENOMEM;
}
azread_frm(&proto_stream, proto_string);
if (table_proto->ParseFromArray(proto_string, proto_stream.frm_length) == false)
error= HA_ERR_CRASHED_ON_USAGE;
azclose(&proto_stream);
free(proto_string);
}
return error;
}
static ArchiveEngine *archive_engine= NULL;
/*
Initialize the archive Cursor.
SYNOPSIS
archive_db_init()
void *
RETURN
false OK
true Error
*/
static int archive_db_init(drizzled::plugin::Registry ®istry)
{
pthread_mutex_init(&archive_mutex, MY_MUTEX_INIT_FAST);
archive_engine= new ArchiveEngine(engine_name);
registry.add(archive_engine);
/* When the engine starts up set the first version */
global_version= 1;
return false;
}
/*
Release the archive Cursor.
SYNOPSIS
archive_db_done()
void
RETURN
false OK
*/
static int archive_db_done(drizzled::plugin::Registry ®istry)
{
registry.remove(archive_engine);
delete archive_engine;
pthread_mutex_destroy(&archive_mutex);
return 0;
}
ha_archive::ha_archive(drizzled::plugin::StorageEngine &engine_arg,
TableShare &table_arg)
:Cursor(engine_arg, table_arg), delayed_insert(0), bulk_insert(0)
{
/* Set our original buffer from pre-allocated memory */
buffer.set((char *)byte_buffer, IO_SIZE, system_charset_info);
/* The size of the offset value we will use for position() */
ref_length= sizeof(my_off_t);
archive_reader_open= false;
}
/*
This method reads the header of a datafile and returns whether or not it was successful.
*/
int ha_archive::read_data_header(azio_stream *file_to_read)
{
if (azread_init(file_to_read) == -1)
return(HA_ERR_CRASHED_ON_USAGE);
if (file_to_read->version >= 3)
return(0);
return(1);
}
ArchiveShare::ArchiveShare():
use_count(0), archive_write_open(false), dirty(false), crashed(false),
mean_rec_length(0), version(0), rows_recorded(0), version_rows(0)
{
assert(1);
}
ArchiveShare::ArchiveShare(const char *name):
use_count(0), archive_write_open(false), dirty(false), crashed(false),
mean_rec_length(0), version(0), rows_recorded(0), version_rows(0)
{
memset(&archive_write, 0, sizeof(azio_stream)); /* Archive file we are working with */
table_name.append(name);
fn_format(data_file_name, table_name.c_str(), "",
ARZ, MY_REPLACE_EXT | MY_UNPACK_FILENAME);
/*
We will use this lock for rows.
*/
pthread_mutex_init(&mutex,MY_MUTEX_INIT_FAST);
}
ArchiveShare::~ArchiveShare()
{
thr_lock_delete(&lock);
pthread_mutex_destroy(&mutex);
/*
We need to make sure we don't reset the crashed state.
If we open a crashed file, wee need to close it as crashed unless
it has been repaired.
Since we will close the data down after this, we go on and count
the flush on close;
*/
if (archive_write_open == true)
(void)azclose(&archive_write);
}
bool ArchiveShare::prime(uint64_t *auto_increment)
{
azio_stream archive_tmp;
/*
We read the meta file, but do not mark it dirty. Since we are not
doing a write we won't mark it dirty (and we won't open it for
anything but reading... open it for write and we will generate null
compression writes).
*/
if (!(azopen(&archive_tmp, data_file_name, O_RDONLY,
AZ_METHOD_BLOCK)))
return false;
*auto_increment= archive_tmp.auto_increment + 1;
rows_recorded= (ha_rows)archive_tmp.rows;
crashed= archive_tmp.dirty;
if (version < global_version)
{
version_rows= rows_recorded;
version= global_version;
}
azclose(&archive_tmp);
return true;
}
/*
We create the shared memory space that we will use for the open table.
No matter what we try to get or create a share. This is so that a repair
table operation can occur.
See ha_example.cc for a longer description.
*/
ArchiveShare *ha_archive::get_share(const char *table_name, int *rc)
{
pthread_mutex_lock(&archive_mutex);
ArchiveEngine *a_engine= static_cast<ArchiveEngine *>(engine);
share= a_engine->findOpenTable(table_name);
if (!share)
{
share= new ArchiveShare(table_name);
if (share == NULL)
{
pthread_mutex_unlock(&archive_mutex);
*rc= HA_ERR_OUT_OF_MEM;
return(NULL);
}
if (share->prime(&stats.auto_increment_value) == false)
{
pthread_mutex_unlock(&archive_mutex);
*rc= HA_ERR_CRASHED_ON_REPAIR;
delete share;
return NULL;
}
a_engine->addOpenTable(share->table_name, share);
thr_lock_init(&share->lock);
}
share->use_count++;
if (share->crashed)
*rc= HA_ERR_CRASHED_ON_USAGE;
pthread_mutex_unlock(&archive_mutex);
return(share);
}
/*
Free the share.
See ha_example.cc for a description.
*/
int ha_archive::free_share()
{
pthread_mutex_lock(&archive_mutex);
if (!--share->use_count)
{
ArchiveEngine *a_engine= static_cast<ArchiveEngine *>(engine);
a_engine->deleteOpenTable(share->table_name);
delete share;
}
pthread_mutex_unlock(&archive_mutex);
return 0;
}
int ha_archive::init_archive_writer()
{
/*
It is expensive to open and close the data files and since you can't have
a gzip file that can be both read and written we keep a writer open
that is shared amoung all open tables.
*/
if (!(azopen(&(share->archive_write), share->data_file_name,
O_RDWR, AZ_METHOD_BLOCK)))
{
share->crashed= true;
return(1);
}
share->archive_write_open= true;
return(0);
}
/*
No locks are required because it is associated with just one Cursor instance
*/
int ha_archive::init_archive_reader()
{
/*
It is expensive to open and close the data files and since you can't have
a gzip file that can be both read and written we keep a writer open
that is shared amoung all open tables.
*/
if (archive_reader_open == false)
{
az_method method;
switch (archive_use_aio)
{
case false:
method= AZ_METHOD_BLOCK;
break;
case true:
method= AZ_METHOD_AIO;
break;
default:
method= AZ_METHOD_BLOCK;
}
if (!(azopen(&archive, share->data_file_name, O_RDONLY,
method)))
{
share->crashed= true;
return(1);
}
archive_reader_open= true;
}
return(0);
}
/*
When opening a file we:
Create/get our shared structure.
Init out lock.
We open the file we will read from.
*/
int ha_archive::open(const char *name, int, uint32_t)
{
int rc= 0;
share= get_share(name, &rc);
/**
We either fix it ourselves, or we just take it offline
@todo Create some documentation in the recovery tools shipped with the engine.
*/
if (rc == HA_ERR_CRASHED_ON_USAGE)
{
free_share();
rc= repair();
return 0;
}
else if (rc == HA_ERR_OUT_OF_MEM)
{
return(rc);
}
assert(share);
record_buffer= create_record_buffer(table->s->reclength +
ARCHIVE_ROW_HEADER_SIZE);
if (!record_buffer)
{
free_share();
return(HA_ERR_OUT_OF_MEM);
}
thr_lock_data_init(&share->lock, &lock, NULL);
return(rc);
}
/*
Closes the file.
SYNOPSIS
close();
IMPLEMENTATION:
We first close this storage engines file handle to the archive and
then remove our reference count to the table (and possibly free it
as well).
RETURN
0 ok
1 Error
*/
int ha_archive::close(void)
{
int rc= 0;
destroy_record_buffer(record_buffer);
/* First close stream */
if (archive_reader_open == true)
{
if (azclose(&archive))
rc= 1;
}
/* then also close share */
rc|= free_share();
return(rc);
}
/*
We create our data file here. The format is pretty simple.
You can read about the format of the data file above.
Unlike other storage engines we do not "pack" our data. Since we
are about to do a general compression, packing would just be a waste of
CPU time. If the table has blobs they are written after the row in the order
of creation.
*/
int ArchiveEngine::doCreateTable(Session *,
const char *table_name,
Table& table_arg,
drizzled::message::Table& proto)
{
char name_buff[FN_REFLEN];
int error= 0;
azio_stream create_stream; /* Archive file we are working with */
uint64_t auto_increment_value;
string serialized_proto;
auto_increment_value= proto.options().auto_increment_value();
for (uint32_t key= 0; key < table_arg.sizeKeys(); key++)
{
KEY *pos= table_arg.key_info+key;
KEY_PART_INFO *key_part= pos->key_part;
KEY_PART_INFO *key_part_end= key_part + pos->key_parts;
for (; key_part != key_part_end; key_part++)
{
Field *field= key_part->field;
if (!(field->flags & AUTO_INCREMENT_FLAG))
{
error= -1;
goto error;
}
}
}
/*
We reuse name_buff since it is available.
*/
fn_format(name_buff, table_name, "", ARZ,
MY_REPLACE_EXT | MY_UNPACK_FILENAME);
my_errno= 0;
if (azopen(&create_stream, name_buff, O_CREAT|O_RDWR,
AZ_METHOD_BLOCK) == 0)
{
error= errno;
goto error2;
}
proto.SerializeToString(&serialized_proto);
if (azwrite_frm(&create_stream, serialized_proto.c_str(),
serialized_proto.length()))
goto error2;
if (proto.options().has_comment())
{
int write_length;
write_length= azwrite_comment(&create_stream,
proto.options().comment().c_str(),
proto.options().comment().length());
if (write_length < 0)
{
error= errno;
goto error2;
}
}
/*
Yes you need to do this, because the starting value
for the autoincrement may not be zero.
*/
create_stream.auto_increment= auto_increment_value ?
auto_increment_value - 1 : 0;
if (azclose(&create_stream))
{
error= errno;
goto error2;
}
return(0);
error2:
unlink(name_buff);
error:
/* Return error number, if we got one */
return(error ? error : -1);
}
/*
This is where the actual row is written out.
*/
int ha_archive::real_write_row(unsigned char *buf, azio_stream *writer)
{
off_t written;
unsigned int r_pack_length;
/* We pack the row for writing */
r_pack_length= pack_row(buf);
written= azwrite_row(writer, record_buffer->buffer, r_pack_length);
if (written != r_pack_length)
{
return(-1);
}
if (!delayed_insert || !bulk_insert)
share->dirty= true;
return(0);
}
/*
Calculate max length needed for row. This includes
the bytes required for the length in the header.
*/
uint32_t ha_archive::max_row_length(const unsigned char *)
{
uint32_t length= (uint32_t)(table->getRecordLength() + table->sizeFields()*2);
length+= ARCHIVE_ROW_HEADER_SIZE;
uint32_t *ptr, *end;
for (ptr= table->getBlobField(), end=ptr + table->sizeBlobFields();
ptr != end ;
ptr++)
{
length += 2 + ((Field_blob*)table->field[*ptr])->get_length();
}
return length;
}
unsigned int ha_archive::pack_row(unsigned char *record)
{
unsigned char *ptr;
if (fix_rec_buff(max_row_length(record)))
return(HA_ERR_OUT_OF_MEM);
/* Copy null bits */
memcpy(record_buffer->buffer, record, table->s->null_bytes);
ptr= record_buffer->buffer + table->s->null_bytes;
for (Field **field=table->field ; *field ; field++)
{
if (!((*field)->is_null()))
ptr= (*field)->pack(ptr, record + (*field)->offset(record));
}
return((unsigned int) (ptr - record_buffer->buffer));
}
/*
Look at ha_archive::open() for an explanation of the row format.
Here we just write out the row.
Wondering about start_bulk_insert()? We don't implement it for
archive since it optimizes for lots of writes. The only save
for implementing start_bulk_insert() is that we could skip
setting dirty to true each time.
*/
int ha_archive::write_row(unsigned char *buf)
{
int rc;
unsigned char *read_buf= NULL;
uint64_t temp_auto;
unsigned char *record= table->record[0];
if (share->crashed)
return(HA_ERR_CRASHED_ON_USAGE);
ha_statistic_increment(&SSV::ha_write_count);
pthread_mutex_lock(&share->mutex);
if (share->archive_write_open == false)
if (init_archive_writer())
return(HA_ERR_CRASHED_ON_USAGE);
if (table->next_number_field && record == table->record[0])
{
KEY *mkey= &table->s->key_info[0]; // We only support one key right now
update_auto_increment();
temp_auto= table->next_number_field->val_int();
/*
We don't support decremening auto_increment. They make the performance
just cry.
*/
if (temp_auto <= share->archive_write.auto_increment &&
mkey->flags & HA_NOSAME)
{
rc= HA_ERR_FOUND_DUPP_KEY;
goto error;
}
else
{
if (temp_auto > share->archive_write.auto_increment)
stats.auto_increment_value=
(share->archive_write.auto_increment= temp_auto) + 1;
}
}
/*
Notice that the global auto_increment has been increased.
In case of a failed row write, we will never try to reuse the value.
*/
share->rows_recorded++;
rc= real_write_row(buf, &(share->archive_write));
error:
pthread_mutex_unlock(&share->mutex);
if (read_buf)
free((unsigned char*) read_buf);
return(rc);
}
void ha_archive::get_auto_increment(uint64_t, uint64_t, uint64_t,
uint64_t *first_value, uint64_t *nb_reserved_values)
{
*nb_reserved_values= UINT64_MAX;
*first_value= share->archive_write.auto_increment + 1;
}
/* Initialized at each key walk (called multiple times unlike rnd_init()) */
int ha_archive::index_init(uint32_t keynr, bool)
{
active_index= keynr;
return(0);
}
/*
No indexes, so if we get a request for an index search since we tell
the optimizer that we have unique indexes, we scan
*/
int ha_archive::index_read(unsigned char *buf, const unsigned char *key,
uint32_t key_len, enum ha_rkey_function find_flag)
{
int rc;
rc= index_read_idx(buf, active_index, key, key_len, find_flag);
return(rc);
}
int ha_archive::index_read_idx(unsigned char *buf, uint32_t index, const unsigned char *key,
uint32_t key_len, enum ha_rkey_function)
{
int rc;
bool found= 0;
KEY *mkey= &table->s->key_info[index];
current_k_offset= mkey->key_part->offset;
current_key= key;
current_key_len= key_len;
rc= rnd_init(true);
if (rc)
goto error;
while (!(get_row(&archive, buf)))
{
if (!memcmp(current_key, buf + current_k_offset, current_key_len))
{
found= 1;
break;
}
}
if (found)
return(0);
error:
return(rc ? rc : HA_ERR_END_OF_FILE);
}
int ha_archive::index_next(unsigned char * buf)
{
bool found= 0;
while (!(get_row(&archive, buf)))
{
if (!memcmp(current_key, buf+current_k_offset, current_key_len))
{
found= 1;
break;
}
}
return(found ? 0 : HA_ERR_END_OF_FILE);
}
/*
All calls that need to scan the table start with this method. If we are told
that it is a table scan we rewind the file to the beginning, otherwise
we assume the position will be set.
*/
int ha_archive::rnd_init(bool scan)
{
if (share->crashed)
return(HA_ERR_CRASHED_ON_USAGE);
init_archive_reader();
/* We rewind the file so that we can read from the beginning if scan */
if (scan)
{
if (read_data_header(&archive))
return(HA_ERR_CRASHED_ON_USAGE);
}
return(0);
}
/*
This is the method that is used to read a row. It assumes that the row is
positioned where you want it.
*/
int ha_archive::get_row(azio_stream *file_to_read, unsigned char *buf)
{
int rc;
if (file_to_read->version == ARCHIVE_VERSION)
rc= get_row_version3(file_to_read, buf);
else
rc= -1;
return(rc);
}
/* Reallocate buffer if needed */
bool ha_archive::fix_rec_buff(unsigned int length)
{
assert(record_buffer->buffer);
if (length > record_buffer->length)
{
unsigned char *newptr;
if (!(newptr= (unsigned char *)realloc(record_buffer->buffer, length)))
return(1);
record_buffer->buffer= newptr;
record_buffer->length= length;
}
assert(length <= record_buffer->length);
return(0);
}
int ha_archive::unpack_row(azio_stream *file_to_read, unsigned char *record)
{
unsigned int read;
int error;
const unsigned char *ptr;
read= azread_row(file_to_read, &error);
ptr= (const unsigned char *)file_to_read->row_ptr;
if (error || read == 0)
{
return(-1);
}
/* Copy null bits */
memcpy(record, ptr, table->getNullBytes());
ptr+= table->getNullBytes();
for (Field **field=table->field ; *field ; field++)
{
if (!((*field)->is_null()))
{
ptr= (*field)->unpack(record + (*field)->offset(table->record[0]), ptr);
}
}
return(0);
}
int ha_archive::get_row_version3(azio_stream *file_to_read, unsigned char *buf)
{
int returnable= unpack_row(file_to_read, buf);
return(returnable);
}
/*
Called during ORDER BY. Its position is either from being called sequentially
or by having had ha_archive::rnd_pos() called before it is called.
*/
int ha_archive::rnd_next(unsigned char *buf)
{
int rc;
if (share->crashed)
return(HA_ERR_CRASHED_ON_USAGE);
if (!scan_rows)
return(HA_ERR_END_OF_FILE);
scan_rows--;
ha_statistic_increment(&SSV::ha_read_rnd_next_count);
current_position= aztell(&archive);
rc= get_row(&archive, buf);
table->status=rc ? STATUS_NOT_FOUND: 0;
return(rc);
}
/*
Thanks to the table bool is_ordered this will be called after
each call to ha_archive::rnd_next() if an ordering of the rows is
needed.
*/
void ha_archive::position(const unsigned char *)
{
my_store_ptr(ref, ref_length, current_position);
return;
}
/*
This is called after a table scan for each row if the results of the
scan need to be ordered. It will take *pos and use it to move the
cursor in the file so that the next row that is called is the
correctly ordered row.
*/
int ha_archive::rnd_pos(unsigned char * buf, unsigned char *pos)
{
ha_statistic_increment(&SSV::ha_read_rnd_next_count);
current_position= (my_off_t)my_get_ptr(pos, ref_length);
if (azseek(&archive, (size_t)current_position, SEEK_SET) == (size_t)(-1L))
return(HA_ERR_CRASHED_ON_USAGE);
return(get_row(&archive, buf));
}
/*
This method repairs the meta file. It does this by walking the datafile and
rewriting the meta file. Currently it does this by calling optimize with
the extended flag.
*/
int ha_archive::repair()
{
int rc= optimize();
if (rc)
return(HA_ERR_CRASHED_ON_REPAIR);
share->crashed= false;
return(0);
}
/*
The table can become fragmented if data was inserted, read, and then
inserted again. What we do is open up the file and recompress it completely.
*/
int ha_archive::optimize()
{
int rc= 0;
azio_stream writer;
char writer_filename[FN_REFLEN];
init_archive_reader();
// now we close both our writer and our reader for the rename
if (share->archive_write_open)
{
azclose(&(share->archive_write));
share->archive_write_open= false;
}
char* proto_string;
proto_string= (char*)malloc(sizeof(char) * archive.frm_length);
if (proto_string == NULL)
{
return ENOMEM;
}
azread_frm(&archive, proto_string);
/* Lets create a file to contain the new data */
fn_format(writer_filename, share->table_name.c_str(), "", ARN,
MY_REPLACE_EXT | MY_UNPACK_FILENAME);
if (!(azopen(&writer, writer_filename, O_CREAT|O_RDWR, AZ_METHOD_BLOCK)))
{
free(proto_string);
return(HA_ERR_CRASHED_ON_USAGE);
}
azwrite_frm(&writer, proto_string, archive.frm_length);
/*
An extended rebuild is a lot more effort. We open up each row and re-record it.
Any dead rows are removed (aka rows that may have been partially recorded).
As of Archive format 3, this is the only type that is performed, before this
version it was just done on T_EXTEND
*/
if (1)
{
/*
Now we will rewind the archive file so that we are positioned at the
start of the file.
*/
azflush(&archive, Z_SYNC_FLUSH);
rc= read_data_header(&archive);
/*
On success of writing out the new header, we now fetch each row and
insert it into the new archive file.
*/
if (!rc)
{
uint64_t x;
uint64_t rows_restored;
share->rows_recorded= 0;
stats.auto_increment_value= 1;
share->archive_write.auto_increment= 0;
rows_restored= archive.rows;
for (x= 0; x < rows_restored ; x++)
{
rc= get_row(&archive, table->record[0]);
if (rc != 0)
break;
real_write_row(table->record[0], &writer);
/*
Long term it should be possible to optimize this so that
it is not called on each row.
*/
if (table->found_next_number_field)
{
Field *field= table->found_next_number_field;
/* Since we will need to use field to translate, we need to flip its read bit */
field->setReadSet();
uint64_t auto_value=
(uint64_t) field->val_int(table->record[0] +
field->offset(table->record[0]));
if (share->archive_write.auto_increment < auto_value)
stats.auto_increment_value=
(share->archive_write.auto_increment= auto_value) + 1;
}
}
share->rows_recorded= (ha_rows)writer.rows;
}
if (rc && rc != HA_ERR_END_OF_FILE)
{
goto error;
}
}
azclose(&writer);
share->dirty= false;
azclose(&archive);
// make the file we just wrote be our data file
rc = my_rename(writer_filename,share->data_file_name,MYF(0));
free(proto_string);
return(rc);
error:
free(proto_string);
azclose(&writer);
return(rc);
}
/*
Below is an example of how to setup row level locking.
*/
THR_LOCK_DATA **ha_archive::store_lock(Session *session,
THR_LOCK_DATA **to,
enum thr_lock_type lock_type)
{
delayed_insert= false;
if (lock_type != TL_IGNORE && lock.type == TL_UNLOCK)
{
/*
Here is where we get into the guts of a row level lock.
If TL_UNLOCK is set
If we are not doing a LOCK Table or DISCARD/IMPORT
TABLESPACE, then allow multiple writers
*/
if ((lock_type >= TL_WRITE_CONCURRENT_INSERT &&
lock_type <= TL_WRITE)
&& !session_tablespace_op(session))
lock_type = TL_WRITE_ALLOW_WRITE;
/*
In queries of type INSERT INTO t1 SELECT ... FROM t2 ...
MySQL would use the lock TL_READ_NO_INSERT on t2, and that
would conflict with TL_WRITE_ALLOW_WRITE, blocking all inserts
to t2. Convert the lock to a normal read lock to allow
concurrent inserts to t2.
*/
if (lock_type == TL_READ_NO_INSERT)
lock_type = TL_READ;
lock.type=lock_type;
}
*to++= &lock;
return to;
}
/*
Hints for optimizer, see ha_tina for more information
*/
int ha_archive::info(uint32_t flag)
{
/*
If dirty, we lock, and then reset/flush the data.
I found that just calling azflush() doesn't always work.
*/
pthread_mutex_lock(&share->mutex);
if (share->dirty == true)
{
azflush(&(share->archive_write), Z_SYNC_FLUSH);
share->rows_recorded= share->archive_write.rows;
share->dirty= false;
if (share->version < global_version)
{
share->version_rows= share->rows_recorded;
share->version= global_version;
}
}
/*
This should be an accurate number now, though bulk and delayed inserts can
cause the number to be inaccurate.
*/
stats.records= share->rows_recorded;
pthread_mutex_unlock(&share->mutex);
scan_rows= stats.records;
stats.deleted= 0;
/* Costs quite a bit more to get all information */
if (flag & HA_STATUS_TIME)
{
struct stat file_stat; // Stat information for the data file
stat(share->data_file_name, &file_stat);
stats.mean_rec_length= table->getRecordLength()+ buffer.alloced_length();
stats.data_file_length= file_stat.st_size;
stats.create_time= file_stat.st_ctime;
stats.update_time= file_stat.st_mtime;
stats.max_data_file_length= share->rows_recorded * stats.mean_rec_length;
}
stats.delete_length= 0;
stats.index_file_length=0;
if (flag & HA_STATUS_AUTO)
{
init_archive_reader();
pthread_mutex_lock(&share->mutex);
azflush(&archive, Z_SYNC_FLUSH);
pthread_mutex_unlock(&share->mutex);
stats.auto_increment_value= archive.auto_increment + 1;
}
return(0);
}
/*
This method tells us that a bulk insert operation is about to occur. We set
a flag which will keep write_row from saying that its data is dirty. This in
turn will keep selects from causing a sync to occur.
Basically, yet another optimizations to keep compression working well.
*/
void ha_archive::start_bulk_insert(ha_rows rows)
{
if (!rows || rows >= ARCHIVE_MIN_ROWS_TO_USE_BULK_INSERT)
bulk_insert= true;
return;
}
/*
Other side of start_bulk_insert, is end_bulk_insert. Here we turn off the bulk insert
flag, and set the share dirty so that the next select will call sync for us.
*/
int ha_archive::end_bulk_insert()
{
bulk_insert= false;
share->dirty= true;
return(0);
}
/*
We cancel a truncate command. The only way to delete an archive table is to drop it.
This is done for security reasons. In a later version we will enable this by
allowing the user to select a different row format.
*/
int ha_archive::delete_all_rows()
{
return(HA_ERR_WRONG_COMMAND);
}
/*
Simple scan of the tables to make sure everything is ok.
*/
int ha_archive::check(Session* session)
{
int rc= 0;
const char *old_proc_info;
uint64_t x;
old_proc_info= get_session_proc_info(session);
set_session_proc_info(session, "Checking table");
/* Flush any waiting data */
pthread_mutex_lock(&share->mutex);
azflush(&(share->archive_write), Z_SYNC_FLUSH);
pthread_mutex_unlock(&share->mutex);
/*
Now we will rewind the archive file so that we are positioned at the
start of the file.
*/
init_archive_reader();
azflush(&archive, Z_SYNC_FLUSH);
read_data_header(&archive);
for (x= 0; x < share->archive_write.rows; x++)
{
rc= get_row(&archive, table->record[0]);
if (rc != 0)
break;
}
set_session_proc_info(session, old_proc_info);
if ((rc && rc != HA_ERR_END_OF_FILE))
{
share->crashed= false;
return(HA_ADMIN_CORRUPT);
}
else
{
return(HA_ADMIN_OK);
}
}
archive_record_buffer *ha_archive::create_record_buffer(unsigned int length)
{
archive_record_buffer *r;
if (!(r= (archive_record_buffer*) malloc(sizeof(archive_record_buffer))))
{
return(NULL);
}
r->length= (int)length;
if (!(r->buffer= (unsigned char*) malloc(r->length)))
{
free((char*) r);
return(NULL);
}
return(r);
}
void ha_archive::destroy_record_buffer(archive_record_buffer *r)
{
free((char*) r->buffer);
free((char*) r);
return;
}
static DRIZZLE_SYSVAR_BOOL(aio, archive_use_aio,
PLUGIN_VAR_NOCMDOPT,
"Whether or not to use asynchronous IO.",
NULL, NULL, true);
static struct st_mysql_sys_var* archive_system_variables[]= {
DRIZZLE_SYSVAR(aio),
NULL
};
drizzle_declare_plugin
{
"ARCHIVE",
"3.5",
"Brian Aker, MySQL AB",
"Archive storage engine",
PLUGIN_LICENSE_GPL,
archive_db_init, /* Plugin Init */
archive_db_done, /* Plugin Deinit */
NULL, /* status variables */
archive_system_variables, /* system variables */
NULL /* config options */
}
drizzle_declare_plugin_end;
|