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