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