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