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