Handle non-existant register area better
[idzebra-moved-to-github.git] / index / zebraapi.c
1 /* $Id: zebraapi.c,v 1.102 2003-05-20 21:39:57 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,
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     if (zebra_begin_trans (zh, 1))
1044         return;
1045
1046     zs = zh->service;
1047     /* announce database */
1048     if (zebraExplain_newDatabase (zh->reg->zei, database, 0 
1049                                   /* explainDatabase */))
1050     {
1051         zh->errCode = 224;
1052         zh->errString = "database already exist";
1053     }
1054     zebra_end_trans (zh);
1055 }
1056
1057 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1058                        const char *input_str, int input_len,
1059                        char *output_str, int output_len)
1060 {
1061     WRBUF wrbuf;
1062     ASSERTZH;
1063     zh->errCode=0;
1064     if (!zh->reg->zebra_maps)
1065         return -1;
1066     wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1067                           input_str, input_len);
1068     if (!wrbuf)
1069         return -2;
1070     if (wrbuf_len(wrbuf) >= output_len)
1071         return -3;
1072     if (wrbuf_len(wrbuf))
1073         memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1074     output_str[wrbuf_len(wrbuf)] = '\0';
1075     return wrbuf_len(wrbuf);
1076 }
1077
1078
1079 void zebra_set_state (ZebraHandle zh, int val, int seqno)
1080 {
1081     char state_fname[256];
1082     char *fname;
1083     long p = getpid();
1084     FILE *f;
1085     ASSERTZH;
1086     zh->errCode=0;
1087
1088     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1089     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1090     f = fopen (fname, "w");
1091
1092     yaz_log (LOG_DEBUG, "%c %d %ld", val, seqno, p);
1093     fprintf (f, "%c %d %ld\n", val, seqno, p);
1094     fclose (f);
1095     xfree (fname);
1096 }
1097
1098 void zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1099 {
1100     char state_fname[256];
1101     char *fname;
1102     FILE *f;
1103
1104     ASSERTZH;
1105     zh->errCode=0;
1106     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1107     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1108     f = fopen (fname, "r");
1109     *val = 'o';
1110     *seqno = 0;
1111
1112     if (f)
1113     {
1114         fscanf (f, "%c %d", val, seqno);
1115         fclose (f);
1116     }
1117     xfree (fname);
1118 }
1119
1120 int zebra_begin_read (ZebraHandle zh)
1121 {
1122     return zebra_begin_trans(zh, 0);
1123 }
1124
1125 void zebra_end_read (ZebraHandle zh)
1126 {
1127     zebra_end_trans(zh);
1128 }
1129
1130 int zebra_begin_trans (ZebraHandle zh, int rw)
1131 {
1132     yaz_log(LOG_LOG, "zebra_begin_trans rw=%d trans=%d", rw, zh->trans_no);
1133     if (!zh->res)
1134     {
1135         zh->errCode = 2;
1136         zh->errString = "zebra_begin_trans: no database selected";
1137         return -1;
1138     }
1139     ASSERTZHRES;
1140     assert (zh->res);
1141     if (rw)
1142     {
1143         int pass;
1144         int seqno = 0;
1145         char val = '?';
1146         const char *rval = 0;
1147         
1148         (zh->trans_no++);
1149         if (zh->trans_w_no)
1150             return 0;
1151         if (zh->trans_no != 1)
1152         {
1153             zh->errCode = 2;
1154             zh->errString = "zebra_begin_trans: write trans not allowed within read trans";
1155             return -1;
1156         }
1157         if (zh->reg)
1158             zebra_register_close (zh->service, zh->reg);
1159         
1160         zh->trans_w_no = zh->trans_no;
1161
1162         zh->errCode=0;
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         else
1229         {
1230             zebra_set_state (zh, 'o', seqno);
1231             
1232             zebra_unlock (zh->lock_shadow);
1233             zebra_unlock (zh->lock_normal);
1234
1235             zh->trans_no--;
1236             zh->trans_w_no = 0;
1237
1238             zh->errCode = 2;
1239             zh->errString = "zebra_begin_trans: cannot open register";
1240             yaz_log(LOG_FATAL, zh->errString);
1241             return -1;
1242         }
1243     }
1244     else
1245     {
1246         int dirty = 0;
1247         char val;
1248         int seqno;
1249         
1250         (zh->trans_no)++;
1251         
1252         if (zh->trans_no != 1)
1253         {
1254             zebra_flush_reg (zh);
1255             return 0;
1256         }
1257         zh->errCode=0;
1258 #if HAVE_SYS_TIMES_H
1259         times (&zh->tms1);
1260 #endif
1261         if (!zh->res)
1262         {
1263             (zh->trans_no)--;
1264             zh->errCode = 109;
1265             return -1;
1266         }
1267         if (!zh->lock_normal || !zh->lock_shadow)
1268         {
1269             (zh->trans_no)--;
1270             zh->errCode = 2;
1271             return -1;
1272         }
1273         zebra_get_state (zh, &val, &seqno);
1274         if (val == 'd')
1275             val = 'o';
1276         
1277         if (!zh->reg)
1278             dirty = 1;
1279         else if (seqno != zh->reg->seqno)
1280         {
1281             yaz_log (LOG_LOG, "reopen seqno cur/old %d/%d",
1282                      seqno, zh->reg->seqno);
1283             dirty = 1;
1284         }
1285         else if (zh->reg->last_val != val)
1286         {
1287             yaz_log (LOG_LOG, "reopen last cur/old %d/%d",
1288                      val, zh->reg->last_val);
1289             dirty = 1;
1290         }
1291         if (!dirty)
1292             return 0;
1293         
1294         if (val == 'c')
1295             zebra_lock_r (zh->lock_shadow);
1296         else
1297             zebra_lock_r (zh->lock_normal);
1298         
1299         if (zh->reg)
1300             zebra_register_close (zh->service, zh->reg);
1301         zh->reg = zebra_register_open (zh->service, zh->reg_name,
1302                                        0, val == 'c' ? 1 : 0,
1303                                        zh->res, zh->path_reg);
1304         if (!zh->reg)
1305         {
1306             zebra_unlock (zh->lock_normal);
1307             zebra_unlock (zh->lock_shadow);
1308             zh->trans_no--;
1309             zh->errCode = 109;
1310             return -1;
1311         }
1312         zh->reg->last_val = val;
1313         zh->reg->seqno = seqno;
1314     }
1315     return 0;
1316 }
1317
1318 int zebra_end_trans (ZebraHandle zh)
1319 {
1320     ZebraTransactionStatus dummy;
1321     return zebra_end_transaction(zh, &dummy);
1322 }
1323
1324 int zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1325 {
1326     char val;
1327     int seqno;
1328     const char *rval;
1329
1330     ASSERTZH;
1331
1332     status->processed = 0;
1333     status->inserted  = 0;
1334     status->updated   = 0;
1335     status->deleted   = 0;
1336     status->utime     = 0;
1337     status->stime     = 0;
1338
1339     if (!zh->res || !zh->reg)
1340     {
1341         zh->errCode = 2;
1342         zh->errString = "zebra_end_trans: no open transaction";
1343         return -1;
1344     }
1345     if (zh->trans_no != zh->trans_w_no)
1346     {
1347         zh->trans_no--;
1348         if (zh->trans_no != 0)
1349             return 0;
1350
1351         /* release read lock */
1352
1353         zebra_unlock (zh->lock_normal);
1354         zebra_unlock (zh->lock_shadow);
1355     }
1356     else
1357     {   /* release write lock */
1358         zh->trans_no--;
1359         zh->trans_w_no = 0;
1360         
1361         yaz_log (LOG_LOG, "zebra_end_trans");
1362         rval = res_get (zh->res, "shadow");
1363         
1364         zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1365         
1366         zebra_flush_reg (zh);
1367         
1368         resultSetInvalidate (zh);
1369
1370         zebra_register_close (zh->service, zh->reg);
1371         zh->reg = 0;
1372         
1373         yaz_log (LOG_LOG, "Records: %7d i/u/d %d/%d/%d", 
1374                  zh->records_processed, zh->records_inserted,
1375                  zh->records_updated, zh->records_deleted);
1376         
1377         status->processed = zh->records_processed;
1378         status->inserted = zh->records_inserted;
1379         status->updated = zh->records_updated;
1380         status->deleted = zh->records_deleted;
1381         
1382         zebra_get_state (zh, &val, &seqno);
1383         if (val != 'd')
1384         {
1385             BFiles bfs = bfs_create (rval, zh->path_reg);
1386             yaz_log (LOG_LOG, "deleting shadow stuff val=%c", val);
1387             bf_commitClean (bfs, rval);
1388             bfs_destroy (bfs);
1389         }
1390         if (!rval)
1391             seqno++;
1392         zebra_set_state (zh, 'o', seqno);
1393         
1394         zebra_unlock (zh->lock_shadow);
1395         zebra_unlock (zh->lock_normal);
1396         
1397     }
1398 #if HAVE_SYS_TIMES_H
1399     times (&zh->tms2);
1400     logf (LOG_LOG, "user/system: %ld/%ld",
1401           (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1402           (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1403     
1404     status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1405     status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1406 #endif
1407     return 0;
1408 }
1409
1410 void zebra_repository_update (ZebraHandle zh)
1411 {
1412     ASSERTZH;
1413     zh->errCode=0;
1414     logf (LOG_LOG, "updating %s", zh->rGroup.path);
1415     repositoryUpdate (zh);    
1416 }
1417
1418 void zebra_repository_delete (ZebraHandle zh)
1419 {
1420     ASSERTZH;
1421     zh->errCode=0;
1422     logf (LOG_LOG, "deleting %s", zh->rGroup.path);
1423     repositoryDelete (zh);
1424 }
1425
1426 void zebra_repository_show (ZebraHandle zh)
1427 {
1428     ASSERTZH;
1429     zh->errCode=0;
1430     repositoryShow (zh);
1431 }
1432
1433 static int zebra_commit_ex (ZebraHandle zh, int clean_only)
1434 {
1435     int seqno;
1436     char val;
1437     const char *rval;
1438     BFiles bfs;
1439     ASSERTZH;
1440     zh->errCode=0;
1441
1442     if (!zh->res)
1443     {
1444         zh->errCode = 109;
1445         return -1;
1446     }
1447     rval = res_get (zh->res, "shadow");    
1448     if (!rval)
1449     {
1450         logf (LOG_WARN, "Cannot perform commit");
1451         logf (LOG_WARN, "No shadow area defined");
1452         return 0;
1453     }
1454
1455     zebra_lock_w (zh->lock_normal);
1456     zebra_lock_r (zh->lock_shadow);
1457
1458     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1459
1460     zebra_get_state (zh, &val, &seqno);
1461
1462     if (rval && *rval)
1463         bf_cache (bfs, rval);
1464     if (bf_commitExists (bfs))
1465     {
1466         if (clean_only)
1467             zebra_set_state (zh, 'd', seqno);
1468         else
1469         {
1470             zebra_set_state (zh, 'c', seqno);
1471             
1472             logf (LOG_LOG, "commit start");
1473             bf_commitExec (bfs);
1474 #ifndef WIN32
1475             sync ();
1476 #endif
1477         }
1478         logf (LOG_LOG, "commit clean");
1479         bf_commitClean (bfs, rval);
1480         seqno++;
1481         zebra_set_state (zh, 'o', seqno);
1482     }
1483     else
1484     {
1485         logf (LOG_LOG, "nothing to commit");
1486     }
1487     bfs_destroy (bfs);
1488
1489     zebra_unlock (zh->lock_shadow);
1490     zebra_unlock (zh->lock_normal);
1491     return 0;
1492 }
1493
1494 int zebra_clean (ZebraHandle zh)
1495 {
1496     return zebra_commit_ex(zh, 1);
1497 }
1498
1499 int zebra_commit (ZebraHandle zh)
1500 {
1501     return zebra_commit_ex(zh, 0);
1502 }
1503
1504 int zebra_init (ZebraHandle zh)
1505 {
1506     const char *rval;
1507     BFiles bfs = 0;
1508     ASSERTZH;
1509     zh->errCode=0;
1510
1511     if (!zh->res)
1512     {
1513         zh->errCode = 109;
1514         return -1;
1515     }
1516     rval = res_get (zh->res, "shadow");
1517
1518     bfs = bfs_create (res_get (zh->service->global_res, "register"),
1519                       zh->path_reg);
1520     if (rval && *rval)
1521         bf_cache (bfs, rval);
1522     
1523     bf_reset (bfs);
1524     bfs_destroy (bfs);
1525     zebra_set_state (zh, 'o', 0);
1526     return 0;
1527 }
1528
1529 int zebra_compact (ZebraHandle zh)
1530 {
1531     BFiles bfs;
1532     ASSERTZH;
1533     zh->errCode=0;
1534     if (!zh->res)
1535     {
1536         zh->errCode = 109;
1537         return -1;
1538     }
1539     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1540     inv_compact (bfs);
1541     bfs_destroy (bfs);
1542     return 0;
1543 }
1544
1545 int zebra_record_insert (ZebraHandle zh, const char *buf, int len)
1546 {
1547     int sysno = 0;
1548     ASSERTZH;
1549     zh->errCode=0;
1550     if (zebra_begin_trans (zh, 1))
1551         return 0;
1552     extract_rec_in_mem (zh, "grs.sgml",
1553                         buf, len,
1554                         "Default",  /* database */
1555                         0 /* delete_flag */,
1556                         0 /* test_mode */,
1557                         &sysno /* sysno */,
1558                         1 /* store_keys */,
1559                         1 /* store_data */,
1560                         0 /* match criteria */);
1561     if (zebra_end_trans (zh))
1562         return 0;
1563     return sysno;
1564 }
1565
1566 void zebra_set_group (ZebraHandle zh, struct recordGroup *rg)
1567 {
1568     ASSERTZH;
1569     zh->errCode=0;
1570     memcpy (&zh->rGroup, rg, sizeof(*rg));
1571 }
1572
1573 void zebra_result (ZebraHandle zh, int *code, char **addinfo)
1574 {
1575     ASSERTZH;
1576     *code = zh->errCode;
1577     *addinfo = zh->errString;
1578 }
1579
1580 void zebra_shadow_enable (ZebraHandle zh, int value)
1581 {
1582     ASSERTZH;
1583     zh->errCode=0;
1584     zh->shadow_enable = value;
1585 }
1586
1587 int zebra_record_encoding (ZebraHandle zh, const char *encoding)
1588 {
1589     ASSERTZH;
1590     zh->errCode=0;
1591     xfree (zh->record_encoding);
1592
1593     /*
1594      * Fixme!
1595      */
1596
1597     if (zh->iconv_to_utf8 != 0)
1598         yaz_iconv_close(zh->iconv_to_utf8);
1599     if (zh->iconv_from_utf8 != 0)
1600         yaz_iconv_close(zh->iconv_from_utf8);
1601     
1602     zh->record_encoding = xstrdup (encoding);
1603     
1604     logf(LOG_DEBUG, "Reset record encoding: %s", encoding);
1605     
1606     zh->iconv_to_utf8 =
1607         yaz_iconv_open ("UTF-8", encoding);
1608     if (zh->iconv_to_utf8 == 0)
1609         yaz_log (LOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1610     zh->iconv_from_utf8 =
1611         yaz_iconv_open (encoding, "UTF-8");
1612     if (zh->iconv_to_utf8 == 0)
1613         yaz_log (LOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1614
1615     return 0;
1616 }
1617
1618 void zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1619 {
1620     ASSERTZH;
1621     zh->errCode=0;
1622     res_put(zh->res, name, value);
1623 }
1624
1625 const char *zebra_get_resource(ZebraHandle zh,
1626                                const char *name, const char *defaultvalue)
1627 {
1628     ASSERTZH;
1629     zh->errCode=0;
1630     return res_get_def( zh->res, name, (char *)defaultvalue);
1631 }
1632
1633 /* moved from zebra_api_ext.c by pop */
1634
1635 int zebra_trans_no (ZebraHandle zh) {
1636   return (zh->trans_no);
1637 }
1638
1639
1640
1641 int zebra_get_shadow_enable (ZebraHandle zh) {
1642   return (zh->shadow_enable);
1643 }
1644
1645 void zebra_set_shadow_enable (ZebraHandle zh, int value) {
1646   zh->shadow_enable = value;
1647 }
1648
1649 void init_recordGroup (struct recordGroup *rg) {
1650     rg->groupName = NULL;
1651     rg->databaseName = NULL;
1652     rg->path = NULL;
1653     rg->recordId = NULL;
1654     rg->recordType = NULL;
1655     rg->flagStoreData = -1;
1656     rg->flagStoreKeys = -1; 
1657     rg->flagRw = 1;
1658     rg->databaseNamePath = 0;
1659     rg->explainDatabase = 0; 
1660     rg->fileVerboseLimit = 100000; 
1661     rg->followLinks = -1;
1662
1663
1664
1665 /* This is from extract.c... it seems useful, when extract_rec_in mem is 
1666    called... and in general... Should be moved to somewhere else */
1667 void res_get_recordGroup (ZebraHandle zh,
1668                           struct recordGroup *rGroup,
1669                           const char *ext) {
1670   char gprefix[128];
1671   char ext_res[128]; 
1672     
1673   if (!rGroup->groupName || !*rGroup->groupName)
1674     *gprefix = '\0';
1675   else 
1676     sprintf (gprefix, "%s.", rGroup->groupName);
1677   
1678   /* determine file type - depending on extension */
1679   if (!rGroup->recordType) {
1680     sprintf (ext_res, "%srecordType.%s", gprefix, ext);
1681     if (!(rGroup->recordType = res_get (zh->res, ext_res))) {
1682       sprintf (ext_res, "%srecordType", gprefix);
1683       rGroup->recordType = res_get (zh->res, ext_res);
1684     }
1685   }
1686   /* determine match criteria */
1687   if (!rGroup->recordId) { 
1688     sprintf (ext_res, "%srecordId.%s", gprefix, ext);
1689     if (!(rGroup->recordId = res_get (zh->res, ext_res))) {
1690       sprintf (ext_res, "%srecordId", gprefix);
1691       rGroup->recordId = res_get (zh->res, ext_res);
1692     }
1693   } 
1694   
1695   /* determine database name */
1696   if (!rGroup->databaseName) {
1697     sprintf (ext_res, "%sdatabase.%s", gprefix, ext);
1698     if (!(rGroup->databaseName = res_get (zh->res, ext_res))) { 
1699       sprintf (ext_res, "%sdatabase", gprefix);
1700       rGroup->databaseName = res_get (zh->res, ext_res);
1701     }
1702   }
1703   if (!rGroup->databaseName)
1704     rGroup->databaseName = "Default";
1705
1706   /* determine if explain database */
1707   sprintf (ext_res, "%sexplainDatabase", gprefix);
1708   rGroup->explainDatabase =
1709     atoi (res_get_def (zh->res, ext_res, "0"));
1710
1711   /* storeData */
1712   if (rGroup->flagStoreData == -1) {
1713     const char *sval;
1714     sprintf (ext_res, "%sstoreData.%s", gprefix, ext);
1715     if (!(sval = res_get (zh->res, ext_res))) {
1716       sprintf (ext_res, "%sstoreData", gprefix);
1717       sval = res_get (zh->res, ext_res);
1718     }
1719     if (sval)
1720       rGroup->flagStoreData = atoi (sval);
1721   }
1722   if (rGroup->flagStoreData == -1)  rGroup->flagStoreData = 0;
1723
1724   /* storeKeys */
1725   if (rGroup->flagStoreKeys == -1)  {
1726     const char *sval;
1727     
1728     sprintf (ext_res, "%sstoreKeys.%s", gprefix, ext);
1729     sval = res_get (zh->res, ext_res);
1730     if (!sval) {
1731       sprintf (ext_res, "%sstoreKeys", gprefix);
1732       sval = res_get (zh->res, ext_res);
1733     }
1734     if (!sval)  sval = res_get (zh->res, "storeKeys");
1735     if (sval) rGroup->flagStoreKeys = atoi (sval);
1736   }
1737   if (rGroup->flagStoreKeys == -1) rGroup->flagStoreKeys = 0;
1738   
1739
1740
1741
1742 /* almost the same as zebra_records_retrieve ... but how did it work? 
1743    I mean for multiple records ??? CHECK ??? */
1744 void api_records_retrieve (ZebraHandle zh, ODR stream,
1745                            const char *setname, Z_RecordComposition *comp,
1746                            oid_value input_format, int num_recs,
1747                            ZebraRetrievalRecord *recs)
1748 {
1749     ZebraPosSet poset;
1750     int i, *pos_array;
1751
1752     if (!zh->res)
1753     {
1754         zh->errCode = 30;
1755         zh->errString = odr_strdup (stream, setname);
1756         return;
1757     }
1758     
1759     zh->errCode = 0; 
1760
1761     if (zebra_begin_read (zh))
1762         return;
1763
1764     pos_array = (int *) xmalloc (num_recs * sizeof(*pos_array));
1765     for (i = 0; i<num_recs; i++)
1766         pos_array[i] = recs[i].position;
1767     poset = zebraPosSetCreate (zh, setname, num_recs, pos_array);
1768     if (!poset)
1769     {
1770         logf (LOG_DEBUG, "zebraPosSetCreate error");
1771         zh->errCode = 30;
1772         zh->errString = nmem_strdup (stream->mem, setname);
1773     }
1774     else
1775     {
1776         for (i = 0; i<num_recs; i++)
1777         {
1778             if (poset[i].term)
1779             {
1780                 recs[i].errCode = 0;
1781                 recs[i].format = VAL_SUTRS;
1782                 recs[i].len = strlen(poset[i].term);
1783                 recs[i].buf = poset[i].term;
1784                 recs[i].base = poset[i].db;
1785                 recs[i].sysno = 0;
1786             
1787             }
1788             else if (poset[i].sysno)
1789             {
1790               /* changed here ??? CHECK ??? */
1791               char *b;
1792                 recs[i].errCode =
1793                     zebra_record_fetch (zh, poset[i].sysno, poset[i].score,
1794                                         stream, input_format, comp,
1795                                         &recs[i].format, 
1796                                         &b,
1797                                         &recs[i].len,
1798                                         &recs[i].base);
1799                 recs[i].buf = (char *) odr_malloc(stream,recs[i].len);
1800                 memcpy(recs[i].buf, b, recs[i].len);
1801                 recs[i].errString = 0; /* Hmmm !!! we should get this */ 
1802                 recs[i].sysno = poset[i].sysno;
1803                 recs[i].score = poset[i].score;
1804             }
1805             else
1806             {
1807                 char num_str[20];
1808
1809                 sprintf (num_str, "%d", pos_array[i]);  
1810                 zh->errCode = 13;
1811                 zh->errString = odr_strdup (stream, num_str);
1812                 break;
1813             }
1814
1815         }
1816         zebraPosSetDestroy (zh, poset, num_recs);
1817     }
1818     zebra_end_read (zh);
1819     xfree (pos_array);
1820 }
1821
1822
1823 /* ---------------------------------------------------------------------------
1824   Record insert(=update), delete 
1825
1826   If sysno is provided, then it's used to identify the reocord.
1827   If not, and match_criteria is provided, then sysno is guessed
1828   If not, and a record is provided, then sysno is got from there
1829 */
1830
1831 int zebra_insert_record (ZebraHandle zh, 
1832                          struct recordGroup *rGroup,
1833                          const char *recordType,
1834                          int sysno, const char *match, const char *fname,
1835                          const char *buf, int buf_size,
1836                          int force_update) /* This one is ignored */
1837  
1838 {
1839     int res;
1840
1841     if (buf_size < 1) buf_size = strlen(buf);
1842
1843     zebra_begin_trans(zh, 1);
1844     res=bufferExtractRecord (zh, buf, buf_size, rGroup, 
1845                              0, /* delete_flag  */
1846                              0, /* test_mode */
1847                              recordType,
1848                              &sysno,   
1849                              match, fname,
1850                              force_update, 
1851                              0); /* allow_update */
1852     zebra_end_trans(zh); 
1853     if (res < 0) return (res);
1854     return sysno; 
1855 }
1856
1857 int zebra_update_record (ZebraHandle zh, 
1858                          struct recordGroup *rGroup,
1859                          const char *recordType,
1860                          int sysno, const char *match, const char *fname,
1861                          const char *buf, int buf_size,
1862                          int force_update)
1863
1864 {
1865     int res;
1866
1867     if (buf_size < 1) buf_size = strlen(buf);
1868
1869     zebra_begin_trans(zh, 1);
1870     res=bufferExtractRecord (zh, buf, buf_size, rGroup, 
1871                              0, /* delete_flag */
1872                              0, /* test_mode */
1873                              recordType,
1874                              &sysno,   
1875                              match, fname,
1876                              force_update, 
1877                              1); /* allow_update */
1878     zebra_end_trans(zh); 
1879     return sysno; 
1880 }
1881
1882
1883
1884 int zebra_delete_record (ZebraHandle zh, 
1885                          struct recordGroup *rGroup, 
1886                          const char *recordType,
1887                          int sysno, const char *match, const char *fname,
1888                          const char *buf, int buf_size,
1889                          int force_update) 
1890 {
1891     int res;
1892
1893     if (buf_size < 1) buf_size = strlen(buf);
1894
1895     zebra_begin_trans(zh, 1);
1896     res=bufferExtractRecord (zh, buf, buf_size, rGroup, 
1897                              1, /* delete_flag */
1898                              0, /* test_mode */
1899                              recordType,
1900                              &sysno,
1901                              match,fname,
1902                              force_update,
1903                              1); /* allow_update */
1904     zebra_end_trans(zh);
1905     return sysno;   
1906 }
1907
1908 /* ---------------------------------------------------------------------------
1909   Searching 
1910
1911   zebra_search_RPN is the same as zebra_search_rpn, except that read locking
1912   is not mandatory. (it's repeatable now, also in zebraapi.c)
1913 */
1914
1915 int zebra_search_PQF (ZebraHandle zh, const char *pqf_query,
1916                       const char *setname)
1917 {
1918     int hits = 0;
1919     Z_RPNQuery *query;
1920     ODR odr = odr_createmem(ODR_ENCODE);
1921     
1922     query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
1923     
1924     if (!query)
1925         yaz_log (LOG_WARN, "bad query %s\n", pqf_query);
1926     else
1927         zebra_search_RPN (zh, query, setname, &hits);
1928     
1929     odr_destroy(odr);
1930
1931     return hits;
1932 }
1933
1934 /* ---------------------------------------------------------------------------
1935   Sort - a simplified interface, with optional read locks.
1936 */
1937 int sort (ZebraHandle zh, 
1938           ODR stream,
1939           const char *sort_spec,
1940           const char *output_setname,
1941           const char **input_setnames
1942     ) 
1943 {
1944     int num_input_setnames = 0;
1945     int sort_status = 0;
1946     Z_SortKeySpecList *sort_sequence = yaz_sort_spec (stream, sort_spec);
1947     if (!sort_sequence) {
1948         logf(LOG_WARN,"invalid sort specs '%s'", sort_spec);
1949         zh->errCode = 207;
1950     return (-1);
1951     }
1952     
1953     /* we can do this, since the perl typemap code for char** will 
1954        put a NULL at the end of list */
1955     while (input_setnames[num_input_setnames]) num_input_setnames++;
1956
1957     if (zebra_begin_read (zh))
1958         return -1;
1959     
1960     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
1961                    output_setname, sort_sequence, &sort_status);
1962     
1963     zebra_end_read(zh);
1964     return (sort_status);
1965 }