C++ compilation.
[idzebra-moved-to-github.git] / isam / isam.c
1 /*
2  * Copyright (C) 1994-1999, Index Data
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: isam.c,v $
7  * Revision 1.26  1999-05-26 07:49:14  adam
8  * C++ compilation.
9  *
10  * Revision 1.25  1999/02/02 14:51:16  adam
11  * Updated WIN32 code specific sections. Changed header.
12  *
13  * Revision 1.24  1997/10/27 14:25:39  adam
14  * Fixed memory leaks.
15  *
16  * Revision 1.23  1997/09/17 12:19:20  adam
17  * Zebra version corresponds to YAZ version 1.4.
18  * Changed Zebra server so that it doesn't depend on global common_resource.
19  *
20  * Revision 1.22  1996/10/29 13:56:53  adam
21  * Include of zebrautl.h instead of alexutil.h.
22  *
23  * Revision 1.21  1996/03/29 14:11:47  quinn
24  * Change to is_merge
25  *
26  * Revision 1.20  1996/03/19  13:14:57  quinn
27  * Moved an xfree()
28  *
29  * Revision 1.19  1996/02/10  12:20:56  quinn
30  * *** empty log message ***
31  *
32  * Revision 1.18  1996/02/06  10:19:56  quinn
33  * Attempt at fixing bug. Not all blocks were read before they were unlinked
34  * prior to a remap operation.
35  *
36  * Revision 1.17  1995/12/06  15:48:44  quinn
37  * Fixed update-problem.
38  *
39  * Revision 1.16  1995/12/06  14:48:26  quinn
40  * Fixed some strange bugs.
41  *
42  * Revision 1.15  1995/12/06  09:59:45  quinn
43  * Fixed memory-consumption bug in memory.c
44  * Added more blocksizes to the default ISAM configuration.
45  *
46  * Revision 1.14  1995/11/24  17:26:19  quinn
47  * Mostly about making some ISAM stuff in the config file optional.
48  *
49  * Revision 1.13  1995/10/17  18:03:15  adam
50  * Commented out qsort in is_merge.
51  *
52  * Revision 1.12  1995/09/06  16:11:41  adam
53  * Keysize parameter to is_open (if non-zero).
54  *
55  * Revision 1.11  1995/09/04  12:33:46  adam
56  * Various cleanup. YAZ util used instead.
57  *
58  * Revision 1.10  1994/09/28  16:58:32  quinn
59  * Small mod.
60  *
61  * Revision 1.9  1994/09/28  12:56:15  quinn
62  * Added access functions (ISPT)
63  *
64  * Revision 1.8  1994/09/28  12:32:17  quinn
65  * Trivial
66  *
67  * Revision 1.7  1994/09/28  11:56:25  quinn
68  * Added sort of input to is_merge
69  *
70  * Revision 1.6  1994/09/28  11:29:33  quinn
71  * Added cmp parameter.
72  *
73  * Revision 1.5  1994/09/27  20:03:50  quinn
74  * Seems relatively bug-free.
75  *
76  * Revision 1.4  1994/09/26  17:11:29  quinn
77  * Trivial
78  *
79  * Revision 1.3  1994/09/26  17:06:35  quinn
80  * Back again...
81  *
82  * Revision 1.1  1994/09/12  08:02:13  quinn
83  * Not functional yet
84  *
85  */
86
87 #include <stdio.h>
88 #include <stdlib.h>
89 #include <string.h>
90 #include <ctype.h>
91
92 #include <zebrautl.h>
93 #include <bfile.h>
94 #include <isam.h>
95 #include "isutil.h"
96 #include "rootblk.h"
97 #include "keyops.h"
98
99 static ispt_struct *ispt_freelist = 0;
100
101 static struct
102 {
103     int total_merge_operations;
104     int total_items;
105     int dub_items_removed;
106     int new_items;
107     int failed_deletes;
108     int skipped_inserts;
109     int delete_insert_noop;
110     int delete_replace;
111     int deletes;
112     int remaps;
113     int block_jumps;
114     int tab_deletes;
115     int new_tables;
116 } statistics;
117
118 static ISPT ispt_alloc()
119 {
120     ISPT p;
121
122     if (ispt_freelist)
123     {
124         p = ispt_freelist;
125         ispt_freelist = ispt_freelist->next;
126     }
127     else
128         p = (ISPT) xmalloc(sizeof(ispt_struct));
129     return p;
130 }
131
132 static void ispt_free(ISPT pt)
133 {
134     pt->next = ispt_freelist;
135     ispt_freelist = pt;
136 }
137
138 static int splitargs(const char *s, char *bf[], int max)
139 {
140     int ct = 0;
141     for (;;)
142     {
143         while (*s && isspace(*s))
144             s++;
145         bf[ct] = (char *) s;
146         if (!*s)
147                 return ct;
148         ct++;
149         if (ct > max)
150         {
151             logf (LOG_WARN, "Ignoring extra args to is resource");
152             bf[ct] = '\0';
153             return(ct - 1);
154         }
155         while (*s && !isspace(*s))
156             s++;
157     }
158 }
159
160 /*
161  * Open isam file.
162  * Process resources.
163  */
164 ISAM is_open(BFiles bfs, const char *name,
165              int (*cmp)(const void *p1, const void *p2),
166              int writeflag, int keysize, Res res)
167 {
168     ISAM inew;
169     char *nm, *r, *pp[IS_MAX_BLOCKTYPES+1], m[2];
170     int num, size, rs, tmp, i;
171     is_type_header th;
172
173     logf (LOG_DEBUG, "is_open(%s, %s)", name, writeflag ? "RW" : "RDONLY");
174     if (writeflag)
175     {
176         statistics.total_merge_operations = 0;
177         statistics.total_items = 0;
178         statistics.dub_items_removed = 0;
179         statistics.new_items = 0;
180         statistics.failed_deletes = 0;
181         statistics.skipped_inserts = 0;
182         statistics.delete_insert_noop = 0;
183         statistics.delete_replace = 0;
184         statistics.deletes = 0;
185         statistics.remaps = 0;
186         statistics.new_tables = 0;
187         statistics.block_jumps = 0;
188         statistics.tab_deletes = 0;
189     }
190
191     inew = (ISAM) xmalloc(sizeof(*inew));
192     inew->writeflag = writeflag;
193     for (i = 0; i < IS_MAX_BLOCKTYPES; i++)
194         inew->types[i].index = 0;                        /* dummy */
195
196     /* determine number and size of blocktypes */
197     if (!(r = res_get_def(res,
198                           nm = strconcat(name, ".",
199                                          "blocktypes", 0), "64 512 4K 32K")) ||
200         !(num = splitargs(r, pp, IS_MAX_BLOCKTYPES)))
201     {
202         logf (LOG_FATAL, "Failed to locate resource %s", nm);
203         return 0;
204     }
205     inew->num_types = num;
206     for (i = 0; i < num; i++)
207     {
208         if ((rs = sscanf(pp[i], "%d%1[bBkKmM]", &size, m)) < 1)
209         {
210             logf (LOG_FATAL, "Error in resource %s: %s", r, pp[i]);
211             return 0;
212         }
213         if (rs == 1)
214                 *m = 'b';
215         switch (*m)
216         {
217                 case 'b': case 'B':
218                     inew->types[i].blocksize = size; break;
219                 case 'k': case 'K':
220                     inew->types[i].blocksize = size * 1024; break;
221                 case 'm': case 'M':
222                     inew->types[i].blocksize = size * 1048576; break;
223                 default:
224                     logf (LOG_FATAL, "Illegal size suffix: %c", *m);
225                     return 0;
226         }
227         inew->types[i].dbuf = (char *) xmalloc(inew->types[i].blocksize);
228         m[0] = 'A' + i;
229         m[1] = '\0';
230         if (!(inew->types[i].bf = bf_open(bfs, strconcat(name, m, 0), 
231             inew->types[i].blocksize, writeflag)))
232         {
233             logf (LOG_FATAL, "bf_open failed");
234             return 0;
235         }
236         if ((rs = is_rb_read(&inew->types[i], &th)) > 0)
237         {
238             if (th.blocksize != inew->types[i].blocksize)
239             {
240                 logf (LOG_FATAL, "File blocksize mismatch in %s", name);
241                 exit(1);
242             }
243             inew->types[i].freelist = th.freelist;
244             inew->types[i].top = th.top;
245         }
246         else if (writeflag) /* write dummy superblock to determine top */
247         {
248             if ((rs = is_rb_write(&inew->types[i], &th)) <=0)  /* dummy */
249             {
250                 logf (LOG_FATAL, "Failed to write initial superblock.");
251                 exit(1);
252             }
253             inew->types[i].freelist = -1;
254             inew->types[i].top = rs;
255         }
256         /* ELSE: this is an empty file opened in read-only mode. */
257     }
258     if (keysize > 0)
259         inew->keysize = keysize;
260     else
261     {
262         if (!(r = res_get_def(res, nm = strconcat(name, ".",
263                                                   "keysize", 0), "4")))
264         {
265             logf (LOG_FATAL, "Failed to locate resource %s", nm);
266             return 0;
267         }
268         if ((inew->keysize = atoi(r)) <= 0)
269         {
270             logf (LOG_FATAL, "Must specify positive keysize.");
271             return 0;
272         }
273     }
274
275     /* determine repack percent */
276     if (!(r = res_get_def(res, nm = strconcat(name, ".", "repack",
277                                               0), IS_DEF_REPACK_PERCENT)))
278     {
279         logf (LOG_FATAL, "Failed to locate resource %s", nm);
280         return 0;
281     }
282     inew->repack = atoi(r);
283
284     /* determine max keys/blocksize */
285     if (!(r = res_get_def(res,
286                           nm = strconcat(name, ".",
287                                          "maxkeys", 0), "50 640 10000")) ||
288         !(num = splitargs(r, pp, IS_MAX_BLOCKTYPES)))
289     {
290         logf (LOG_FATAL, "Failed to locate resource %s", nm);
291         return 0;
292     }
293     if (num < inew->num_types -1)
294     {
295         logf (LOG_FATAL, "Not enough elements in %s", nm);
296         return 0;
297     }
298     for (i = 0; i < num; i++)
299     {
300         if ((rs = sscanf(pp[i], "%d", &tmp)) < 1)
301         {
302             logf (LOG_FATAL, "Error in resource %s: %s", r, pp[i]);
303             return 0;
304         }
305         inew->types[i].max_keys = tmp;
306     }
307
308     /* determine max keys/block */
309     for (i = 0; i < inew->num_types; i++)
310     {
311         if (!inew->types[i].index)
312         {
313             inew->types[i].max_keys_block = (inew->types[i].blocksize - 2 *
314                 sizeof(int)) / inew->keysize;
315             inew->types[i].max_keys_block0 = (inew->types[i].blocksize - 3 *
316                 sizeof(int)) / inew->keysize;
317         }
318         else
319             inew->types[i].max_keys_block = inew->types[i].max_keys_block0 /
320                 inew->keysize;
321         if (inew->types[i].max_keys_block0 < 1)
322         {
323             logf (LOG_FATAL, "Blocksize too small in %s", name);
324             exit(1);
325         }
326     }
327
328     /* determine nice fill rates */
329     if (!(r = res_get_def(res,
330                           nm = strconcat(name, ".",
331                                          "nicefill", 0), "90 90 90 95")) ||
332         !(num = splitargs(r, pp, IS_MAX_BLOCKTYPES)))
333     {
334         logf (LOG_FATAL, "Failed to locate resource %s", nm);
335         return 0;
336     }
337     if (num < inew->num_types)
338     {
339         logf (LOG_FATAL, "Not enough elements in %s", nm);
340         return 0;
341     }
342     for (i = 0; i < num; i++)
343     {
344         if ((rs = sscanf(pp[i], "%d", &tmp)) < 1)
345         {
346             logf (LOG_FATAL, "Error in resource %s: %s", r, pp[i]);
347             return 0;
348         }
349         inew->types[i].nice_keys_block = (inew->types[i].max_keys_block0 * tmp) /
350             100;
351         if (inew->types[i].nice_keys_block < 1)
352                 inew->types[i].nice_keys_block = 1;
353     }
354
355     inew->cmp = cmp ? cmp : is_default_cmp;
356     return inew;
357 }
358
359 /*
360  * Close isam file.
361  */
362 int is_close(ISAM is)
363 {
364     int i;
365     is_type_header th;
366
367     logf (LOG_DEBUG, "is_close()");
368     for (i = 0; i < is->num_types; i++)
369     {
370         if (is->types[i].bf)
371         {
372             if (is->writeflag)
373             {
374                 th.blocksize = is->types[i].blocksize;
375                 th.keysize = is->keysize;
376                 th.freelist = is->types[i].freelist;
377                 th.top = is->types[i].top;
378                 if (is_rb_write(&is->types[i], &th) < 0)
379                 {
380                     logf (LOG_FATAL, "Failed to write headerblock");
381                     exit(1);
382                 }
383             }
384             bf_close(is->types[i].bf);
385         }
386     }
387     for (i = 0; i < is->num_types; i++)
388         xfree (is->types[i].dbuf);
389
390     if (is->writeflag)
391     {
392         logf(LOG_LOG, "ISAM statistics:");
393         logf(LOG_LOG, "total_merge_operations      %d",
394             statistics.total_merge_operations);
395         logf(LOG_LOG, "total_items                 %d", statistics.total_items);
396         logf(LOG_LOG, "dub_items_removed           %d",
397             statistics.dub_items_removed);
398         logf(LOG_LOG, "new_items                   %d", statistics.new_items);
399         logf(LOG_LOG, "failed_deletes              %d",
400             statistics.failed_deletes);
401         logf(LOG_LOG, "skipped_inserts             %d",
402             statistics.skipped_inserts);
403         logf(LOG_LOG, "delete_insert_noop          %d",
404             statistics.delete_insert_noop);
405         logf(LOG_LOG, "delete_replace              %d",
406             statistics.delete_replace);
407         logf(LOG_LOG, "delete                      %d", statistics.deletes);
408         logf(LOG_LOG, "remaps                      %d", statistics.remaps);
409         logf(LOG_LOG, "block_jumps                 %d", statistics.block_jumps);
410         logf(LOG_LOG, "tab_deletes                 %d", statistics.tab_deletes);
411     }
412     xfree(is);
413     return 0;
414 }
415
416 static ISAM_P is_address(int type, int pos)
417 {
418     ISAM_P r;
419
420     r = pos << 2;
421     r |= type;
422     return r;
423 }
424
425 ISAM_P is_merge(ISAM is, ISAM_P pos, int num, char *data)
426 {
427     is_mtable tab;
428     int res;
429     char keybuf[IS_MAX_RECORD];
430     int oldnum, oldtype, i;
431     char operation, *record;
432
433     statistics.total_merge_operations++;
434     statistics.total_items += num;
435     if (!pos)
436         statistics.new_tables++;
437
438     is_m_establish_tab(is, &tab, pos);
439     if (pos)
440         if (is_m_read_full(&tab, tab.data) < 0)
441         {
442             logf (LOG_FATAL, "read_full failed");
443             exit(1);
444         }
445     oldnum = tab.num_records;
446     oldtype = tab.pos_type;
447     while (num)
448     {
449         operation = *(data)++;
450         record = (char*) data;
451         data += is_keysize(is);
452         num--;
453         while (num && !memcmp(record - 1, data, is_keysize(tab.is) + 1))
454         {
455             data += 1 + is_keysize(is);
456             num--;
457             statistics.dub_items_removed++;
458         }
459         if ((res = is_m_seek_record(&tab, record)) > 0)  /* no match */
460         {
461             if (operation == KEYOP_INSERT)
462             {
463                 logf (LOG_DEBUG, "XXInserting new record.");
464                 is_m_write_record(&tab, record);
465                 statistics.new_items++;
466             }
467             else
468             {
469                 logf (LOG_DEBUG, "XXDeletion failed to find match.");
470                 statistics.failed_deletes++;
471             }
472         }
473         else /* match found */
474         {
475             if (operation == KEYOP_INSERT)
476             {
477                 logf (LOG_DEBUG, "XXSkipping insertion - match found.");
478                 statistics.skipped_inserts++;
479                 continue;
480             }
481             else if (operation == KEYOP_DELETE)
482             {
483                 /* try to avoid needlessly moving data */
484                 if (num && *(data) == KEYOP_INSERT)
485                 {
486                     /* next key is identical insert? - NOOP - skip it */
487                     if (!memcmp(record, data + 1, is_keysize(is)))
488                     {
489                         logf (LOG_DEBUG, "XXNoop delete. skipping.");
490                         data += 1 + is_keysize(is);
491                         num--;
492                         while (num && !memcmp(data, data + is_keysize(tab.is) +
493                             1, is_keysize(tab.is) + 1))
494                         {
495                             data += 1 + is_keysize(is);
496                             num--;
497                             statistics.dub_items_removed++;
498                         }
499                         statistics.delete_insert_noop++;
500                         continue;
501                     }
502                     /* else check if next key can fit in this position */
503                     if (is_m_peek_record(&tab, keybuf) &&
504                         (*is->cmp)(data + 1, keybuf) < 0)
505                     {
506                         logf (LOG_DEBUG, "XXReplacing record.");
507                         is_m_replace_record(&tab, data + 1);
508                         data += 1 + is_keysize(is);
509                         num--;
510                         while (num && !memcmp(data, data + is_keysize(tab.is) +
511                             1, is_keysize(tab.is) + 1))
512                         {
513                             data += 1 + is_keysize(is);
514                             num--;
515                             statistics.dub_items_removed++;
516                         }
517                         statistics.delete_replace++;
518                         continue;
519                     }
520                 }
521                 logf (LOG_DEBUG, "Deleting record.");
522                 is_m_delete_record(&tab);
523                 statistics.deletes++;
524             }
525         }
526     }
527     i = tab.pos_type;
528     while (i < tab.is->num_types - 1 && tab.num_records >
529         tab.is->types[i].max_keys)
530         i++;
531     if (i != tab.pos_type)
532     {
533         /* read remaining blocks */
534         for (; tab.cur_mblock; tab.cur_mblock = tab.cur_mblock->next)
535             if (tab.cur_mblock->state < IS_MBSTATE_CLEAN)
536                 is_m_read_full(&tab, tab.cur_mblock);
537         is_p_unmap(&tab);
538         tab.pos_type = i;
539         if (pos)
540             statistics.block_jumps++;
541     }
542     if (!oldnum || tab.pos_type != oldtype || (abs(oldnum - tab.num_records) *
543         100) / oldnum > tab.is->repack)
544     {
545         is_p_remap(&tab);
546         statistics.remaps++;
547     }
548     else
549         is_p_align(&tab);
550     if (tab.data)
551     {
552         is_p_sync(&tab);
553         pos = is_address(tab.pos_type, tab.data->diskpos);
554     }
555     else
556     {
557         pos = 0;
558         statistics.tab_deletes++;
559     }
560     is_m_release_tab(&tab);
561     return pos;
562 }
563
564 /*
565  * Locate a table of keys in an isam file. The ISPT is an individual
566  * position marker for that table.
567  */
568 ISPT is_position(ISAM is, ISAM_P pos)
569 {
570     ispt_struct *p;
571
572     p = ispt_alloc();
573     is_m_establish_tab(is, &p->tab, pos);
574     return p;
575 }
576
577 /*
578  * Release ISPT.
579  */
580 void is_pt_free(ISPT ip)
581 {
582     is_m_release_tab(&ip->tab);
583     ispt_free(ip);
584 }
585
586 /*
587  * Read a key from a table.
588  */
589 int is_readkey(ISPT ip, void *buf)
590 {
591     return is_m_read_record(&ip->tab, buf, 0);
592 }    
593
594 int is_numkeys(ISPT ip)
595 {
596     return is_m_num_records(&ip->tab);
597 }
598
599 void is_rewind(ISPT ip)
600 {
601     is_m_rewind(&ip->tab);
602 }