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