Fix memory handling of quries in result sets
[idzebra-moved-to-github.git] / index / zebraapi.c
1 /* $Id: zebraapi.c,v 1.105 2003-06-18 11:46:33 adam Exp $
2    Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003
3    Index Data Aps
4
5 This file is part of the Zebra server.
6
7 Zebra is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Zebra; see the file LICENSE.zebra.  If not, write to the
19 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.
21 */
22
23
24
25 #include <assert.h>
26 #include <stdio.h>
27 #ifdef WIN32
28 #include <io.h>
29 #include <process.h>
30 #include <direct.h>
31 #else
32 #include <unistd.h>
33 #endif
34
35 #include <yaz/diagbib1.h>
36 #include <yaz/pquery.h>
37 #include <yaz/sortspec.h>
38 #include "index.h"
39 #include <charmap.h>
40 #include "zebraapi.h"
41
42 /* simple asserts to validate the most essential input args */
43 #define ASSERTZH assert(zh && zh->service)
44 #define ASSERTZHRES assert(zh && zh->service && zh->res)
45 #define ASSERTZS assert(zs)
46
47 /* A simple log macro */
48 /* don't break with older yazen that lack log_app2 */
49 #ifdef LOG_APP2
50 #define LOG_API LOG_APP2
51 #else
52 #define LOG_API LOG_DEBUG
53 #endif
54
55 static Res zebra_open_res (ZebraHandle zh);
56 static void zebra_close_res (ZebraHandle zh);
57
58
59 static void zebra_chdir (ZebraService zs)
60 {
61     const char *dir ;
62     ASSERTZS;
63     yaz_log(LOG_API,"zebra_chdir");
64     dir = res_get (zs->global_res, "chdir");
65     if (!dir)
66         return;
67     logf (LOG_DEBUG, "chdir %s", dir);
68 #ifdef WIN32
69     _chdir(dir);
70 #else
71     chdir (dir);
72 #endif
73 }
74
75 static void zebra_flush_reg (ZebraHandle zh)
76 {
77     ASSERTZH;
78     yaz_log(LOG_API,"zebra_flush_reg");
79     zh->errCode=0;
80     zebraExplain_flush (zh->reg->zei, zh);
81     
82     extract_flushWriteKeys (zh);
83     zebra_index_merge (zh);
84 }
85
86 static struct zebra_register *zebra_register_open (ZebraService zs, 
87                                                    const char *name,
88                                                    int rw, int useshadow,
89                                                    Res res,
90                                                    const char *reg_path);
91 static void zebra_register_close (ZebraService zs, struct zebra_register *reg);
92
93 ZebraHandle zebra_open (ZebraService zs)
94 {
95     ZebraHandle zh;
96     const char *default_encoding;
97     ASSERTZS;
98     yaz_log(LOG_API,"zebra_open");
99
100     if (!zs)
101         return 0;
102
103     zh = (ZebraHandle) xmalloc (sizeof(*zh));
104     yaz_log (LOG_DEBUG, "zebra_open zs=%p returns %p", zs, zh);
105
106     zh->service = zs;
107     zh->reg = 0;          /* no register attached yet */
108     zh->sets = 0;
109     zh->destroyed = 0;
110     zh->errCode = 0;
111     zh->errString = 0;
112     zh->res = 0; 
113
114     zh->reg_name = xstrdup ("");
115     zh->path_reg = 0;
116     zh->num_basenames = 0;
117     zh->basenames = 0;
118
119     zh->trans_no = 0;
120     zh->trans_w_no = 0;
121
122     zh->lock_normal = 0;
123     zh->lock_shadow = 0;
124
125     zh->admin_databaseName = 0;
126
127     zh->shadow_enable = 1;
128
129     default_encoding = res_get_def(zs->global_res, "encoding", "ISO-8859-1");
130     zh->record_encoding = xstrdup (default_encoding);
131
132     zh->iconv_to_utf8 =
133         yaz_iconv_open ("UTF-8", default_encoding);
134     if (zh->iconv_to_utf8 == 0)
135         yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported",
136            default_encoding);
137     zh->iconv_from_utf8 =
138         yaz_iconv_open (default_encoding, "UTF-8");
139     if (zh->iconv_to_utf8 == 0)
140         yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported",
141            default_encoding);
142
143     zebra_mutex_cond_lock (&zs->session_lock);
144
145     zh->next = zs->sessions;
146     zs->sessions = zh;
147
148     zebra_mutex_cond_unlock (&zs->session_lock);
149
150     return zh;
151 }
152
153 ZebraService zebra_start (const char *configName)
154 {
155     Res res;
156
157     yaz_log(LOG_API|LOG_LOG,"zebra_start %s",configName);
158
159     if ((res = res_open (configName, 0)))
160     {
161         ZebraService zh = xmalloc (sizeof(*zh));
162
163         yaz_log (LOG_DEBUG, "Read resources `%s'", configName);
164         
165         zh->global_res = res;
166         zh->configName = xstrdup(configName);
167         zh->sessions = 0;
168         
169         zebra_chdir (zh);
170         
171         zebra_mutex_cond_init (&zh->session_lock);
172         if (!res_get (zh->global_res, "passwd"))
173             zh->passwd_db = NULL;
174         else
175         {
176             zh->passwd_db = passwd_db_open ();
177             if (!zh->passwd_db)
178                 logf (LOG_WARN|LOG_ERRNO, "passwd_db_open failed");
179             else
180                 passwd_db_file (zh->passwd_db,
181                                 res_get (zh->global_res, "passwd"));
182         }
183         zh->path_root = res_get (zh->global_res, "root");
184         return zh;
185     }
186     return 0;
187 }
188
189 static
190 struct zebra_register *zebra_register_open (ZebraService zs, const char *name,
191                                             int rw, int useshadow, Res res,
192                                             const char *reg_path)
193 {
194     struct zebra_register *reg;
195     int record_compression = REC_COMPRESS_NONE;
196     char *recordCompression = 0;
197
198     ASSERTZS;
199     
200     reg = xmalloc (sizeof(*reg));
201
202     assert (name);
203     reg->name = xstrdup (name);
204
205     reg->seqno = 0;
206     reg->last_val = 0;
207
208     assert (res);
209
210     yaz_log (LOG_LOG|LOG_API, "zebra_register_open rw = %d useshadow=%d p=%p,n=%s,rp=%s",
211              rw, useshadow, reg, name, reg_path ? reg_path : "(none)");
212     
213     reg->dh = data1_createx (DATA1_FLAG_XML);
214     if (!reg->dh)
215         return 0;
216     reg->bfs = bfs_create (res_get (res, "register"), reg_path);
217     if (!reg->bfs)
218     {
219         data1_destroy(reg->dh);
220         return 0;
221     }
222     if (useshadow)
223         bf_cache (reg->bfs, res_get (res, "shadow"));
224     data1_set_tabpath (reg->dh, res_get_def(res, "profilePath",
225                                             DEFAULT_PROFILE_PATH));
226     data1_set_tabroot (reg->dh, reg_path);
227     reg->recTypes = recTypes_init (reg->dh);
228     recTypes_default_handlers (reg->recTypes);
229
230     reg->zebra_maps = zebra_maps_open (res, reg_path);
231     reg->rank_classes = NULL;
232
233     reg->key_buf = 0;
234
235     reg->keys.buf_max = 0;
236     reg->keys.buf = 0;
237     reg->sortKeys.buf = 0;
238     reg->sortKeys.buf_max = 0;
239
240     reg->records = 0;
241     reg->dict = 0;
242     reg->sortIdx = 0;
243     reg->isams = 0;
244     reg->matchDict = 0;
245     reg->isam = 0;
246     reg->isamc = 0;
247     reg->isamd = 0;
248     reg->isamb = 0;
249     reg->zei = 0;
250     reg->matchDict = 0;
251     reg->key_file_no = 0;
252     
253     zebraRankInstall (reg, rank1_class);
254     zebraRankInstall (reg, rankzv_class);
255     zebraRankInstall (reg, rankliv_class);
256
257     recordCompression = res_get_def (res, "recordCompression", "none");
258     if (!strcmp (recordCompression, "none"))
259         record_compression = REC_COMPRESS_NONE;
260     if (!strcmp (recordCompression, "bzip2"))
261         record_compression = REC_COMPRESS_BZIP2;
262
263     if (!(reg->records = rec_open (reg->bfs, rw, record_compression)))
264     {
265         logf (LOG_WARN, "rec_open");
266         return 0;
267     }
268     if (rw)
269     {
270         reg->matchDict = dict_open (reg->bfs, GMATCH_DICT, 20, 1, 0);
271     }
272     if (!(reg->dict = dict_open (reg->bfs, FNAME_DICT, 40, rw, 0)))
273     {
274         logf (LOG_WARN, "dict_open");
275         return 0;
276     }
277     if (!(reg->sortIdx = sortIdx_open (reg->bfs, rw)))
278     {
279         logf (LOG_WARN, "sortIdx_open");
280         return 0;
281     }
282     if (res_get_match (res, "isam", "s", ISAM_DEFAULT))
283     {
284         struct ISAMS_M_s isams_m;
285         if (!(reg->isams = isams_open (reg->bfs, FNAME_ISAMS, rw,
286                                       key_isams_m(res, &isams_m))))
287         {
288             logf (LOG_WARN, "isams_open");
289             return 0;
290         }
291     }
292     if (res_get_match (res, "isam", "i", ISAM_DEFAULT))
293     {
294         if (!(reg->isam = is_open (reg->bfs, FNAME_ISAM, key_compare, rw,
295                                   sizeof (struct it_key), res)))
296         {
297             logf (LOG_WARN, "is_open");
298             return 0;
299         }
300     }
301     if (res_get_match (res, "isam", "c", ISAM_DEFAULT))
302     {
303         struct ISAMC_M_s isamc_m;
304         if (!(reg->isamc = isc_open (reg->bfs, FNAME_ISAMC,
305                                     rw, key_isamc_m(res, &isamc_m))))
306         {
307             logf (LOG_WARN, "isc_open");
308             return 0;
309         }
310     }
311     if (res_get_match (res, "isam", "d", ISAM_DEFAULT))
312     {
313         struct ISAMD_M_s isamd_m;
314         
315         if (!(reg->isamd = isamd_open (reg->bfs, FNAME_ISAMD,
316                                       rw, key_isamd_m(res, &isamd_m))))
317         {
318             logf (LOG_WARN, "isamd_open");
319             return 0;
320         }
321     }
322     if (res_get_match (res, "isam", "b", ISAM_DEFAULT))
323     {
324         struct ISAMC_M_s isamc_m;
325         
326         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
327                                        rw, key_isamc_m(res, &isamc_m), 0)))
328         {
329             logf (LOG_WARN, "isamb_open");
330             return 0;
331         }
332     }
333     if (res_get_match (res, "isam", "bc", ISAM_DEFAULT))
334     {
335         struct ISAMC_M_s isamc_m;
336         
337         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
338                                        rw, key_isamc_m(res, &isamc_m), 1)))
339         {
340             logf (LOG_WARN, "isamb_open");
341             return 0;
342         }
343     }
344     if (res_get_match (res, "isam", "null", ISAM_DEFAULT))
345     {
346         struct ISAMC_M_s isamc_m;
347         
348         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
349                                        rw, key_isamc_m(res, &isamc_m), -1)))
350         {
351             logf (LOG_WARN, "isamb_open");
352             return 0;
353         }
354     }
355     reg->zei = zebraExplain_open (reg->records, reg->dh,
356                                   res, rw, reg,
357                                   explain_extract);
358     if (!reg->zei)
359     {
360         logf (LOG_WARN, "Cannot obtain EXPLAIN information");
361         return 0;
362     }
363     reg->active = 2;
364     yaz_log (LOG_DEBUG, "zebra_register_open ok p=%p", reg);
365     return reg;
366 }
367
368 void zebra_admin_shutdown (ZebraHandle zh)
369 {
370     ASSERTZH;
371     yaz_log(LOG_API,"zebra_admin_shutdown");
372     zh->errCode=0;
373
374     zebra_mutex_cond_lock (&zh->service->session_lock);
375     zh->service->stop_flag = 1;
376     zebra_mutex_cond_unlock (&zh->service->session_lock);
377 }
378
379 void zebra_admin_start (ZebraHandle zh)
380 {
381     ZebraService zs;
382     ASSERTZH;
383     yaz_log(LOG_API,"zebra_admin_start");
384     zh->errCode=0;
385     zs = zh->service;
386     zebra_mutex_cond_lock (&zs->session_lock);
387     zebra_mutex_cond_unlock (&zs->session_lock);
388 }
389
390 static void zebra_register_close (ZebraService zs, struct zebra_register *reg)
391 {
392     ASSERTZS;
393     yaz_log(LOG_LOG|LOG_API, "zebra_register_close p=%p", reg);
394     reg->stop_flag = 0;
395     zebra_chdir (zs);
396     if (reg->records)
397     {
398         zebraExplain_close (reg->zei);
399         dict_close (reg->dict);
400         if (reg->matchDict)
401             dict_close (reg->matchDict);
402         sortIdx_close (reg->sortIdx);
403         if (reg->isams)
404             isams_close (reg->isams);
405         if (reg->isam)
406             is_close (reg->isam);
407         if (reg->isamc)
408             isc_close (reg->isamc);
409         if (reg->isamd)
410             isamd_close (reg->isamd);
411         if (reg->isamb)
412             isamb_close (reg->isamb);
413         rec_close (&reg->records);
414     }
415
416     recTypes_destroy (reg->recTypes);
417     zebra_maps_close (reg->zebra_maps);
418     zebraRankDestroy (reg);
419     bfs_destroy (reg->bfs);
420     data1_destroy (reg->dh);
421
422     xfree (reg->sortKeys.buf);
423     xfree (reg->keys.buf);
424
425     xfree (reg->key_buf);
426     xfree (reg->name);
427     xfree (reg);
428 }
429
430 void zebra_stop(ZebraService zs)
431 {
432     if (!zs)
433         return ;
434     yaz_log (LOG_LOG|LOG_API, "zebra_stop");
435
436     while (zs->sessions)
437     {
438         zebra_close (zs->sessions);
439     }
440         
441     zebra_mutex_cond_destroy (&zs->session_lock);
442
443     if (zs->passwd_db)
444         passwd_db_close (zs->passwd_db);
445
446     res_close (zs->global_res);
447     xfree (zs->configName);
448     xfree (zs->path_root);
449     xfree (zs);
450 }
451
452 void zebra_close (ZebraHandle zh)
453 {
454     ZebraService zs;
455     struct zebra_session **sp;
456     int i;
457
458     yaz_log(LOG_API,"zebra_close");
459     if (!zh)
460         return;
461     ASSERTZH;
462     zh->errCode=0;
463     
464     zs = zh->service;
465     yaz_log (LOG_DEBUG, "zebra_close zh=%p", zh);
466     if (!zh)
467         return ;
468     resultSetDestroy (zh, -1, 0, 0);
469
470     if (zh->reg)
471         zebra_register_close (zh->service, zh->reg);
472     zebra_close_res (zh);
473
474     xfree (zh->record_encoding);
475
476     for (i = 0; i < zh->num_basenames; i++)
477         xfree (zh->basenames[i]);
478     xfree (zh->basenames);
479
480     if (zh->iconv_to_utf8 != 0)
481         yaz_iconv_close (zh->iconv_to_utf8);
482     if (zh->iconv_from_utf8 != 0)
483         yaz_iconv_close (zh->iconv_from_utf8);
484
485     xfree (zh->admin_databaseName);
486     zebra_mutex_cond_lock (&zs->session_lock);
487     zebra_lock_destroy (zh->lock_normal);
488     zebra_lock_destroy (zh->lock_shadow);
489     sp = &zs->sessions;
490     while (1)
491     {
492         assert (*sp);
493         if (*sp == zh)
494         {
495             *sp = (*sp)->next;
496             break;
497         }
498         sp = &(*sp)->next;
499     }
500     zebra_mutex_cond_unlock (&zs->session_lock);
501     xfree (zh->reg_name);
502     zh->service=0; /* more likely to trigger an assert */
503     xfree (zh);
504 }
505
506 struct map_baseinfo {
507     ZebraHandle zh;
508     NMEM mem;
509     int num_bases;
510     char **basenames;
511     int new_num_bases;
512     char **new_basenames;
513     int new_num_max;
514 };
515
516 static Res zebra_open_res (ZebraHandle zh)
517 {
518     Res res = 0;
519     char fname[512];
520     ASSERTZH;
521     zh->errCode=0;
522
523     if (zh->path_reg)
524     {
525         sprintf (fname, "%.200s/zebra.cfg", zh->path_reg);
526         res = res_open (fname, zh->service->global_res);
527         if (!res)
528             res = zh->service->global_res;
529     }
530     else if (*zh->reg_name == 0)
531     {
532         res = zh->service->global_res;
533     }
534     else
535     {
536         yaz_log (LOG_WARN, "no register root specified");
537         return 0;  /* no path for register - fail! */
538     }
539     return res;
540 }
541
542 static void zebra_close_res (ZebraHandle zh)
543 {
544     ASSERTZH;
545     zh->errCode=0;
546     if (zh->res != zh->service->global_res)
547         res_close (zh->res);
548     zh->res = 0;
549 }
550
551 static int zebra_select_register (ZebraHandle zh, const char *new_reg)
552 {
553     ASSERTZH;
554     zh->errCode=0;
555     if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
556         return 0;
557     if (!zh->res)
558     {
559         assert (zh->reg == 0);
560         assert (*zh->reg_name == 0);
561     }
562     else
563     {
564         if (zh->reg)
565         {
566             resultSetInvalidate (zh);
567             zebra_register_close (zh->service, zh->reg);
568             zh->reg = 0;
569         }
570         zebra_close_res(zh);
571     }
572     xfree (zh->reg_name);
573     zh->reg_name = xstrdup (new_reg);
574
575     xfree (zh->path_reg);
576     zh->path_reg = 0;
577     if (zh->service->path_root)
578     {
579         zh->path_reg = xmalloc (strlen(zh->service->path_root) + 
580                                 strlen(zh->reg_name) + 3);
581         strcpy (zh->path_reg, zh->service->path_root);
582         if (*zh->reg_name)
583         {
584             strcat (zh->path_reg, "/");
585             strcat (zh->path_reg, zh->reg_name);
586         }
587     }
588     zh->res = zebra_open_res (zh);
589     
590     if (zh->lock_normal)
591         zebra_lock_destroy (zh->lock_normal);
592     zh->lock_normal = 0;
593
594     if (zh->lock_shadow)
595         zebra_lock_destroy (zh->lock_shadow);
596     zh->lock_shadow = 0;
597
598     if (zh->res)
599     {
600         char fname[512];
601         const char *lock_area  =res_get (zh->res, "lockDir");
602         
603         if (!lock_area && zh->path_reg)
604             res_put (zh->res, "lockDir", zh->path_reg);
605         sprintf (fname, "norm.%s.LCK", zh->reg_name);
606         zh->lock_normal =
607             zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
608         
609         sprintf (fname, "shadow.%s.LCK", zh->reg_name);
610         zh->lock_shadow =
611             zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
612
613     }
614     return 1;
615 }
616
617 void map_basenames_func (void *vp, const char *name, const char *value)
618 {
619     struct map_baseinfo *p = (struct map_baseinfo *) vp;
620     int i, no;
621     char fromdb[128], todb[8][128];
622     
623     no =
624         sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
625                 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
626                 todb[5], todb[6], todb[7]);
627     if (no < 2)
628         return ;
629     no--;
630     for (i = 0; i<p->num_bases; i++)
631         if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
632         {
633             p->basenames[i] = 0;
634             for (i = 0; i < no; i++)
635             {
636                 if (p->new_num_bases == p->new_num_max)
637                     return;
638                 p->new_basenames[(p->new_num_bases)++] = 
639                     nmem_strdup (p->mem, todb[i]);
640             }
641             return;
642         }
643 }
644
645 void map_basenames (ZebraHandle zh, ODR stream,
646                     int *num_bases, char ***basenames)
647 {
648     struct map_baseinfo info;
649     struct map_baseinfo *p = &info;
650     int i;
651     ASSERTZH;
652     yaz_log(LOG_API,"map_basenames ");
653     zh->errCode=0;
654
655     info.zh = zh;
656     info.num_bases = *num_bases;
657     info.basenames = *basenames;
658     info.new_num_max = 128;
659     info.new_num_bases = 0;
660     info.new_basenames = (char **)
661         odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
662     info.mem = stream->mem;
663
664     res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
665     
666     for (i = 0; i<p->num_bases; i++)
667         if (p->basenames[i] && p->new_num_bases < p->new_num_max)
668         {
669             p->new_basenames[(p->new_num_bases)++] = 
670                 nmem_strdup (p->mem, p->basenames[i]);
671         }
672     *num_bases = info.new_num_bases;
673     *basenames = info.new_basenames;
674     for (i = 0; i<*num_bases; i++)
675         logf (LOG_LOG, "base %s", (*basenames)[i]);
676 }
677
678 int zebra_select_database (ZebraHandle zh, const char *basename)
679 {
680     ASSERTZH;
681     yaz_log(LOG_API,"zebra_select_database %s",basename);
682     zh->errCode=0;
683     return zebra_select_databases (zh, 1, &basename);
684 }
685
686 int zebra_select_databases (ZebraHandle zh, int num_bases,
687                             const char **basenames)
688 {
689     int i;
690     const char *cp;
691     int len = 0;
692     char *new_reg = 0;
693     ASSERTZH;
694     yaz_log(LOG_API,"zebra_select_databases n=%d [0]=%s",
695                     num_bases,basenames[0]);
696     zh->errCode=0;
697     
698     if (num_bases < 1)
699     {
700         zh->errCode = 23;
701         return -1;
702     }
703     for (i = 0; i < zh->num_basenames; i++)
704         xfree (zh->basenames[i]);
705     xfree (zh->basenames);
706     
707     zh->num_basenames = num_bases;
708     zh->basenames = xmalloc (zh->num_basenames * sizeof(*zh->basenames));
709     for (i = 0; i < zh->num_basenames; i++)
710         zh->basenames[i] = xstrdup (basenames[i]);
711
712     cp = strrchr(basenames[0], '/');
713     if (cp)
714     {
715         len = cp - basenames[0];
716         new_reg = xmalloc (len + 1);
717         memcpy (new_reg, basenames[0], len);
718         new_reg[len] = '\0';
719     }
720     else
721         new_reg = xstrdup ("");
722     for (i = 1; i<num_bases; i++)
723     {
724         const char *cp1;
725
726         cp1 = strrchr (basenames[i], '/');
727         if (cp)
728         {
729             if (!cp1)
730             {
731                 zh->errCode = 23;
732                 return -1;
733             }
734             if (len != cp1 - basenames[i] ||
735                 memcmp (basenames[i], new_reg, len))
736             {
737                 zh->errCode = 23;
738                 return -1;
739             }
740         }
741         else
742         {
743             if (cp1)
744             {
745                 zh->errCode = 23;
746                 return -1;
747             }
748         }
749     }
750     zebra_select_register (zh, new_reg);
751     xfree (new_reg);
752     if (!zh->res)
753     {
754         zh->errCode = 109;
755         return -1;
756     }
757     if (!zh->lock_normal || !zh->lock_shadow)
758     {
759         zh->errCode = 2;
760         return -1;
761     }
762     return 0;
763 }
764
765 void zebra_search_RPN (ZebraHandle zh, ODR o,
766                        Z_RPNQuery *query, const char *setname, int *hits)
767 {
768     ASSERTZH;
769     yaz_log(LOG_API,"zebra_search_rpn");
770     zh->errCode=0;
771     zh->hits = 0;
772     *hits = 0;
773
774     if (zebra_begin_read (zh))
775         return;
776
777     zebra_livcode_transform(zh, query);
778
779     resultSetAddRPN (zh, odr_extract_mem(o), query, 
780                      zh->num_basenames, zh->basenames, setname);
781
782     zebra_end_read (zh);
783
784     *hits = zh->hits;
785 }
786
787 void zebra_records_retrieve (ZebraHandle zh, ODR stream,
788                              const char *setname, Z_RecordComposition *comp,
789                              oid_value input_format, int num_recs,
790                              ZebraRetrievalRecord *recs)
791 {
792     ZebraPosSet poset;
793     int i, *pos_array;
794     ASSERTZH;
795     yaz_log(LOG_API,"zebra_records_retrieve n=%d",num_recs);
796     zh->errCode=0;
797
798     if (!zh->res)
799     {
800         zh->errCode = 30;
801         zh->errString = odr_strdup (stream, setname);
802         return;
803     }
804     
805     zh->errCode = 0;
806
807     if (zebra_begin_read (zh))
808         return;
809
810     pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
811     for (i = 0; i<num_recs; i++)
812         pos_array[i] = recs[i].position;
813     poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
814     if (!poset)
815     {
816         logf (LOG_DEBUG, "zebraPosSetCreate error");
817         zh->errCode = 30;
818         zh->errString = nmem_strdup (stream->mem, setname);
819     }
820     else
821     {
822         for (i = 0; i<num_recs; i++)
823         {
824             if (poset[i].term)
825             {
826                 recs[i].errCode = 0;
827                 recs[i].format = VAL_SUTRS;
828                 recs[i].len = strlen(poset[i].term);
829                 recs[i].buf = poset[i].term;
830                 recs[i].base = poset[i].db;
831             }
832             else if (poset[i].sysno)
833             {
834                 recs[i].errCode =
835                     zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
836                                         stream, input_format, comp,
837                                         &recs[i].format, &recs[i].buf,
838                                         &recs[i].len,
839                                         &recs[i].base);
840                 recs[i].errString = NULL;
841             }
842             else
843             {
844                 char num_str[20];
845
846                 sprintf (num_str, "%d", pos_array[i]);  
847                 zh->errCode = 13;
848                 zh->errString = odr_strdup (stream, num_str);
849                 break;
850             }
851         }
852         zebraPosSetDestroy (zh, poset, num_recs);
853     }
854     zebra_end_read (zh);
855     xfree (pos_array);
856 }
857
858 void zebra_scan (ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
859                  oid_value attributeset,
860                  int *position, int *num_entries, ZebraScanEntry **entries,
861                  int *is_partial)
862 {
863     ASSERTZH;
864     yaz_log(LOG_API,"zebra_scan");
865     zh->errCode=0;
866     if (zebra_begin_read (zh))
867     {
868         *entries = 0;
869         *num_entries = 0;
870         return;
871     }
872     rpn_scan (zh, stream, zapt, attributeset,
873               zh->num_basenames, zh->basenames, position,
874               num_entries, entries, is_partial, 0, 0);
875     zebra_end_read (zh);
876 }
877
878 void zebra_sort (ZebraHandle zh, ODR stream,
879                  int num_input_setnames, const char **input_setnames,
880                  const char *output_setname, Z_SortKeySpecList *sort_sequence,
881                  int *sort_status)
882 {
883     ASSERTZH;
884     yaz_log(LOG_API,"zebra_sort");
885     zh->errCode=0;
886     if (zebra_begin_read (zh))
887         return;
888     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
889                    output_setname, sort_sequence, sort_status);
890     zebra_end_read(zh);
891 }
892
893 int zebra_deleleResultSet(ZebraHandle zh, int function,
894                           int num_setnames, char **setnames,
895                           int *statuses)
896 {
897     int i, status;
898     ASSERTZH;
899     yaz_log(LOG_API,"zebra_deleleResultSet n=%d",num_setnames);
900     zh->errCode=0;
901     if (zebra_begin_read(zh))
902         return Z_DeleteStatus_systemProblemAtTarget;
903     switch (function)
904     {
905     case Z_DeleteRequest_list:
906         resultSetDestroy (zh, num_setnames, setnames, statuses);
907         break;
908     case Z_DeleteRequest_all:
909         resultSetDestroy (zh, -1, 0, statuses);
910         break;
911     }
912     zebra_end_read (zh);
913     status = Z_DeleteStatus_success;
914     for (i = 0; i<num_setnames; i++)
915         if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
916             status = statuses[i];
917     return status;
918 }
919
920 int zebra_errCode (ZebraHandle zh)
921 {
922     if (zh)
923     {
924         yaz_log(LOG_API,"zebra_errCode: %d",zh->errCode);
925         return zh->errCode;
926     }
927     yaz_log(LOG_API,"zebra_errCode: o");
928     return 0; 
929 }
930
931 const char *zebra_errString (ZebraHandle zh)
932 {
933     const char *e="";
934     if (zh)
935         e= diagbib1_str (zh->errCode);
936     yaz_log(LOG_API,"zebra_errString: %s",e);
937     return e;
938 }
939
940 char *zebra_errAdd (ZebraHandle zh)
941 {
942     char *a="";
943     if (zh)
944         a= zh->errString;
945     yaz_log(LOG_API,"zebra_errAdd: %s",a);
946     return a;
947 }
948
949 int zebra_auth (ZebraHandle zh, const char *user, const char *pass)
950 {
951     ZebraService zs;
952     ASSERTZH;
953     yaz_log(LOG_API,"zebra_auth u=%s p=%s",user,pass);
954     zh->errCode=0;
955     zs= zh->service;
956     if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
957     {
958         logf(LOG_APP,"AUTHOK:%s", user?user:"ANONYMOUS");
959         return 0;
960     }
961
962     logf(LOG_APP,"AUTHFAIL:%s", user?user:"ANONYMOUS");
963     return 1;
964 }
965
966 void zebra_admin_import_begin (ZebraHandle zh, const char *database,
967                                const char *record_type)
968 {
969     ASSERTZH;
970     yaz_log(LOG_API,"zebra_admin_import_begin db=%s rt=%s", 
971                      database, record_type);
972     zh->errCode=0;
973     if (zebra_select_database(zh, database))
974         return;
975     zebra_begin_trans (zh, 1);
976     xfree (zh->admin_databaseName);
977     zh->admin_databaseName = xstrdup(database);
978 }
979
980 void zebra_admin_import_end (ZebraHandle zh)
981 {
982     ASSERTZH;
983     yaz_log(LOG_API,"zebra_admin_import_end");
984     zh->errCode=0;
985     zebra_end_trans (zh);
986 }
987
988 void zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
989 {
990     int sysno;
991     int i;
992     ASSERTZH;
993     yaz_log(LOG_API,"zebra_admin_import_segment");
994     zh->errCode=0;
995     for (i = 0; i<segment->num_segmentRecords; i++)
996     {
997         Z_NamePlusRecord *npr = segment->segmentRecords[i];
998         const char *databaseName = npr->databaseName;
999
1000         if (!databaseName)
1001             databaseName = zh->admin_databaseName;
1002         printf ("--------------%d--------------------\n", i);
1003         if (npr->which == Z_NamePlusRecord_intermediateFragment)
1004         {
1005             Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
1006             if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
1007             {
1008                 Odr_oct *oct = fragment->u.notExternallyTagged;
1009                 printf ("%.*s", (oct->len > 100 ? 100 : oct->len) ,
1010                         oct->buf);
1011                 
1012                 sysno = 0;
1013                 extract_rec_in_mem (zh, "grs.sgml",
1014                                     oct->buf, oct->len,
1015                                     databaseName,
1016                                     0 /* delete_flag */,
1017                                     0 /* test_mode */,
1018                                     &sysno /* sysno */,
1019                                     1 /* store_keys */,
1020                                     1 /* store_data */,
1021                                     0 /* match criteria */);
1022             }
1023         }
1024     }
1025 }
1026
1027 int zebra_admin_exchange_record (ZebraHandle zh,
1028                                  const char *database,
1029                                  const char *rec_buf,
1030                                  size_t rec_len,
1031                                  const char *recid_buf, size_t recid_len,
1032                                  int action)
1033 {
1034     int sysno = 0;
1035     char *rinfo = 0;
1036     char recid_z[256];
1037     ASSERTZH;
1038     yaz_log(LOG_API,"zebra_admin_exchange_record db=%s ac=%d",
1039                     database, action);
1040     zh->errCode=0;
1041
1042     if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
1043         return -1;
1044     memcpy (recid_z, recid_buf, recid_len);
1045     recid_z[recid_len] = 0;
1046
1047     rinfo = dict_lookup (zh->reg->matchDict, recid_z);
1048     if (rinfo)
1049     {
1050         if (action == 1)  /* fail if insert */
1051             return -1;
1052         memcpy (&sysno, rinfo+1, sizeof(sysno));
1053     }
1054     else
1055     {
1056         if (action == 2 || action == 3) /* fail if delete or update */
1057             return -1;
1058     }
1059     extract_rec_in_mem (zh, "grs.sgml", rec_buf, rec_len, database,
1060                         action == 3 ? 1 : 0 /* delete flag */,
1061                         0, &sysno, 1, 1, 0);
1062     if (action == 1)
1063     {
1064         dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
1065     }
1066     else if (action == 3)
1067     {
1068         dict_delete (zh->reg->matchDict, recid_z);
1069     }
1070     return 0;
1071 }
1072
1073 void zebra_create_database (ZebraHandle zh, const char *database)
1074 {
1075     ZebraService zs;
1076     ASSERTZH;
1077     yaz_log(LOG_API,"zebra_admin_create");
1078     zh->errCode=0;
1079
1080     if (zebra_select_database (zh, database))
1081         return;
1082     if (zebra_begin_trans (zh, 1))
1083         return;
1084
1085     zs = zh->service;
1086     /* announce database */
1087     if (zebraExplain_newDatabase (zh->reg->zei, database, 0 
1088                                   /* explainDatabase */))
1089     {
1090         zh->errCode = 224;
1091         zh->errString = "database already exist";
1092     }
1093     zebra_end_trans (zh);
1094 }
1095
1096 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1097                        const char *input_str, int input_len,
1098                        char *output_str, int output_len)
1099 {
1100     WRBUF wrbuf;
1101     ASSERTZH;
1102     yaz_log(LOG_API,"zebra_string_norm ");
1103     zh->errCode=0;
1104     if (!zh->reg->zebra_maps)
1105         return -1;
1106     wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1107                           input_str, input_len);
1108     if (!wrbuf)
1109         return -2;
1110     if (wrbuf_len(wrbuf) >= output_len)
1111         return -3;
1112     if (wrbuf_len(wrbuf))
1113         memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1114     output_str[wrbuf_len(wrbuf)] = '\0';
1115     return wrbuf_len(wrbuf);
1116 }
1117
1118
1119 void zebra_set_state (ZebraHandle zh, int val, int seqno)
1120 {
1121     char state_fname[256];
1122     char *fname;
1123     long p = getpid();
1124     FILE *f;
1125     ASSERTZH;
1126     yaz_log(LOG_API,"zebra_set_state v=%d seq=%d", val, seqno);
1127     zh->errCode=0;
1128
1129     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1130     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1131     f = fopen (fname, "w");
1132
1133     yaz_log (LOG_DEBUG, "%c %d %ld", val, seqno, p);
1134     fprintf (f, "%c %d %ld\n", val, seqno, p);
1135     fclose (f);
1136     xfree (fname);
1137 }
1138
1139 void zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1140 {
1141     char state_fname[256];
1142     char *fname;
1143     FILE *f;
1144
1145     ASSERTZH;
1146     yaz_log(LOG_API,"zebra_get_state ");
1147     zh->errCode=0;
1148     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1149     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1150     f = fopen (fname, "r");
1151     *val = 'o';
1152     *seqno = 0;
1153
1154     if (f)
1155     {
1156         fscanf (f, "%c %d", val, seqno);
1157         fclose (f);
1158     }
1159     xfree (fname);
1160 }
1161
1162 int zebra_begin_read (ZebraHandle zh)
1163 {
1164     return zebra_begin_trans(zh, 0);
1165 }
1166
1167 void zebra_end_read (ZebraHandle zh)
1168 {
1169     zebra_end_trans(zh);
1170 }
1171
1172 int zebra_begin_trans (ZebraHandle zh, int rw)
1173 {
1174     yaz_log(LOG_LOG, "zebra_begin_trans rw=%d trans=%d", rw, zh->trans_no);
1175     if (!zh->res)
1176     {
1177         zh->errCode = 2;
1178         zh->errString = "zebra_begin_trans: no database selected";
1179         return -1;
1180     }
1181     ASSERTZHRES;
1182     yaz_log(LOG_API,"zebra_begin_trans rw=%d",rw);
1183     assert (zh->res);
1184     if (rw)
1185     {
1186         int pass;
1187         int seqno = 0;
1188         char val = '?';
1189         const char *rval = 0;
1190         
1191         (zh->trans_no++);
1192         if (zh->trans_w_no)
1193             return 0;
1194         if (zh->trans_no != 1)
1195         {
1196             zh->errCode = 2;
1197             zh->errString = "zebra_begin_trans: write trans not allowed within read trans";
1198             return -1;
1199         }
1200         if (zh->reg)
1201         {
1202             resultSetInvalidate (zh);
1203             zebra_register_close (zh->service, zh->reg);
1204         }
1205         zh->trans_w_no = zh->trans_no;
1206
1207         zh->errCode=0;
1208         
1209         zh->records_inserted = 0;
1210         zh->records_updated = 0;
1211         zh->records_deleted = 0;
1212         zh->records_processed = 0;
1213         
1214 #if HAVE_SYS_TIMES_H
1215         times (&zh->tms1);
1216 #endif
1217         /* lock */
1218         if (zh->shadow_enable)
1219             rval = res_get (zh->res, "shadow");
1220         
1221         for (pass = 0; pass < 2; pass++)
1222         {
1223             if (rval)
1224             {
1225                 zebra_lock_r (zh->lock_normal);
1226                 zebra_lock_w (zh->lock_shadow);
1227             }
1228             else
1229             {
1230                 zebra_lock_w (zh->lock_normal);
1231                 zebra_lock_w (zh->lock_shadow);
1232             }
1233             
1234             zebra_get_state (zh, &val, &seqno);
1235             if (val == 'c')
1236             {
1237                 yaz_log (LOG_LOG, "previous transaction didn't finish commit");
1238                 zebra_unlock (zh->lock_shadow);
1239                 zebra_unlock (zh->lock_normal);
1240                 zebra_commit (zh);
1241                 continue;
1242             }
1243             else if (val == 'd')
1244             {
1245                 if (rval)
1246                 {
1247                     BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1248                                              zh->path_reg);
1249                     yaz_log (LOG_LOG, "previous transaction didn't reach commit");
1250                     bf_commitClean (bfs, rval);
1251                     bfs_destroy (bfs);
1252             }
1253                 else
1254                 {
1255                     yaz_log (LOG_WARN, "your previous transaction didn't finish");
1256                 }
1257             }
1258             break;
1259         }
1260         if (pass == 2)
1261         {
1262             yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
1263             abort();
1264             return -1;
1265         }
1266         zebra_set_state (zh, 'd', seqno);
1267         
1268         zh->reg = zebra_register_open (zh->service, zh->reg_name,
1269                                        1, rval ? 1 : 0, zh->res,
1270                                        zh->path_reg);
1271         if (zh->reg)
1272             zh->reg->seqno = seqno;
1273         else
1274         {
1275             zebra_set_state (zh, 'o', seqno);
1276             
1277             zebra_unlock (zh->lock_shadow);
1278             zebra_unlock (zh->lock_normal);
1279
1280             zh->trans_no--;
1281             zh->trans_w_no = 0;
1282
1283             zh->errCode = 2;
1284             zh->errString = "zebra_begin_trans: cannot open register";
1285             yaz_log(LOG_FATAL, zh->errString);
1286             return -1;
1287         }
1288     }
1289     else
1290     {
1291         int dirty = 0;
1292         char val;
1293         int seqno;
1294         
1295         (zh->trans_no)++;
1296         
1297         if (zh->trans_no != 1)
1298         {
1299             zebra_flush_reg (zh);
1300             return 0;
1301         }
1302         zh->errCode=0;
1303 #if HAVE_SYS_TIMES_H
1304         times (&zh->tms1);
1305 #endif
1306         if (!zh->res)
1307         {
1308             (zh->trans_no)--;
1309             zh->errCode = 109;
1310             return -1;
1311         }
1312         if (!zh->lock_normal || !zh->lock_shadow)
1313         {
1314             (zh->trans_no)--;
1315             zh->errCode = 2;
1316             return -1;
1317         }
1318         zebra_get_state (zh, &val, &seqno);
1319         if (val == 'd')
1320             val = 'o';
1321         
1322         if (!zh->reg)
1323             dirty = 1;
1324         else if (seqno != zh->reg->seqno)
1325         {
1326             yaz_log (LOG_LOG, "reopen seqno cur/old %d/%d",
1327                      seqno, zh->reg->seqno);
1328             dirty = 1;
1329         }
1330         else if (zh->reg->last_val != val)
1331         {
1332             yaz_log (LOG_LOG, "reopen last cur/old %d/%d",
1333                      val, zh->reg->last_val);
1334             dirty = 1;
1335         }
1336         if (!dirty)
1337             return 0;
1338         
1339         if (val == 'c')
1340             zebra_lock_r (zh->lock_shadow);
1341         else
1342             zebra_lock_r (zh->lock_normal);
1343         
1344         if (zh->reg)
1345             zebra_register_close (zh->service, zh->reg);
1346         zh->reg = zebra_register_open (zh->service, zh->reg_name,
1347                                        0, val == 'c' ? 1 : 0,
1348                                        zh->res, zh->path_reg);
1349         if (!zh->reg)
1350         {
1351             zebra_unlock (zh->lock_normal);
1352             zebra_unlock (zh->lock_shadow);
1353             zh->trans_no--;
1354             zh->errCode = 109;
1355             return -1;
1356         }
1357         zh->reg->last_val = val;
1358         zh->reg->seqno = seqno;
1359     }
1360     return 0;
1361 }
1362
1363 int zebra_end_trans (ZebraHandle zh)
1364 {
1365     ZebraTransactionStatus dummy;
1366     yaz_log(LOG_API,"zebra_end_trans");
1367     return zebra_end_transaction(zh, &dummy);
1368 }
1369
1370 int zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1371 {
1372     char val;
1373     int seqno;
1374     const char *rval;
1375
1376     ASSERTZH;
1377     yaz_log(LOG_API,"zebra_end_transaction");
1378
1379     status->processed = 0;
1380     status->inserted  = 0;
1381     status->updated   = 0;
1382     status->deleted   = 0;
1383     status->utime     = 0;
1384     status->stime     = 0;
1385
1386     if (!zh->res || !zh->reg)
1387     {
1388         zh->errCode = 2;
1389         zh->errString = "zebra_end_trans: no open transaction";
1390         return -1;
1391     }
1392     if (zh->trans_no != zh->trans_w_no)
1393     {
1394         zh->trans_no--;
1395         if (zh->trans_no != 0)
1396             return 0;
1397
1398         /* release read lock */
1399
1400         zebra_unlock (zh->lock_normal);
1401         zebra_unlock (zh->lock_shadow);
1402     }
1403     else
1404     {   /* release write lock */
1405         zh->trans_no--;
1406         zh->trans_w_no = 0;
1407         
1408         yaz_log (LOG_LOG, "zebra_end_trans");
1409         rval = res_get (zh->res, "shadow");
1410         
1411         zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1412         
1413         zebra_flush_reg (zh);
1414         
1415         resultSetInvalidate (zh);
1416
1417         zebra_register_close (zh->service, zh->reg);
1418         zh->reg = 0;
1419         
1420         yaz_log (LOG_LOG, "Records: %7d i/u/d %d/%d/%d", 
1421                  zh->records_processed, zh->records_inserted,
1422                  zh->records_updated, zh->records_deleted);
1423         
1424         status->processed = zh->records_processed;
1425         status->inserted = zh->records_inserted;
1426         status->updated = zh->records_updated;
1427         status->deleted = zh->records_deleted;
1428         
1429         zebra_get_state (zh, &val, &seqno);
1430         if (val != 'd')
1431         {
1432             BFiles bfs = bfs_create (rval, zh->path_reg);
1433             yaz_log (LOG_LOG, "deleting shadow stuff val=%c", val);
1434             bf_commitClean (bfs, rval);
1435             bfs_destroy (bfs);
1436         }
1437         if (!rval)
1438             seqno++;
1439         zebra_set_state (zh, 'o', seqno);
1440         
1441         zebra_unlock (zh->lock_shadow);
1442         zebra_unlock (zh->lock_normal);
1443         
1444     }
1445 #if HAVE_SYS_TIMES_H
1446     times (&zh->tms2);
1447     logf (LOG_LOG, "user/system: %ld/%ld",
1448           (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1449           (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1450     
1451     status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1452     status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1453 #endif
1454     return 0;
1455 }
1456
1457 void zebra_repository_update (ZebraHandle zh)
1458 {
1459     ASSERTZH;
1460     zh->errCode=0;
1461     logf (LOG_LOG|LOG_API, "updating %s", zh->rGroup.path);
1462     repositoryUpdate (zh);    
1463 }
1464
1465 void zebra_repository_delete (ZebraHandle zh)
1466 {
1467     ASSERTZH;
1468     zh->errCode=0;
1469     logf (LOG_LOG|LOG_API, "deleting %s", zh->rGroup.path);
1470     repositoryDelete (zh);
1471 }
1472
1473 void zebra_repository_show (ZebraHandle zh)
1474 {
1475     ASSERTZH;
1476     yaz_log(LOG_API,"zebra_repository_show");
1477     zh->errCode=0;
1478     repositoryShow (zh);
1479 }
1480
1481 static int zebra_commit_ex (ZebraHandle zh, int clean_only)
1482 {
1483     int seqno;
1484     char val;
1485     const char *rval;
1486     BFiles bfs;
1487     ASSERTZH;
1488     zh->errCode=0;
1489
1490     if (!zh->res)
1491     {
1492         zh->errCode = 109;
1493         return -1;
1494     }
1495     rval = res_get (zh->res, "shadow");    
1496     if (!rval)
1497     {
1498         logf (LOG_WARN, "Cannot perform commit");
1499         logf (LOG_WARN, "No shadow area defined");
1500         return 0;
1501     }
1502
1503     zebra_lock_w (zh->lock_normal);
1504     zebra_lock_r (zh->lock_shadow);
1505
1506     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1507
1508     zebra_get_state (zh, &val, &seqno);
1509
1510     if (rval && *rval)
1511         bf_cache (bfs, rval);
1512     if (bf_commitExists (bfs))
1513     {
1514         if (clean_only)
1515             zebra_set_state (zh, 'd', seqno);
1516         else
1517         {
1518             zebra_set_state (zh, 'c', seqno);
1519             
1520             logf (LOG_LOG, "commit start");
1521             bf_commitExec (bfs);
1522 #ifndef WIN32
1523             sync ();
1524 #endif
1525         }
1526         logf (LOG_LOG, "commit clean");
1527         bf_commitClean (bfs, rval);
1528         seqno++;
1529         zebra_set_state (zh, 'o', seqno);
1530     }
1531     else
1532     {
1533         logf (LOG_LOG, "nothing to commit");
1534     }
1535     bfs_destroy (bfs);
1536
1537     zebra_unlock (zh->lock_shadow);
1538     zebra_unlock (zh->lock_normal);
1539     return 0;
1540 }
1541
1542 int zebra_clean (ZebraHandle zh)
1543 {
1544     yaz_log(LOG_API,"zebra_clean");
1545     return zebra_commit_ex(zh, 1);
1546 }
1547
1548 int zebra_commit (ZebraHandle zh)
1549 {
1550     yaz_log(LOG_API,"zebra_commit");
1551     return zebra_commit_ex(zh, 0);
1552 }
1553
1554 int zebra_init (ZebraHandle zh)
1555 {
1556     const char *rval;
1557     BFiles bfs = 0;
1558     ASSERTZH;
1559     yaz_log(LOG_API,"zebra_init");
1560     zh->errCode=0;
1561
1562     if (!zh->res)
1563     {
1564         zh->errCode = 109;
1565         return -1;
1566     }
1567     rval = res_get (zh->res, "shadow");
1568
1569     bfs = bfs_create (res_get (zh->service->global_res, "register"),
1570                       zh->path_reg);
1571     if (rval && *rval)
1572         bf_cache (bfs, rval);
1573     
1574     bf_reset (bfs);
1575     bfs_destroy (bfs);
1576     zebra_set_state (zh, 'o', 0);
1577     return 0;
1578 }
1579
1580 int zebra_compact (ZebraHandle zh)
1581 {
1582     BFiles bfs;
1583     ASSERTZH;
1584     yaz_log(LOG_API,"zebra_compact");
1585     zh->errCode=0;
1586     if (!zh->res)
1587     {
1588         zh->errCode = 109;
1589         return -1;
1590     }
1591     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1592     inv_compact (bfs);
1593     bfs_destroy (bfs);
1594     return 0;
1595 }
1596
1597 int zebra_record_insert (ZebraHandle zh, const char *buf, int len)
1598 {
1599     int sysno = 0;
1600     ASSERTZH;
1601     yaz_log(LOG_API,"zebra_record_insert");
1602     zh->errCode=0;
1603     if (zebra_begin_trans (zh, 1))
1604         return 0;
1605     extract_rec_in_mem (zh, "grs.sgml",
1606                         buf, len,
1607                         "Default",  /* database */
1608                         0 /* delete_flag */,
1609                         0 /* test_mode */,
1610                         &sysno /* sysno */,
1611                         1 /* store_keys */,
1612                         1 /* store_data */,
1613                         0 /* match criteria */);
1614     if (zebra_end_trans (zh))
1615         return 0;
1616     return sysno;
1617 }
1618
1619 void zebra_set_group (ZebraHandle zh, struct recordGroup *rg)
1620 {
1621     ASSERTZH;
1622     yaz_log(LOG_API,"zebra_set_group");
1623     zh->errCode=0;
1624     memcpy (&zh->rGroup, rg, sizeof(*rg));
1625 }
1626
1627 void zebra_result (ZebraHandle zh, int *code, char **addinfo)
1628 {
1629     ASSERTZH;
1630     yaz_log(LOG_API,"zebra_result");
1631     *code = zh->errCode;
1632     *addinfo = zh->errString;
1633 }
1634
1635 void zebra_shadow_enable (ZebraHandle zh, int value)
1636 {
1637     ASSERTZH;
1638     yaz_log(LOG_API,"zebra_shadow_enable");
1639     zh->errCode=0;
1640     zh->shadow_enable = value;
1641 }
1642
1643 int zebra_record_encoding (ZebraHandle zh, const char *encoding)
1644 {
1645     ASSERTZH;
1646     yaz_log(LOG_API,"zebra_record_encoding");
1647     zh->errCode=0;
1648     xfree (zh->record_encoding);
1649
1650     /*
1651      * Fixme!
1652      */
1653
1654     if (zh->iconv_to_utf8 != 0)
1655         yaz_iconv_close(zh->iconv_to_utf8);
1656     if (zh->iconv_from_utf8 != 0)
1657         yaz_iconv_close(zh->iconv_from_utf8);
1658     
1659     zh->record_encoding = xstrdup (encoding);
1660     
1661     logf(LOG_DEBUG, "Reset record encoding: %s", encoding);
1662     
1663     zh->iconv_to_utf8 =
1664         yaz_iconv_open ("UTF-8", encoding);
1665     if (zh->iconv_to_utf8 == 0)
1666         yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1667     zh->iconv_from_utf8 =
1668         yaz_iconv_open (encoding, "UTF-8");
1669     if (zh->iconv_to_utf8 == 0)
1670         yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1671
1672     return 0;
1673 }
1674
1675 void zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1676 {
1677     ASSERTZH;
1678     yaz_log(LOG_API,"zebra_set_resource %s:%s",name,value);
1679     zh->errCode=0;
1680     res_put(zh->res, name, value);
1681 }
1682
1683 const char *zebra_get_resource(ZebraHandle zh,
1684                                const char *name, const char *defaultvalue)
1685 {
1686     const char *v;
1687     ASSERTZH;
1688     v= res_get_def( zh->res, name, (char *)defaultvalue);
1689     zh->errCode=0;
1690     yaz_log(LOG_API,"zebra_get_resource %s:%s",name,v);
1691     return v;
1692 }
1693
1694 /* moved from zebra_api_ext.c by pop */
1695
1696 int zebra_trans_no (ZebraHandle zh) {
1697   ASSERTZH;
1698   yaz_log(LOG_API,"zebra_trans_no");
1699   return (zh->trans_no);
1700 }
1701
1702
1703
1704 int zebra_get_shadow_enable (ZebraHandle zh) {
1705     yaz_log(LOG_API,"zebra_get_shadow_enable");
1706     return (zh->shadow_enable);
1707 }
1708
1709 void zebra_set_shadow_enable (ZebraHandle zh, int value) {
1710     yaz_log(LOG_API,"zebra_set_shadow_enable %d",value);
1711     zh->shadow_enable = value;
1712 }
1713
1714 void init_recordGroup (struct recordGroup *rg) {
1715     assert(rg);
1716     yaz_log(LOG_API,"init_recordGroup");
1717     rg->groupName = NULL;
1718     rg->databaseName = NULL;
1719     rg->path = NULL;
1720     rg->recordId = NULL;
1721     rg->recordType = NULL;
1722     rg->flagStoreData = -1;
1723     rg->flagStoreKeys = -1; 
1724     rg->flagRw = 1;
1725     rg->databaseNamePath = 0;
1726     rg->explainDatabase = 0; 
1727     rg->fileVerboseLimit = 100000; 
1728     rg->followLinks = -1;
1729
1730
1731
1732 /* This is from extract.c... it seems useful, when extract_rec_in mem is 
1733    called... and in general... Should be moved to somewhere else */
1734 void res_get_recordGroup (ZebraHandle zh,
1735                           struct recordGroup *rGroup,
1736                           const char *ext) {
1737   char gprefix[128];
1738   char ext_res[128]; 
1739     
1740   yaz_log(LOG_API,"res_get_recordGroup e=%s",ext);
1741   if (!rGroup->groupName || !*rGroup->groupName)
1742     *gprefix = '\0';
1743   else 
1744     sprintf (gprefix, "%s.", rGroup->groupName);
1745   
1746   /* determine file type - depending on extension */
1747   if (!rGroup->recordType) {
1748     sprintf (ext_res, "%srecordType.%s", gprefix, ext);
1749     if (!(rGroup->recordType = res_get (zh->res, ext_res))) {
1750       sprintf (ext_res, "%srecordType", gprefix);
1751       rGroup->recordType = res_get (zh->res, ext_res);
1752     }
1753   }
1754   /* determine match criteria */
1755   if (!rGroup->recordId) { 
1756     sprintf (ext_res, "%srecordId.%s", gprefix, ext);
1757     if (!(rGroup->recordId = res_get (zh->res, ext_res))) {
1758       sprintf (ext_res, "%srecordId", gprefix);
1759       rGroup->recordId = res_get (zh->res, ext_res);
1760     }
1761   } 
1762   
1763   /* determine database name */
1764   if (!rGroup->databaseName) {
1765     sprintf (ext_res, "%sdatabase.%s", gprefix, ext);
1766     if (!(rGroup->databaseName = res_get (zh->res, ext_res))) { 
1767       sprintf (ext_res, "%sdatabase", gprefix);
1768       rGroup->databaseName = res_get (zh->res, ext_res);
1769     }
1770   }
1771   if (!rGroup->databaseName)
1772     rGroup->databaseName = "Default";
1773
1774   /* determine if explain database */
1775   sprintf (ext_res, "%sexplainDatabase", gprefix);
1776   rGroup->explainDatabase =
1777     atoi (res_get_def (zh->res, ext_res, "0"));
1778
1779   /* storeData */
1780   if (rGroup->flagStoreData == -1) {
1781     const char *sval;
1782     sprintf (ext_res, "%sstoreData.%s", gprefix, ext);
1783     if (!(sval = res_get (zh->res, ext_res))) {
1784       sprintf (ext_res, "%sstoreData", gprefix);
1785       sval = res_get (zh->res, ext_res);
1786     }
1787     if (sval)
1788       rGroup->flagStoreData = atoi (sval);
1789   }
1790   if (rGroup->flagStoreData == -1)  rGroup->flagStoreData = 0;
1791
1792   /* storeKeys */
1793   if (rGroup->flagStoreKeys == -1)  {
1794     const char *sval;
1795     
1796     sprintf (ext_res, "%sstoreKeys.%s", gprefix, ext);
1797     sval = res_get (zh->res, ext_res);
1798     if (!sval) {
1799       sprintf (ext_res, "%sstoreKeys", gprefix);
1800       sval = res_get (zh->res, ext_res);
1801     }
1802     if (!sval)  sval = res_get (zh->res, "storeKeys");
1803     if (sval) rGroup->flagStoreKeys = atoi (sval);
1804   }
1805   if (rGroup->flagStoreKeys == -1) rGroup->flagStoreKeys = 0;
1806   
1807
1808
1809
1810 /* almost the same as zebra_records_retrieve ... but how did it work? 
1811    I mean for multiple records ??? CHECK ??? */
1812 void api_records_retrieve (ZebraHandle zh, ODR stream,
1813                            const char *setname, Z_RecordComposition *comp,
1814                            oid_value input_format, int num_recs,
1815                            ZebraRetrievalRecord *recs)
1816 {
1817     ZebraPosSet poset;
1818     int i, *pos_array;
1819     yaz_log(LOG_API,"api_records_retrieve s=%s n=%d",setname,num_recs);
1820
1821     if (!zh->res)
1822     {
1823         zh->errCode = 30;
1824         zh->errString = odr_strdup (stream, setname);
1825         return;
1826     }
1827     
1828     zh->errCode = 0; 
1829
1830     if (zebra_begin_read (zh))
1831         return;
1832
1833     pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
1834     for (i = 0; i<num_recs; i++)
1835         pos_array[i] = recs[i].position;
1836     poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
1837     if (!poset)
1838     {
1839         logf (LOG_DEBUG, "zebraPosSetCreate error");
1840         zh->errCode = 30;
1841         zh->errString = nmem_strdup (stream->mem, setname);
1842     }
1843     else
1844     {
1845         for (i = 0; i<num_recs; i++)
1846         {
1847             if (poset[i].term)
1848             {
1849                 recs[i].errCode = 0;
1850                 recs[i].format = VAL_SUTRS;
1851                 recs[i].len = strlen(poset[i].term);
1852                 recs[i].buf = poset[i].term;
1853                 recs[i].base = poset[i].db;
1854                 recs[i].sysno = 0;
1855             
1856             }
1857             else if (poset[i].sysno)
1858             {
1859               /* changed here ??? CHECK ??? */
1860               char *b;
1861                 recs[i].errCode =
1862                     zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
1863                                         stream, input_format, comp,
1864                                         &recs[i].format, 
1865                                         &b,
1866                                         &recs[i].len,
1867                                         &recs[i].base);
1868                 recs[i].buf = (char *) odr_malloc(stream,recs[i].len);
1869                 memcpy(recs[i].buf, b, recs[i].len);
1870                 recs[i].errString = 0; /* Hmmm !!! we should get this */ 
1871                 recs[i].sysno = poset[i].sysno;
1872                 recs[i].score = poset[i].score;
1873             }
1874             else
1875             {
1876                 char num_str[20];
1877
1878                 sprintf (num_str, "%d", pos_array[i]);  
1879                 zh->errCode = 13;
1880                 zh->errString = odr_strdup (stream, num_str);
1881                 break;
1882             }
1883
1884         }
1885         zebraPosSetDestroy (zh, poset, num_recs);
1886     }
1887     zebra_end_read (zh);
1888     xfree (pos_array);
1889 }
1890
1891
1892 /* ---------------------------------------------------------------------------
1893   Record insert(=update), delete 
1894
1895   If sysno is provided, then it's used to identify the reocord.
1896   If not, and match_criteria is provided, then sysno is guessed
1897   If not, and a record is provided, then sysno is got from there
1898 */
1899
1900 int zebra_insert_record (ZebraHandle zh, 
1901                          struct recordGroup *rGroup,
1902                          const char *recordType,
1903                          int sysno, const char *match, const char *fname,
1904                          const char *buf, int buf_size,
1905                          int force_update) /* This one is ignored */
1906  
1907 {
1908     int res;
1909     yaz_log(LOG_API,"zebra_insert_record sysno=%d",sysno);
1910
1911     if (buf_size < 1) buf_size = strlen(buf);
1912
1913     zebra_begin_trans(zh, 1);
1914     res=bufferExtractRecord (zh, buf, buf_size, rGroup, 
1915                              0, /* delete_flag  */
1916                              0, /* test_mode */
1917                              recordType,
1918                              &sysno,   
1919                              match, fname,
1920                              force_update, 
1921                              0); /* allow_update */
1922     zebra_end_trans(zh); 
1923     if (res < 0) return (res);
1924     return sysno; 
1925 }
1926
1927 int zebra_update_record (ZebraHandle zh, 
1928                          struct recordGroup *rGroup,
1929                          const char *recordType,
1930                          int sysno, const char *match, const char *fname,
1931                          const char *buf, int buf_size,
1932                          int force_update)
1933
1934 {
1935     int res;
1936     yaz_log(LOG_API,"zebra_update_record sysno=%d",sysno);
1937
1938     if (buf_size < 1) buf_size = strlen(buf);
1939
1940     zebra_begin_trans(zh, 1);
1941     res=bufferExtractRecord (zh, buf, buf_size, rGroup, 
1942                              0, /* delete_flag */
1943                              0, /* test_mode */
1944                              recordType,
1945                              &sysno,   
1946                              match, fname,
1947                              force_update, 
1948                              1); /* allow_update */
1949     zebra_end_trans(zh); 
1950     return sysno; 
1951 }
1952
1953
1954
1955 int zebra_delete_record (ZebraHandle zh, 
1956                          struct recordGroup *rGroup, 
1957                          const char *recordType,
1958                          int sysno, const char *match, const char *fname,
1959                          const char *buf, int buf_size,
1960                          int force_update) 
1961 {
1962     int res;
1963     yaz_log(LOG_API,"zebra_delete_record sysno=%d",sysno);
1964
1965     if (buf_size < 1) buf_size = strlen(buf);
1966
1967     zebra_begin_trans(zh, 1);
1968     res=bufferExtractRecord (zh, buf, buf_size, rGroup, 
1969                              1, /* delete_flag */
1970                              0, /* test_mode */
1971                              recordType,
1972                              &sysno,
1973                              match,fname,
1974                              force_update,
1975                              1); /* allow_update */
1976     zebra_end_trans(zh);
1977     return sysno;   
1978 }
1979
1980 /* ---------------------------------------------------------------------------
1981   Searching 
1982 */
1983
1984 int zebra_search_PQF (ZebraHandle zh, const char *pqf_query,
1985                       const char *setname)
1986 {
1987     int hits = 0;
1988     Z_RPNQuery *query;
1989     ODR odr = odr_createmem(ODR_ENCODE);
1990     yaz_log(LOG_API,"zebra_search_PQF s=%s q=%s",setname, pqf_query);
1991     
1992     query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
1993     
1994     if (!query)
1995         yaz_log (LOG_WARN, "bad query %s\n", pqf_query);
1996     else
1997         zebra_search_RPN (zh, odr, query, setname, &hits);
1998     
1999     odr_destroy(odr);
2000
2001     return hits;
2002 }
2003
2004 /* ---------------------------------------------------------------------------
2005   Sort - a simplified interface, with optional read locks.
2006   FIXME - This is a horrible name, will conflict with half the applications
2007 */
2008 int sort (ZebraHandle zh, 
2009           ODR stream,
2010           const char *sort_spec,
2011           const char *output_setname,
2012           const char **input_setnames
2013     ) 
2014 {
2015     int num_input_setnames = 0;
2016     int sort_status = 0;
2017     Z_SortKeySpecList *sort_sequence = yaz_sort_spec (stream, sort_spec);
2018     yaz_log(LOG_API,"sort (FIXME) ");
2019     if (!sort_sequence) {
2020         logf(LOG_WARN,"invalid sort specs '%s'", sort_spec);
2021         zh->errCode = 207;
2022     return (-1);
2023     }
2024     
2025     /* we can do this, since the perl typemap code for char** will 
2026        put a NULL at the end of list */
2027     while (input_setnames[num_input_setnames]) num_input_setnames++;
2028
2029     if (zebra_begin_read (zh))
2030         return -1;
2031     
2032     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2033                    output_setname, sort_sequence, &sort_status);
2034     
2035     zebra_end_read(zh);
2036     return (sort_status);
2037 }