Handle no database selected in zebra_begin_trans
[idzebra-moved-to-github.git] / index / zebraapi.c
1 /* $Id: zebraapi.c,v 1.98 2003-04-24 19:46:59 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_DEBUG, "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_DEBUG, "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, decode, stream, 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_admin_create (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         zh->trans_w_no = zh->trans_no;
1156
1157         zh->errCode=0;
1158         
1159         yaz_log (LOG_LOG, "zebra_begin_trans");
1160         
1161         zh->records_inserted = 0;
1162         zh->records_updated = 0;
1163         zh->records_deleted = 0;
1164         zh->records_processed = 0;
1165         
1166 #if HAVE_SYS_TIMES_H
1167         times (&zh->tms1);
1168 #endif
1169         /* lock */
1170         if (zh->shadow_enable)
1171             rval = res_get (zh->res, "shadow");
1172         
1173         for (pass = 0; pass < 2; pass++)
1174         {
1175             if (rval)
1176             {
1177                 zebra_lock_r (zh->lock_normal);
1178                 zebra_lock_w (zh->lock_shadow);
1179             }
1180             else
1181             {
1182                 zebra_lock_w (zh->lock_normal);
1183                 zebra_lock_w (zh->lock_shadow);
1184             }
1185             
1186             zebra_get_state (zh, &val, &seqno);
1187             if (val == 'c')
1188             {
1189                 yaz_log (LOG_LOG, "previous transaction didn't finish commit");
1190                 zebra_unlock (zh->lock_shadow);
1191                 zebra_unlock (zh->lock_normal);
1192                 zebra_commit (zh);
1193                 continue;
1194             }
1195             else if (val == 'd')
1196             {
1197                 if (rval)
1198                 {
1199                     BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1200                                              zh->path_reg);
1201                     yaz_log (LOG_LOG, "previous transaction didn't reach commit");
1202                     bf_commitClean (bfs, rval);
1203                     bfs_destroy (bfs);
1204             }
1205                 else
1206                 {
1207                     yaz_log (LOG_WARN, "your previous transaction didn't finish");
1208                 }
1209             }
1210             break;
1211         }
1212         if (pass == 2)
1213         {
1214             yaz_log (LOG_FATAL, "zebra_begin_trans couldn't finish commit");
1215             abort();
1216             return -1;
1217         }
1218         zebra_set_state (zh, 'd', seqno);
1219         
1220         zh->reg = zebra_register_open (zh->service, zh->reg_name,
1221                                        1, rval ? 1 : 0, zh->res,
1222                                        zh->path_reg);
1223         if (zh->reg)
1224             zh->reg->seqno = seqno;
1225     }
1226     else
1227     {
1228         int dirty = 0;
1229         char val;
1230         int seqno;
1231         
1232         (zh->trans_no)++;
1233         
1234         if (zh->trans_no != 1)
1235         {
1236             zebra_flush_reg (zh);
1237             return 0;
1238         }
1239         zh->errCode=0;
1240 #if HAVE_SYS_TIMES_H
1241         times (&zh->tms1);
1242 #endif
1243         if (!zh->res)
1244         {
1245             (zh->trans_no)--;
1246             zh->errCode = 109;
1247             return -1;
1248         }
1249         if (!zh->lock_normal || !zh->lock_shadow)
1250         {
1251             (zh->trans_no)--;
1252             zh->errCode = 2;
1253             return -1;
1254         }
1255         zebra_get_state (zh, &val, &seqno);
1256         if (val == 'd')
1257             val = 'o';
1258         
1259         if (!zh->reg)
1260             dirty = 1;
1261         else if (seqno != zh->reg->seqno)
1262         {
1263             yaz_log (LOG_LOG, "reopen seqno cur/old %d/%d",
1264                      seqno, zh->reg->seqno);
1265             dirty = 1;
1266         }
1267         else if (zh->reg->last_val != val)
1268         {
1269             yaz_log (LOG_LOG, "reopen last cur/old %d/%d",
1270                      val, zh->reg->last_val);
1271             dirty = 1;
1272         }
1273         if (!dirty)
1274             return 0;
1275         
1276         if (val == 'c')
1277             zebra_lock_r (zh->lock_shadow);
1278         else
1279             zebra_lock_r (zh->lock_normal);
1280         
1281         if (zh->reg)
1282             zebra_register_close (zh->service, zh->reg);
1283         zh->reg = zebra_register_open (zh->service, zh->reg_name,
1284                                        0, val == 'c' ? 1 : 0,
1285                                        zh->res, zh->path_reg);
1286         if (!zh->reg)
1287         {
1288             zh->errCode = 109;
1289             return -1;
1290         }
1291         zh->reg->last_val = val;
1292         zh->reg->seqno = seqno;
1293     }
1294     return 0;
1295 }
1296
1297 int zebra_end_trans (ZebraHandle zh)
1298 {
1299     ZebraTransactionStatus dummy;
1300     return zebra_end_transaction(zh, &dummy);
1301 }
1302
1303 int zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1304 {
1305     char val;
1306     int seqno;
1307     const char *rval;
1308
1309     ASSERTZH;
1310
1311     status->processed = 0;
1312     status->inserted  = 0;
1313     status->updated   = 0;
1314     status->deleted   = 0;
1315     status->utime     = 0;
1316     status->stime     = 0;
1317
1318     if (!zh->res || !zh->reg)
1319     {
1320         zh->errCode = 2;
1321         zh->errString = "zebra_end_trans: no open transaction";
1322         return -1;
1323     }
1324     if (zh->trans_no != zh->trans_w_no)
1325     {
1326         zh->trans_no--;
1327         if (zh->trans_no != 0)
1328             return 0;
1329
1330         /* release read lock */
1331
1332         zebra_unlock (zh->lock_normal);
1333         zebra_unlock (zh->lock_shadow);
1334     }
1335     else
1336     {   /* release write lock */
1337         zh->trans_no--;
1338         zh->trans_w_no = 0;
1339         
1340         yaz_log (LOG_LOG, "zebra_end_trans");
1341         rval = res_get (zh->res, "shadow");
1342         
1343         zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1344         
1345         zebra_flush_reg (zh);
1346         
1347         zebra_register_close (zh->service, zh->reg);
1348         zh->reg = 0;
1349         
1350         yaz_log (LOG_LOG, "Records: %7d i/u/d %d/%d/%d", 
1351                  zh->records_processed, zh->records_inserted,
1352                  zh->records_updated, zh->records_deleted);
1353         
1354         status->processed = zh->records_processed;
1355         status->inserted = zh->records_inserted;
1356         status->updated = zh->records_updated;
1357         status->deleted = zh->records_deleted;
1358         
1359         zebra_get_state (zh, &val, &seqno);
1360         if (val != 'd')
1361         {
1362             BFiles bfs = bfs_create (rval, zh->path_reg);
1363             yaz_log (LOG_LOG, "deleting shadow stuff val=%c", val);
1364             bf_commitClean (bfs, rval);
1365             bfs_destroy (bfs);
1366         }
1367         if (!rval)
1368             seqno++;
1369         zebra_set_state (zh, 'o', seqno);
1370         
1371         zebra_unlock (zh->lock_shadow);
1372         zebra_unlock (zh->lock_normal);
1373         
1374     }
1375 #if HAVE_SYS_TIMES_H
1376     times (&zh->tms2);
1377     logf (LOG_LOG, "user/system: %ld/%ld",
1378           (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1379           (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1380     
1381     status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1382     status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1383 #endif
1384     return 0;
1385 }
1386
1387 void zebra_repository_update (ZebraHandle zh)
1388 {
1389     ASSERTZH;
1390     zh->errCode=0;
1391     logf (LOG_LOG, "updating %s", zh->rGroup.path);
1392     repositoryUpdate (zh);    
1393 }
1394
1395 void zebra_repository_delete (ZebraHandle zh)
1396 {
1397     ASSERTZH;
1398     zh->errCode=0;
1399     logf (LOG_LOG, "deleting %s", zh->rGroup.path);
1400     repositoryDelete (zh);
1401 }
1402
1403 void zebra_repository_show (ZebraHandle zh)
1404 {
1405     ASSERTZH;
1406     zh->errCode=0;
1407     repositoryShow (zh);
1408 }
1409
1410 static int zebra_commit_ex (ZebraHandle zh, int clean_only)
1411 {
1412     int seqno;
1413     char val;
1414     const char *rval;
1415     BFiles bfs;
1416     ASSERTZH;
1417     zh->errCode=0;
1418
1419     if (!zh->res)
1420     {
1421         zh->errCode = 109;
1422         return -1;
1423     }
1424     rval = res_get (zh->res, "shadow");    
1425     if (!rval)
1426     {
1427         logf (LOG_WARN, "Cannot perform commit");
1428         logf (LOG_WARN, "No shadow area defined");
1429         return 0;
1430     }
1431
1432     zebra_lock_w (zh->lock_normal);
1433     zebra_lock_r (zh->lock_shadow);
1434
1435     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1436
1437     zebra_get_state (zh, &val, &seqno);
1438
1439     if (rval && *rval)
1440         bf_cache (bfs, rval);
1441     if (bf_commitExists (bfs))
1442     {
1443         if (clean_only)
1444             zebra_set_state (zh, 'd', seqno);
1445         else
1446         {
1447             zebra_set_state (zh, 'c', seqno);
1448             
1449             logf (LOG_LOG, "commit start");
1450             bf_commitExec (bfs);
1451 #ifndef WIN32
1452             sync ();
1453 #endif
1454         }
1455         logf (LOG_LOG, "commit clean");
1456         bf_commitClean (bfs, rval);
1457         seqno++;
1458         zebra_set_state (zh, 'o', seqno);
1459     }
1460     else
1461     {
1462         logf (LOG_LOG, "nothing to commit");
1463     }
1464     bfs_destroy (bfs);
1465
1466     zebra_unlock (zh->lock_shadow);
1467     zebra_unlock (zh->lock_normal);
1468     return 0;
1469 }
1470
1471 int zebra_clean (ZebraHandle zh)
1472 {
1473     return zebra_commit_ex(zh, 1);
1474 }
1475
1476 int zebra_commit (ZebraHandle zh)
1477 {
1478     return zebra_commit_ex(zh, 0);
1479 }
1480
1481 int zebra_init (ZebraHandle zh)
1482 {
1483     const char *rval;
1484     BFiles bfs = 0;
1485     ASSERTZH;
1486     zh->errCode=0;
1487
1488     if (!zh->res)
1489     {
1490         zh->errCode = 109;
1491         return -1;
1492     }
1493     rval = res_get (zh->res, "shadow");
1494
1495     bfs = bfs_create (res_get (zh->service->global_res, "register"),
1496                       zh->path_reg);
1497     if (rval && *rval)
1498         bf_cache (bfs, rval);
1499     
1500     bf_reset (bfs);
1501     bfs_destroy (bfs);
1502     zebra_set_state (zh, 'o', 0);
1503     return 0;
1504 }
1505
1506 int zebra_compact (ZebraHandle zh)
1507 {
1508     BFiles bfs;
1509     ASSERTZH;
1510     zh->errCode=0;
1511     if (!zh->res)
1512     {
1513         zh->errCode = 109;
1514         return -1;
1515     }
1516     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1517     inv_compact (bfs);
1518     bfs_destroy (bfs);
1519     return 0;
1520 }
1521
1522 int zebra_record_insert (ZebraHandle zh, const char *buf, int len)
1523 {
1524     int sysno = 0;
1525     ASSERTZH;
1526     zh->errCode=0;
1527     if (zebra_begin_trans (zh, 1))
1528         return 0;
1529     extract_rec_in_mem (zh, "grs.sgml",
1530                         buf, len,
1531                         "Default",  /* database */
1532                         0 /* delete_flag */,
1533                         0 /* test_mode */,
1534                         &sysno /* sysno */,
1535                         1 /* store_keys */,
1536                         1 /* store_data */,
1537                         0 /* match criteria */);
1538     if (zebra_end_trans (zh))
1539         return 0;
1540     return sysno;
1541 }
1542
1543 void zebra_set_group (ZebraHandle zh, struct recordGroup *rg)
1544 {
1545     ASSERTZH;
1546     zh->errCode=0;
1547     memcpy (&zh->rGroup, rg, sizeof(*rg));
1548 }
1549
1550 void zebra_result (ZebraHandle zh, int *code, char **addinfo)
1551 {
1552     ASSERTZH;
1553     *code = zh->errCode;
1554     *addinfo = zh->errString;
1555 }
1556
1557 void zebra_shadow_enable (ZebraHandle zh, int value)
1558 {
1559     ASSERTZH;
1560     zh->errCode=0;
1561     zh->shadow_enable = value;
1562 }
1563
1564 int zebra_record_encoding (ZebraHandle zh, const char *encoding)
1565 {
1566     ASSERTZH;
1567     zh->errCode=0;
1568     xfree (zh->record_encoding);
1569
1570     /*
1571      * Fixme!
1572      */
1573
1574     if (zh->iconv_to_utf8 != 0)
1575         yaz_iconv_close(zh->iconv_to_utf8);
1576     if (zh->iconv_from_utf8 != 0)
1577         yaz_iconv_close(zh->iconv_from_utf8);
1578     
1579     zh->record_encoding = xstrdup (encoding);
1580     
1581     logf(LOG_DEBUG, "Reset record encoding: %s", encoding);
1582     
1583     zh->iconv_to_utf8 =
1584         yaz_iconv_open ("UTF-8", encoding);
1585     if (zh->iconv_to_utf8 == 0)
1586         yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1587     zh->iconv_from_utf8 =
1588         yaz_iconv_open (encoding, "UTF-8");
1589     if (zh->iconv_to_utf8 == 0)
1590         yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1591
1592     return 0;
1593 }
1594
1595 void zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1596 {
1597     ASSERTZH;
1598     zh->errCode=0;
1599     res_put(zh->res, name, value);
1600 }
1601
1602 const char *zebra_get_resource(ZebraHandle zh,
1603                                const char *name, const char *defaultvalue)
1604 {
1605     ASSERTZH;
1606     zh->errCode=0;
1607     return res_get_def( zh->res, name, (char *)defaultvalue);
1608 }
1609
1610 /* moved from zebra_api_ext.c by pop */
1611
1612 int zebra_trans_no (ZebraHandle zh) {
1613   return (zh->trans_no);
1614 }
1615
1616
1617
1618 int zebra_get_shadow_enable (ZebraHandle zh) {
1619   return (zh->shadow_enable);
1620 }
1621
1622 void zebra_set_shadow_enable (ZebraHandle zh, int value) {
1623   zh->shadow_enable = value;
1624 }
1625
1626 void init_recordGroup (struct recordGroup *rg) {
1627     rg->groupName = NULL;
1628     rg->databaseName = NULL;
1629     rg->path = NULL;
1630     rg->recordId = NULL;
1631     rg->recordType = NULL;
1632     rg->flagStoreData = -1;
1633     rg->flagStoreKeys = -1; 
1634     rg->flagRw = 1;
1635     rg->databaseNamePath = 0;
1636     rg->explainDatabase = 0; 
1637     rg->fileVerboseLimit = 100000; 
1638     rg->followLinks = -1;
1639
1640
1641
1642 /* This is from extract.c... it seems useful, when extract_rec_in mem is 
1643    called... and in general... Should be moved to somewhere else */
1644 void res_get_recordGroup (ZebraHandle zh,
1645                           struct recordGroup *rGroup,
1646                           const char *ext) {
1647   char gprefix[128];
1648   char ext_res[128]; 
1649     
1650   if (!rGroup->groupName || !*rGroup->groupName)
1651     *gprefix = '\0';
1652   else 
1653     sprintf (gprefix, "%s.", rGroup->groupName);
1654   
1655   /* determine file type - depending on extension */
1656   if (!rGroup->recordType) {
1657     sprintf (ext_res, "%srecordType.%s", gprefix, ext);
1658     if (!(rGroup->recordType = res_get (zh->res, ext_res))) {
1659       sprintf (ext_res, "%srecordType", gprefix);
1660       rGroup->recordType = res_get (zh->res, ext_res);
1661     }
1662   }
1663   /* determine match criteria */
1664   if (!rGroup->recordId) { 
1665     sprintf (ext_res, "%srecordId.%s", gprefix, ext);
1666     if (!(rGroup->recordId = res_get (zh->res, ext_res))) {
1667       sprintf (ext_res, "%srecordId", gprefix);
1668       rGroup->recordId = res_get (zh->res, ext_res);
1669     }
1670   } 
1671   
1672   /* determine database name */
1673   if (!rGroup->databaseName) {
1674     sprintf (ext_res, "%sdatabase.%s", gprefix, ext);
1675     if (!(rGroup->databaseName = res_get (zh->res, ext_res))) { 
1676       sprintf (ext_res, "%sdatabase", gprefix);
1677       rGroup->databaseName = res_get (zh->res, ext_res);
1678     }
1679   }
1680   if (!rGroup->databaseName)
1681     rGroup->databaseName = "Default";
1682
1683   /* determine if explain database */
1684   sprintf (ext_res, "%sexplainDatabase", gprefix);
1685   rGroup->explainDatabase =
1686     atoi (res_get_def (zh->res, ext_res, "0"));
1687
1688   /* storeData */
1689   if (rGroup->flagStoreData == -1) {
1690     const char *sval;
1691     sprintf (ext_res, "%sstoreData.%s", gprefix, ext);
1692     if (!(sval = res_get (zh->res, ext_res))) {
1693       sprintf (ext_res, "%sstoreData", gprefix);
1694       sval = res_get (zh->res, ext_res);
1695     }
1696     if (sval)
1697       rGroup->flagStoreData = atoi (sval);
1698   }
1699   if (rGroup->flagStoreData == -1)  rGroup->flagStoreData = 0;
1700
1701   /* storeKeys */
1702   if (rGroup->flagStoreKeys == -1)  {
1703     const char *sval;
1704     
1705     sprintf (ext_res, "%sstoreKeys.%s", gprefix, ext);
1706     sval = res_get (zh->res, ext_res);
1707     if (!sval) {
1708       sprintf (ext_res, "%sstoreKeys", gprefix);
1709       sval = res_get (zh->res, ext_res);
1710     }
1711     if (!sval)  sval = res_get (zh->res, "storeKeys");
1712     if (sval) rGroup->flagStoreKeys = atoi (sval);
1713   }
1714   if (rGroup->flagStoreKeys == -1) rGroup->flagStoreKeys = 0;
1715   
1716
1717
1718
1719 /* almost the same as zebra_records_retrieve ... but how did it work? 
1720    I mean for multiple records ??? CHECK ??? */
1721 void api_records_retrieve (ZebraHandle zh, ODR stream,
1722                            const char *setname, Z_RecordComposition *comp,
1723                            oid_value input_format, int num_recs,
1724                            ZebraRetrievalRecord *recs)
1725 {
1726     ZebraPosSet poset;
1727     int i, *pos_array;
1728
1729     if (!zh->res)
1730     {
1731         zh->errCode = 30;
1732         zh->errString = odr_strdup (stream, setname);
1733         return;
1734     }
1735     
1736     zh->errCode = 0; 
1737
1738     if (zebra_begin_read (zh))
1739         return;
1740
1741     pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
1742     for (i = 0; i<num_recs; i++)
1743         pos_array[i] = recs[i].position;
1744     poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
1745     if (!poset)
1746     {
1747         logf (LOG_DEBUG, "zebraPosSetCreate error");
1748         zh->errCode = 30;
1749         zh->errString = nmem_strdup (stream->mem, setname);
1750     }
1751     else
1752     {
1753         for (i = 0; i<num_recs; i++)
1754         {
1755             if (poset[i].term)
1756             {
1757                 recs[i].errCode = 0;
1758                 recs[i].format = VAL_SUTRS;
1759                 recs[i].len = strlen(poset[i].term);
1760                 recs[i].buf = poset[i].term;
1761                 recs[i].base = poset[i].db;
1762                 recs[i].sysno = 0;
1763             
1764             }
1765             else if (poset[i].sysno)
1766             {
1767               /* changed here ??? CHECK ??? */
1768               char *b;
1769                 recs[i].errCode =
1770                     zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
1771                                         stream, input_format, comp,
1772                                         &recs[i].format, 
1773                                         &b,
1774                                         &recs[i].len,
1775                                         &recs[i].base);
1776                 recs[i].buf = (char *) odr_malloc(stream,recs[i].len);
1777                 memcpy(recs[i].buf, b, recs[i].len);
1778                 recs[i].errString = 0; /* Hmmm !!! we should get this */ 
1779                 recs[i].sysno = poset[i].sysno;
1780                 recs[i].score = poset[i].score;
1781             }
1782             else
1783             {
1784                 char num_str[20];
1785
1786                 sprintf (num_str, "%d", pos_array[i]);  
1787                 zh->errCode = 13;
1788                 zh->errString = odr_strdup (stream, num_str);
1789                 break;
1790             }
1791
1792         }
1793         zebraPosSetDestroy (zh, poset, num_recs);
1794     }
1795     zebra_end_read (zh);
1796     xfree (pos_array);
1797 }
1798
1799
1800 /* ---------------------------------------------------------------------------
1801   Record insert(=update), delete 
1802
1803   If sysno is provided, then it's used to identify the reocord.
1804   If not, and match_criteria is provided, then sysno is guessed
1805   If not, and a record is provided, then sysno is got from there
1806 */
1807
1808 int zebra_insert_record (ZebraHandle zh, 
1809                          struct recordGroup *rGroup,
1810                          const char *recordType,
1811                          int sysno, const char *match, const char *fname,
1812                          const char *buf, int buf_size,
1813                          int force_update) /* This one is ignored */
1814  
1815 {
1816     int res;
1817
1818     if (buf_size < 1) buf_size = strlen(buf);
1819
1820     zebra_begin_trans(zh, 1);
1821     res=bufferExtractRecord (zh, buf, buf_size, rGroup, 
1822                              0, /* delete_flag  */
1823                              0, /* test_mode */
1824                              recordType,
1825                              &sysno,   
1826                              match, fname,
1827                              force_update, 
1828                              0); /* allow_update */
1829     zebra_end_trans(zh); 
1830     if (res < 0) return (res);
1831     return sysno; 
1832 }
1833
1834 int zebra_update_record (ZebraHandle zh, 
1835                          struct recordGroup *rGroup,
1836                          const char *recordType,
1837                          int sysno, const char *match, const char *fname,
1838                          const char *buf, int buf_size,
1839                          int force_update)
1840
1841 {
1842     int res;
1843
1844     if (buf_size < 1) buf_size = strlen(buf);
1845
1846     zebra_begin_trans(zh, 1);
1847     res=bufferExtractRecord (zh, buf, buf_size, rGroup, 
1848                              0, /* delete_flag */
1849                              0, /* test_mode */
1850                              recordType,
1851                              &sysno,   
1852                              match, fname,
1853                              force_update, 
1854                              1); /* allow_update */
1855     zebra_end_trans(zh); 
1856     return sysno; 
1857 }
1858
1859
1860
1861 int zebra_delete_record (ZebraHandle zh, 
1862                          struct recordGroup *rGroup, 
1863                          const char *recordType,
1864                          int sysno, const char *match, const char *fname,
1865                          const char *buf, int buf_size,
1866                          int force_update) 
1867 {
1868     int res;
1869
1870     if (buf_size < 1) buf_size = strlen(buf);
1871
1872     zebra_begin_trans(zh, 1);
1873     res=bufferExtractRecord (zh, buf, buf_size, rGroup, 
1874                              1, /* delete_flag */
1875                              0, /* test_mode */
1876                              recordType,
1877                              &sysno,
1878                              match,fname,
1879                              force_update,
1880                              1); /* allow_update */
1881     zebra_end_trans(zh);
1882     return sysno;   
1883 }
1884
1885 /* ---------------------------------------------------------------------------
1886   Searching 
1887
1888   zebra_search_RPN is the same as zebra_search_rpn, except that read locking
1889   is not mandatory. (it's repeatable now, also in zebraapi.c)
1890 */
1891
1892 void zebra_search_RPN (ZebraHandle zh, ODR decode, ODR stream,
1893                        Z_RPNQuery *query, const char *setname, int *hits)
1894 {
1895     zh->hits = 0;
1896     *hits = 0;
1897
1898     if (zebra_begin_read (zh))
1899         return;
1900     resultSetAddRPN (zh, decode, stream, query, 
1901                      zh->num_basenames, zh->basenames, setname);
1902
1903     zebra_end_read (zh);
1904
1905     *hits = zh->hits;
1906 }
1907
1908 int zebra_search_PQF (ZebraHandle zh, 
1909                       ODR odr_input, ODR odr_output, 
1910                       const char *pqf_query,
1911                       const char *setname)
1912     
1913 {
1914     int hits;
1915     Z_RPNQuery *query;
1916     query = p_query_rpn (odr_input, PROTO_Z3950, pqf_query);
1917     
1918     if (!query) {
1919         logf (LOG_WARN, "bad query %s\n", pqf_query);
1920         odr_reset (odr_input);
1921         return(0);
1922     }
1923     zebra_search_RPN (zh, odr_input, odr_output, query, setname, &hits);
1924     
1925     odr_reset (odr_input);
1926     odr_reset (odr_output);
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 }